private String getFormDirUri(Path formPath) {
    String fileName = formPath.getFileName();
    try {
      fileName = URIUtil.encodeQuery(fileName);
    } catch (Exception e) {

    }
    return formPath.toURI().substring(0, formPath.toURI().lastIndexOf(fileName) - 1);
  }
  @Override
  public void create(
      final Package pkg, final String baseFileName, final NewResourcePresenter presenter) {
    busyIndicatorView.showBusyIndicator(ScoreCardXLSEditorConstants.INSTANCE.Uploading());

    final Path path = pkg.getPackageMainResourcesPath();
    final String fileName = buildFileName(resourceType, baseFileName);
    final Path newPath =
        PathFactory.newPath(
            path.getFileSystem(), fileName, URL.encode(path.toURI() + "/" + fileName));

    uploadWidget.submit(
        path,
        fileName,
        URLHelper.getServletUrl(),
        new Command() {

          @Override
          public void execute() {
            busyIndicatorView.hideBusyIndicator();
            presenter.complete();
            notifySuccess();
            final PlaceRequest place = new PathPlaceRequest(newPath);
            placeManager.goTo(place);
          }
        },
        new Command() {

          @Override
          public void execute() {
            busyIndicatorView.hideBusyIndicator();
          }
        });
  }
  @Test
  public void testNewProjectCreation() throws URISyntaxException {
    final URI fs = new URI("git://test");
    try {
      FileSystems.getFileSystem(fs);
    } catch (FileSystemNotFoundException e) {
      FileSystems.newFileSystem(fs, new HashMap<String, Object>());
    }

    final Repository repository = mock(Repository.class);
    final String name = "p0";
    final POM pom = new POM();
    final String baseURL = "/";

    final Path repositoryRootPath = mock(Path.class);
    when(repository.getRoot()).thenReturn(repositoryRootPath);
    when(repositoryRootPath.toURI()).thenReturn("git://test");

    pom.getGav().setGroupId("org.kie.workbench.services");
    pom.getGav().setArtifactId("kie-wb-common-services-test");
    pom.getGav().setVersion("1.0.0-SNAPSHOT");

    when(pomService.load(any(Path.class))).thenReturn(pom);

    final AbstractProjectService projectServiceSpy = spy(projectService);

    final Project project = projectServiceSpy.newProject(repository, name, pom, baseURL);

    verify(projectServiceSpy, times(1))
        .simpleProjectInstance(any(org.uberfire.java.nio.file.Path.class));

    assertEquals(pom, project.getPom());
  }
  @Test
  public void testDeleteProjectObserverBridge() throws URISyntaxException {
    final URI fs = new URI("git://test");
    try {
      FileSystems.getFileSystem(fs);
    } catch (FileSystemNotFoundException e) {
      FileSystems.newFileSystem(fs, new HashMap<String, Object>());
    }

    final Path path = mock(Path.class);
    final org.uberfire.java.nio.file.Path nioPath = mock(org.uberfire.java.nio.file.Path.class);
    when(path.getFileName()).thenReturn("pom.xml");
    when(path.toURI()).thenReturn("git://test/p0/pom.xml");
    when(nioPath.getParent()).thenReturn(nioPath);
    when(nioPath.resolve(any(String.class))).thenReturn(nioPath);
    when(nioPath.toUri()).thenReturn(URI.create("git://test/p0/pom.xml"));
    when(nioPath.getFileSystem()).thenReturn(FileSystems.getFileSystem(fs));
    when(ioService.get(any(URI.class))).thenReturn(nioPath);

    final SessionInfo sessionInfo = mock(SessionInfo.class);
    final Event<DeleteProjectEvent> deleteProjectEvent = mock(Event.class);
    final AbstractProjectService projectServiceSpy = spy(projectService);

    final DeleteProjectObserverBridge bridge =
        new DeleteProjectObserverBridge(ioService, projectServiceSpy, deleteProjectEvent);

    bridge.onBatchResourceChanges(new ResourceDeletedEvent(path, "message", sessionInfo));

    verify(deleteProjectEvent, times(1)).fire(any(DeleteProjectEvent.class));

    verify(projectServiceSpy, times(0))
        .newProject(any(Repository.class), any(String.class), any(POM.class), any(String.class));
    verify(projectServiceSpy, times(1))
        .simpleProjectInstance(any(org.uberfire.java.nio.file.Path.class));
  }
  public List<ValidationMessage> validate(
      final Path resourcePath,
      final InputStream resource,
      final DirectoryStream.Filter<org.uberfire.java.nio.file.Path>... supportingFileFilters) {

    final Project project = projectService.resolveProject(resourcePath);
    if (project == null) {
      return Collections.emptyList();
    }

    final KieServices kieServices = KieServices.Factory.get();
    final KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
    final String projectPrefix = project.getRootPath().toURI();

    // Add Java Model files
    final org.uberfire.java.nio.file.Path nioProjectRoot = paths.convert(project.getRootPath());
    final DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream =
        Files.newDirectoryStream(nioProjectRoot);
    visitPaths(projectPrefix, kieFileSystem, directoryStream, supportingFileFilters);

    // Add resource to be validated
    final String destinationPath = resourcePath.toURI().substring(projectPrefix.length() + 1);
    final BufferedInputStream bis = new BufferedInputStream(resource);

    kieFileSystem.write(
        destinationPath, KieServices.Factory.get().getResources().newInputStreamResource(bis));

    // Validate
    final KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
    final Results kieResults = kieBuilder.buildAll().getResults();
    final List<ValidationMessage> results = convertMessages(kieResults);

    return results;
  }
  @Override
  public void create(
      final Package pkg, final String baseFileName, final NewResourcePresenter presenter) {
    busyIndicatorView.showBusyIndicator(DecisionTableXLSEditorConstants.INSTANCE.Uploading());

    final Path path = pkg.getPackageMainResourcesPath();
    final String fileName = buildFileName(baseFileName, fileExtensionSelector.getResourceType());
    // Package Path is already encoded, fileName needs to be encoded
    final Path newPath =
        PathFactory.newPathBasedOn(fileName, path.toURI() + "/" + encode(fileName), path);

    uploadWidget.submit(
        path,
        fileName,
        URLHelper.getServletUrl(),
        new Command() {

          @Override
          public void execute() {
            busyIndicatorView.hideBusyIndicator();
            presenter.complete();
            notifySuccess();
            placeManager.goTo(newPath);
          }
        },
        new Command() {

          @Override
          public void execute() {
            busyIndicatorView.hideBusyIndicator();
          }
        });
  }
  @Override
  public Map<String, String> getEditorParameters(
      final Path path, final String editorID, String hostInfo, PlaceRequest place) {
    List<String> activeNodesList = new ArrayList<String>();
    String activeNodesParam = place.getParameter("activeNodes", null);

    String readOnly = place.getParameter("readOnly", "false");
    String encodedProcessSource = place.getParameter("encodedProcessSource", "");

    if (activeNodesParam != null) {
      activeNodesList = Arrays.asList(activeNodesParam.split(","));
    }

    List<String> completedNodesList = new ArrayList<String>();
    String completedNodesParam = place.getParameter("completedNodes", null);

    if (completedNodesParam != null) {
      completedNodesList = Arrays.asList(completedNodesParam.split(","));
    }

    JSONArray activeNodesArray = new JSONArray(activeNodesList);
    String encodedActiveNodesParam;
    try {
      encodedActiveNodesParam =
          Base64.encodeBase64URLSafeString(activeNodesArray.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      encodedActiveNodesParam = "";
    }

    JSONArray completedNodesArray = new JSONArray(completedNodesList);
    String encodedCompletedNodesParam;
    try {
      encodedCompletedNodesParam =
          Base64.encodeBase64URLSafeString(completedNodesArray.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      encodedCompletedNodesParam = "";
    }

    Map<String, String> editorParamsMap = new HashMap<String, String>();
    editorParamsMap.put("hostinfo", hostInfo);
    editorParamsMap.put("uuid", path.toURI());
    editorParamsMap.put("profile", "jbpm");
    editorParamsMap.put("pp", "");
    editorParamsMap.put("editorid", editorID);
    editorParamsMap.put("readonly", readOnly);
    editorParamsMap.put("activenodes", encodedActiveNodesParam);
    editorParamsMap.put("completednodes", encodedCompletedNodesParam);
    editorParamsMap.put("processsource", encodedProcessSource);

    return editorParamsMap;
    //        String editorURL = hostInfo + "/editor/?uuid=" + path.toURI() +
    // "&profile=jbpm&pp=&editorid=" + editorID + "&readonly=" + readOnly +
    //                "&activenodes=" + encodedActiveNodesParam + "&completednodes=" +
    // encodedCompletedNodesParam;
    //        return getEditorResponse( editorURL, encodedProcessSource );
  }
 @Override
 public Path copy(final Path path, final String newName, final String comment) {
   System.out.println(
       "USER:"******" COPYING asset ["
           + path.getFileName()
           + "] to ["
           + newName
           + "]");
   String targetName =
       path.getFileName().substring(0, path.getFileName().lastIndexOf("/") + 1) + newName;
   String targetURI = path.toURI().substring(0, path.toURI().lastIndexOf("/") + 1) + newName;
   Path targetPath = PathFactory.newPath(path.getFileSystem(), targetName, targetURI);
   ioService.copy(
       paths.convert(path),
       paths.convert(targetPath),
       new CommentedOption(identity.getName(), comment));
   return targetPath;
 }
 protected ConfigGroup findProjectConfig(final Path projectRoot) {
   final Collection<ConfigGroup> groups =
       configurationService.getConfiguration(ConfigType.PROJECT);
   if (groups != null) {
     for (ConfigGroup groupConfig : groups) {
       if (groupConfig.getName().equals(projectRoot.toURI())) {
         return groupConfig;
       }
     }
   }
   return null;
 }
  @Test
  public void checkCreate() {
    final Path context = mock(Path.class);
    final String fileName = "filename." + dtGraphResourceType.getSuffix();
    final GuidedDecisionTableEditorGraphModel content = new GuidedDecisionTableEditorGraphModel();
    final String comment = "comment";

    when(context.toURI()).thenReturn("default://project/src/main/resources/mypackage");

    final Path p = service.create(context, fileName, content, comment);

    verify(ioService, times(1))
        .write(
            any(org.uberfire.java.nio.file.Path.class),
            any(String.class),
            any(CommentedOption.class));

    assertTrue(
        p.toURI()
            .contains("src/main/resources/mypackage/filename." + dtGraphResourceType.getSuffix()));
  }
  @Test
  public void checkLoad() {
    final Path path = mock(Path.class);
    when(path.toURI())
        .thenReturn(
            "default://project/src/main/resources/mypackage/dtable."
                + dtGraphResourceType.getSuffix());

    when(ioService.readAllString(any(org.uberfire.java.nio.file.Path.class))).thenReturn("");

    final GuidedDecisionTableEditorGraphModel model = service.load(path);

    verify(ioService, times(1)).readAllString(any(org.uberfire.java.nio.file.Path.class));
    assertNotNull(model);
  }
  @Test
  public void testPackageNameWhiteList() throws URISyntaxException {
    final URI fs = new URI("git://test");
    try {
      FileSystems.getFileSystem(fs);
    } catch (FileSystemNotFoundException e) {
      FileSystems.newFileSystem(fs, new HashMap<String, Object>());
    }

    final Map<String, String> writes = new HashMap<String, String>();

    final Repository repository = mock(Repository.class);
    final String name = "p0";
    final POM pom = new POM();
    final String baseURL = "/";

    final Path repositoryRootPath = mock(Path.class);
    when(repository.getRoot()).thenReturn(repositoryRootPath);
    when(repositoryRootPath.toURI()).thenReturn("git://test");

    when(ioService.write(any(org.uberfire.java.nio.file.Path.class), anyString()))
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(final InvocationOnMock invocation) throws Throwable {
                if (invocation.getArguments().length == 2) {
                  final String path =
                      ((org.uberfire.java.nio.file.Path) invocation.getArguments()[0])
                          .toUri()
                          .getPath();
                  final String content = ((String) invocation.getArguments()[1]);
                  writes.put(path, content);
                }
                return invocation.getArguments()[0];
              }
            });

    pom.getGav().setGroupId("org.kie.workbench.services");
    pom.getGav().setArtifactId("kie-wb-common-services-test");
    pom.getGav().setVersion("1.0.0-SNAPSHOT");

    projectService.newProject(repository, name, pom, baseURL);

    assertTrue(writes.containsKey("/p0/package-names-white-list"));
    assertEquals(
        "org.kie.workbench.services.kie_wb_common_services_test.**",
        writes.get("/p0/package-names-white-list"));
  }
  @Test
  public void checkConstructContent() {
    final Path path = mock(Path.class);
    final Overview overview = mock(Overview.class);
    when(path.toURI())
        .thenReturn(
            "default://project/src/main/resources/mypackage/dtable."
                + dtGraphResourceType.getSuffix());

    final GuidedDecisionTableEditorGraphContent content = service.constructContent(path, overview);

    verify(resourceOpenedEvent, times(1)).fire(any(ResourceOpenedEvent.class));

    assertNotNull(content.getModel());
    assertEquals(overview, content.getOverview());
  }
  @Override
  public Path createProcess(final Path context, final String fileName) {
    final Path path = paths.convert(paths.convert(context).resolve(fileName), false);

    String location = paths.convert(path).getParent().toString();
    String name = path.getFileName();
    String processId = buildProcessId(location, name);

    String processContent = PROCESS_STUB.replaceAll("\\$\\{processid\\}", processId);

    AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(name);
    builder.location(location).content(processContent).uniqueId(path.toURI());
    Asset<String> processAsset = builder.getAsset();

    repository.createAsset(processAsset);

    return path;
  }
 private void openDataObject(final DataObject dataObject) {
   final Path objectPath = getContext().getDataObjectPath(dataObject.getClassName());
   if (objectPath != null) {
     BusyPopup.showMessage(
         org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants.INSTANCE
             .Loading());
     modelerService
         .call(
             new RemoteCallback<Boolean>() {
               @Override
               public void callback(Boolean exists) {
                 BusyPopup.close();
                 if (Boolean.TRUE.equals(exists)) {
                   placeManager.goTo(new PathPlaceRequest(objectPath));
                 } else {
                   YesNoCancelPopup yesNoCancelPopup =
                       YesNoCancelPopup.newYesNoCancelPopup(
                           CommonConstants.INSTANCE.Warning(),
                           Constants.INSTANCE.objectBrowser_message_file_not_exists_or_renamed(
                               objectPath.toURI()),
                           new Command() {
                             @Override
                             public void execute() {
                               // do nothing.
                             }
                           },
                           CommonConstants.INSTANCE.Close(),
                           ButtonType.WARNING,
                           null,
                           null,
                           null,
                           null,
                           null,
                           null);
                   yesNoCancelPopup.setClosable(false);
                   yesNoCancelPopup.show();
                 }
               }
             },
             new DataModelerErrorCallback(
                 CommonConstants.INSTANCE.ExceptionNoSuchFile0(objectPath.toURI())))
         .exists(objectPath);
   }
 }
  @Test
  public void testListDecisionTablesInPackage() {
    final Path path = mock(Path.class);
    when(path.toURI()).thenReturn("default://project/src/main/resources/dtable1.gdst");

    resolvedPaths.add(makeNioPath("default://project/src/main/resources/dtable1.gdst"));
    resolvedPaths.add(makeNioPath("default://project/src/main/resources/dtable2.gdst"));
    resolvedPaths.add(makeNioPath("default://project/src/main/resources/dtable3.gdst"));
    resolvedPaths.add(makeNioPath("default://project/src/main/resources/pupa.smurf"));

    final List<Path> paths = service.listDecisionTablesInPackage(path);

    assertNotNull(paths);
    assertEquals(3, paths.size());
    final Set<String> fileNames = new HashSet<>();
    fileNames.addAll(
        paths.stream().collect(Collectors.mapping(Path::getFileName, Collectors.toSet())));
    assertTrue(fileNames.contains("dtable1.gdst"));
    assertTrue(fileNames.contains("dtable2.gdst"));
    assertTrue(fileNames.contains("dtable3.gdst"));
  }
  @Test
  @SuppressWarnings("unchecked")
  public void checkSave() {
    final Path path = mock(Path.class);
    final GuidedDecisionTableEditorGraphModel model = new GuidedDecisionTableEditorGraphModel();
    final Metadata metadata = mock(Metadata.class);
    final String comment = "comment";
    when(path.toURI())
        .thenReturn(
            "default://project/src/main/resources/mypackage/dtable."
                + dtGraphResourceType.getSuffix());

    service.save(path, model, metadata, comment);

    verify(ioService, times(1))
        .write(
            any(org.uberfire.java.nio.file.Path.class),
            any(String.class),
            any(Map.class),
            any(CommentedOption.class));
  }
  @Before
  public void setup() {
    ioService = mock(IOService.class);
    pomService = mock(POMService.class);

    final KModuleService kModuleService = mock(KModuleService.class);
    final ProjectConfigurationContentHandler projectConfigurationContentHandler =
        new ProjectConfigurationContentHandler();
    final ConfigurationService configurationService = mock(ConfigurationService.class);
    final ConfigurationFactory configurationFactory = mock(ConfigurationFactory.class);
    final Event<NewProjectEvent> newProjectEvent = mock(Event.class);
    final Event<NewPackageEvent> newPackageEvent = mock(Event.class);
    final Event<RenameProjectEvent> renameProjectEvent = mock(Event.class);
    final Event<DeleteProjectEvent> deleteProjectEvent = mock(Event.class);
    final Event<InvalidateDMOProjectCacheEvent> invalidateDMOCache = mock(Event.class);
    final User identity = mock(User.class);
    final SessionInfo sessionInfo = mock(SessionInfo.class);

    final Project project = mock(Project.class);
    final Path projectRootPath = mock(Path.class);
    when(project.getRootPath()).thenReturn(projectRootPath);
    when(projectRootPath.toURI()).thenReturn("git://test/p0");

    when(ioService.createDirectory(any(org.uberfire.java.nio.file.Path.class)))
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(final InvocationOnMock invocation) throws Throwable {
                return invocation.getArguments()[0];
              }
            });

    projectService =
        new ProjectServiceImpl(
            ioService,
            pomService,
            kModuleService,
            projectConfigurationContentHandler,
            configurationService,
            configurationFactory,
            newProjectEvent,
            newPackageEvent,
            renameProjectEvent,
            deleteProjectEvent,
            invalidateDMOCache,
            identity,
            sessionInfo) {

          @Override
          // Override as we don't have the Project Structure set-up in this test
          protected boolean hasPom(final org.uberfire.java.nio.file.Path path) {
            return true;
          }

          @Override
          // Override as we don't have the Project Structure set-up in this test
          protected boolean hasKModule(final org.uberfire.java.nio.file.Path path) {
            return true;
          }

          @Override
          // Override Package resolution as we don't have the Project Structure set-up in this test
          public Package resolvePackage(final Path resource) {
            return makePackage(project, resource);
          }
        };

    assertNotNull(projectService);
  }
 public Builder forPath(final Path path) {
   criteria.append("path=").append(path.toURI()).append(";");
   return this;
 }
 @Override
 public String toURI() {
   return path.toURI();
 }