private void visitPaths(final DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream) {
    for (final org.uberfire.java.nio.file.Path path : directoryStream) {
      if (Files.isDirectory(path)) {
        visitPaths(Files.newDirectoryStream(path));

      } else {
        // Don't process dotFiles
        if (!dotFileFilter.accept(path)) {

          // Resource Type might require "external" validation (i.e. it's not covered by Kie)
          final BuildValidationHelper validator = getBuildValidationHelper(path);
          if (validator != null) {
            nonKieResourceValidationHelpers.put(path, validator);
          }

          // Add new resource
          final String destinationPath =
              path.toUri().toString().substring(projectPrefix.length() + 1);
          final InputStream is = ioService.newInputStream(path);
          final BufferedInputStream bis = new BufferedInputStream(is);
          kieFileSystem.write(
              destinationPath,
              KieServices.Factory.get().getResources().newInputStreamResource(bis));
          handles.put(getBaseFileName(destinationPath), Paths.convert(path));

          // Java classes are handled by KIE so we can safely post-process them here
          addJavaClass(path);
        }
      }
    }
  }
  @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));
  }
  @Override
  public Package resolveParentPackage(final Package pkg) {
    final Set<String> packageNames = new HashSet<String>();

    final org.uberfire.java.nio.file.Path nioProjectRootPath =
        Paths.convert(pkg.getProjectRootPath());
    packageNames.addAll(
        getPackageNames(
            nioProjectRootPath,
            Paths.convert(pkg.getPackageMainSrcPath()).getParent(),
            true,
            false,
            false));

    // Construct Package objects for each package name
    for (String packagePathSuffix : packageNames) {
      for (String src : sourcePaths) {
        if (packagePathSuffix == null) {
          return null;
        }
        final org.uberfire.java.nio.file.Path nioPackagePath =
            nioProjectRootPath.resolve(src).resolve(packagePathSuffix);
        if (Files.exists(nioPackagePath)) {
          return resolvePackage(Paths.convert(nioPackagePath));
        }
      }
    }

    return null;
  }
  @Override
  public Package resolveDefaultPackage(final Project project) {
    final Set<String> packageNames = new HashSet<String>();
    if (project == null) {
      return null;
    }
    // Build a set of all package names across /src/main/java, /src/main/resources, /src/test/java
    // and /src/test/resources paths
    // It is possible (if the project was not created within the workbench that some packages only
    // exist in certain paths)
    final Path projectRoot = project.getRootPath();
    final org.uberfire.java.nio.file.Path nioProjectRootPath = Paths.convert(projectRoot);
    for (String src : sourcePaths) {
      final org.uberfire.java.nio.file.Path nioPackageRootSrcPath = nioProjectRootPath.resolve(src);
      packageNames.addAll(
          getPackageNames(nioProjectRootPath, nioPackageRootSrcPath, true, true, false));
    }

    // Construct Package objects for each package name
    final java.util.Set<String> resolvedPackages = new java.util.HashSet<String>();
    for (String packagePathSuffix : packageNames) {
      for (String src : sourcePaths) {
        final org.uberfire.java.nio.file.Path nioPackagePath =
            nioProjectRootPath.resolve(src).resolve(packagePathSuffix);
        if (Files.exists(nioPackagePath) && !resolvedPackages.contains(packagePathSuffix)) {
          return resolvePackage(Paths.convert(nioPackagePath));
        }
      }
    }

    return null;
  }
  @Override
  public boolean isKModule(final Path resource) {
    try {
      // Null resource paths cannot resolve to a Project
      if (resource == null) {
        return false;
      }

      // Check if path equals kmodule.xml
      final Project project = resolveProject(resource);
      // It's possible that the Incremental Build attempts to act on a Project file before the
      // project has been fully created.
      // This should be a short-term issue that will be resolved when saving a project batches
      // pom.xml, kmodule.xml and project.imports
      // etc into a single git-batch. At present they are saved individually leading to multiple
      // Incremental Build requests.
      if (project == null) {
        return false;
      }

      final org.uberfire.java.nio.file.Path path = Paths.convert(resource).normalize();
      final org.uberfire.java.nio.file.Path kmoduleFilePath =
          Paths.convert(project.getKModuleXMLPath());
      return path.startsWith(kmoduleFilePath);

    } catch (Exception e) {
      throw ExceptionUtilities.handleException(e);
    }
  }
  @Override
  public Path create(
      final Path context, final String fileName, final String content, final String comment) {
    try {
      // Get the template for new Work Item Definitions, stored as a configuration item
      String defaultDefinition =
          workItemDefinitionElements
              .getDefinitionElements()
              .get(WORK_ITEMS_EDITOR_SETTINGS_DEFINITION);
      if (defaultDefinition == null) {
        defaultDefinition = "";
      }
      defaultDefinition = defaultDefinition.replaceAll("\\|", "");

      // Write file to VFS
      final org.uberfire.java.nio.file.Path nioPath = Paths.convert(context).resolve(fileName);
      final Path newPath = Paths.convert(nioPath);

      if (ioService.exists(nioPath)) {
        throw new FileAlreadyExistsException(nioPath.toString());
      }

      ioService.write(nioPath, defaultDefinition, makeCommentedOption(comment));

      return newPath;

    } catch (Exception e) {
      throw ExceptionUtilities.handleException(e);
    }
  }
  public IncrementalBuildResults applyBatchResourceChanges(
      final Map<org.uberfire.backend.vfs.Path, Collection<ResourceChange>> changes) {
    synchronized (kieFileSystem) {
      checkNotNull("changes", changes);

      checkAFullBuildHasBeenPerformed();

      // Add all changes to KieFileSystem before executing the build
      final List<String> changedFilesKieBuilderPaths = new ArrayList<String>();
      final List<ValidationMessage> nonKieResourceValidatorAddedMessages =
          new ArrayList<ValidationMessage>();
      final List<ValidationMessage> nonKieResourceValidatorRemovedMessages =
          new ArrayList<ValidationMessage>();

      for (final Map.Entry<org.uberfire.backend.vfs.Path, Collection<ResourceChange>>
          pathCollectionEntry : changes.entrySet()) {
        for (final ResourceChange change : pathCollectionEntry.getValue()) {
          final ResourceChangeType type = change.getType();
          final Path resource = Paths.convert(pathCollectionEntry.getKey());

          checkNotNull("type", type);
          checkNotNull("resource", resource);

          final String destinationPath =
              resource.toUri().toString().substring(projectPrefix.length() + 1);
          changedFilesKieBuilderPaths.add(destinationPath);
          switch (type) {
            case ADD:
            case UPDATE:
              // Only files can be processed
              if (!Files.isRegularFile(resource)) {
                continue;
              }

              update(
                  nonKieResourceValidatorAddedMessages,
                  nonKieResourceValidatorRemovedMessages,
                  resource,
                  destinationPath);

              break;
            case DELETE:
              delete(nonKieResourceValidatorRemovedMessages, resource, destinationPath);
          }
        }
      }

      // Perform the Incremental build and get messages from incremental build
      final IncrementalBuildResults results = new IncrementalBuildResults(projectGAV);
      buildIncrementally(results, toArray(changedFilesKieBuilderPaths));

      // Copy in BuildMessages for non-KIE resources
      results.addAllAddedMessages(convertValidationMessages(nonKieResourceValidatorAddedMessages));
      results.addAllRemovedMessages(
          convertValidationMessages(nonKieResourceValidatorRemovedMessages));

      return results;
    }
  }
  public Project simpleProjectInstance(final org.uberfire.java.nio.file.Path nioProjectRootPath) {
    final Path projectRootPath = Paths.convert(nioProjectRootPath);

    return new Project(
        projectRootPath,
        Paths.convert(nioProjectRootPath.resolve(POM_PATH)),
        Paths.convert(nioProjectRootPath.resolve(KMODULE_PATH)),
        Paths.convert(nioProjectRootPath.resolve(PROJECT_IMPORTS_PATH)),
        projectRootPath.getFileName());
  }
  private List<String> loadWorkItemImages(final Path resourcePath) {
    final Path projectRoot = projectService.resolveProject(resourcePath).getRootPath();
    final org.uberfire.java.nio.file.Path nioProjectPath = Paths.convert(projectRoot);
    final org.uberfire.java.nio.file.Path nioResourceParent =
        Paths.convert(resourcePath).getParent();

    final Collection<org.uberfire.java.nio.file.Path> imagePaths =
        fileDiscoveryService.discoverFiles(nioProjectPath, imageFilter, true);
    final List<String> images = new ArrayList<String>();
    for (org.uberfire.java.nio.file.Path imagePath : imagePaths) {
      final org.uberfire.java.nio.file.Path relativePath = nioResourceParent.relativize(imagePath);
      images.add(relativePath.toString());
    }
    return images;
  }
  public IncrementalBuildResults deleteResource(final Path resource) {
    synchronized (kieFileSystem) {
      checkNotNull("resource", resource);
      // The file has already been deleted so we can't check if the Path is a file or folder :(

      checkAFullBuildHasBeenPerformed();

      // Resource Type might have been validated "externally" (i.e. it's not covered by Kie). Clear
      // any errors.
      final IncrementalBuildResults results = new IncrementalBuildResults(projectGAV);
      final BuildValidationHelper validator = getBuildValidationHelper(resource);
      if (validator != null) {
        nonKieResourceValidationHelpers.remove(resource);
        results.addAllRemovedMessages(
            convertValidationMessages(nonKieResourceValidationHelperMessages.remove(resource)));
      }

      // Delete resource
      final String destinationPath =
          resource.toUri().toString().substring(projectPrefix.length() + 1);
      kieFileSystem.delete(destinationPath);
      removeJavaClass(resource);

      buildIncrementally(results, destinationPath);

      return results;
    }
  }
  public Builder(
      final Project project,
      final IOService ioService,
      final KieProjectService projectService,
      final ProjectImportsService importsService,
      final List<BuildValidationHelper> buildValidationHelpers,
      final PackageNameWhiteList packageNameWhiteList,
      final LRUProjectDependenciesClassLoaderCache dependenciesClassLoaderCache,
      final LRUPomModelCache pomModelCache) {
    this.project = project;
    this.ioService = ioService;
    this.projectService = projectService;
    this.importsService = importsService;
    this.buildValidationHelpers = buildValidationHelpers;
    this.packageNameWhiteList = packageNameWhiteList;
    this.projectGAV = project.getPom().getGav();
    this.projectRoot = Paths.convert(project.getRootPath());
    this.projectPrefix = projectRoot.toUri().toString();
    this.kieServices = KieServices.Factory.get();
    this.kieFileSystem = kieServices.newKieFileSystem();
    this.dependenciesClassLoaderCache = dependenciesClassLoaderCache;
    this.pomModelCache = pomModelCache;

    DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream =
        Files.newDirectoryStream(projectRoot);
    visitPaths(directoryStream);
  }
  private void restoreContainers() {
    DirectoryStream<Path> ds = null;
    try {
      Path containersPath = fs.getPath("/containers");
      if (ios.exists(containersPath)) {
        ds =
            ios.newDirectoryStream(
                containersPath,
                new Filter<Path>() {

                  @Override
                  public boolean accept(Path entry) throws IOException {
                    return Files.isDirectory(entry);
                  }
                });
        if (ds != null) {
          XStream xs = XStreamXml.newXStreamMarshaller(KieServerImpl.class.getClassLoader());
          for (Path entry : ds) {
            BufferedReader reader = null;
            try {
              logger.info("Restoring state of kie container '" + entry.getFileName() + "'");
              reader =
                  Files.newBufferedReader(
                      entry.resolve(CONTAINER_STATE_FILE), Charset.forName("UTF-8"));
              KieContainerResource resource = (KieContainerResource) xs.fromXML(reader);
              restore(resource);
            } catch (Exception e) {
              logger.error("Error restoring kie container state", e);
            } finally {
              if (reader != null) {
                try {
                  reader.close();
                } catch (java.io.IOException e) {
                }
              }
            }
          }
        }
      }
    } catch (Exception e) {
      logger.error("Error restoring kie server state", e);
    } finally {
      if (ds != null) ds.close();
    }
  }
 private String getFullyQualifiedClassName(final Path path) {
   final Package pkg = projectService.resolvePackage(Paths.convert(path));
   final String packageName = pkg.getPackageName();
   if (packageName == null) {
     return null;
   }
   final String className = path.getFileName().toString().replace(".java", "");
   return (packageName.equals("") ? className : packageName + "." + className);
 }
Exemple #14
0
  @Override
  public void copy(final Path pathToPomXML, final String newName, final String comment) {
    try {
      final org.uberfire.java.nio.file.Path projectDirectory =
          Paths.convert(pathToPomXML).getParent();
      final org.uberfire.java.nio.file.Path newProjectPath =
          projectDirectory.resolveSibling(newName);

      final POM content = pomService.load(pathToPomXML);

      if (newProjectPath.equals(projectDirectory)) {
        return;
      }

      if (ioService.exists(newProjectPath)) {
        throw new FileAlreadyExistsException(newProjectPath.toString());
      }

      content.setName(newName);
      final Path newPathToPomXML = Paths.convert(newProjectPath.resolve("pom.xml"));
      ioService.startBatch();
      ioService.copy(projectDirectory, newProjectPath, makeCommentedOption(comment));
      pomService.save(newPathToPomXML, content, null, comment);
      ioService.endBatch();
      final Project newProject = resolveProject(Paths.convert(newProjectPath));
      newProjectEvent.fire(new NewProjectEvent(newProject, sessionInfo));

    } catch (final Exception e) {
      throw ExceptionUtilities.handleException(e);
    }
  }
  @Override
  public Path create(
      final Path context, final String fileName, final ProcessNode content, final String comment) {
    try {
      final org.uberfire.java.nio.file.Path nioPath = Paths.convert(context).resolve(fileName);
      final Path newPath = Paths.convert(nioPath);

      if (ioService.exists(nioPath)) {
        throw new FileAlreadyExistsException(nioPath.toString());
      }

      ioService.write(
          nioPath,
          BpmnPersistence.getInstance().marshal(content),
          CommentedOptionFactory.makeCommentedOption(identity, sessionInfo, comment));

      return newPath;

    } catch (Exception e) {
      throw ExceptionUtilities.handleException(e);
    }
  }
  private void visitPaths(
      final String projectPrefix,
      final KieFileSystem kieFileSystem,
      final DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream,
      final DirectoryStream.Filter<org.uberfire.java.nio.file.Path>... supportingFileFilters) {
    for (final org.uberfire.java.nio.file.Path path : directoryStream) {
      if (Files.isDirectory(path)) {
        visitPaths(
            projectPrefix, kieFileSystem, Files.newDirectoryStream(path), supportingFileFilters);

      } else {
        if (acceptPath(path, supportingFileFilters)) {
          final String destinationPath =
              path.toUri().toString().substring(projectPrefix.length() + 1);
          final InputStream is = ioService.newInputStream(path);
          final BufferedInputStream bis = new BufferedInputStream(is);

          kieFileSystem.write(
              destinationPath,
              KieServices.Factory.get().getResources().newInputStreamResource(bis));
        }
      }
    }
  }
Exemple #17
0
  @Override
  public Project resolveProject(final Path resource) {
    try {
      // Null resource paths cannot resolve to a Project
      if (resource == null) {
        return null;
      }

      // Check if resource is the project root
      org.uberfire.java.nio.file.Path path = Paths.convert(resource).normalize();

      // A project root is the folder containing the pom.xml file. This will be the parent of the
      // "src" folder
      if (Files.isRegularFile(path)) {
        path = path.getParent();
      }
      if (hasPom(path) && hasKModule(path)) {
        return makeProject(path);
      }
      while (path.getNameCount() > 0 && !path.getFileName().toString().equals(SOURCE_FILENAME)) {
        path = path.getParent();
      }
      if (path.getNameCount() == 0) {
        return null;
      }
      path = path.getParent();
      if (path.getNameCount() == 0 || path == null) {
        return null;
      }
      if (!hasPom(path)) {
        return null;
      }
      if (!hasKModule(path)) {
        return null;
      }
      return makeProject(path);

    } catch (Exception e) {
      throw ExceptionUtilities.handleException(e);
    }
  }
  @PostConstruct
  public void setup() {
    try {
      fileSystem =
          ioService.newFileSystem(
              URI.create("default://bpmn"),
              new HashMap<String, Object>() {
                {
                  put("init", Boolean.TRUE);
                  put("internal", Boolean.TRUE);
                }
              });
    } catch (final FileSystemAlreadyExistsException e) {
      fileSystem = ioService.getFileSystem(URI.create("default://bpmn"));
    }
    this.root = fileSystem.getRootDirectories().iterator().next();

    ioService.write(
        root.resolve("file1.bpmn"), BpmnPersistence.getInstance().marshal(new ProcessNode()));
  }
  public IncrementalBuildResults addResource(final Path resource) {
    synchronized (kieFileSystem) {
      checkNotNull("resource", resource);

      // Only files can be processed
      if (!Files.isRegularFile(resource)) {
        return new IncrementalBuildResults(projectGAV);
      }

      checkAFullBuildHasBeenPerformed();

      // Resource Type might require "external" validation (i.e. it's not covered by Kie)
      final IncrementalBuildResults results = new IncrementalBuildResults(projectGAV);
      final BuildValidationHelper validator = getBuildValidationHelper(resource);
      if (validator != null) {
        final List<ValidationMessage> addedValidationMessages =
            validator.validate(Paths.convert(resource));

        results.addAllAddedMessages(convertValidationMessages(addedValidationMessages));
        results.addAllRemovedMessages(
            convertValidationMessages(nonKieResourceValidationHelperMessages.remove(resource)));

        nonKieResourceValidationHelpers.put(resource, validator);
        nonKieResourceValidationHelperMessages.put(resource, addedValidationMessages);
      }

      // Add new resource
      final String destinationPath =
          resource.toUri().toString().substring(projectPrefix.length() + 1);
      final InputStream is = ioService.newInputStream(resource);
      final BufferedInputStream bis = new BufferedInputStream(is);
      kieFileSystem.write(
          destinationPath, KieServices.Factory.get().getResources().newInputStreamResource(bis));
      addJavaClass(resource);
      handles.put(getBaseFileName(destinationPath), Paths.convert(resource));

      buildIncrementally(results, destinationPath);

      return results;
    }
  }
  @Override
  public KObject toKObject(final Path path) {
    KObject index = null;

    try {
      final String drl = ioService.readAllString(path);
      final DrlParser drlParser = new DrlParser();
      final PackageDescr packageDescr = drlParser.parse(true, drl);

      if (drlParser.hasErrors()) {
        final List<DroolsError> errors = drlParser.getErrors();
        logger.warn(
            ErrorMessageUtilities.makeErrorMessage(
                path, errors.toArray(new DroolsError[errors.size()])));
        return index;
      }
      if (packageDescr == null) {
        logger.warn(ErrorMessageUtilities.makeErrorMessage(path));
        return index;
      }

      final ProjectDataModelOracle dmo = getProjectDataModelOracle(path);
      final Project project = projectService.resolveProject(Paths.convert(path));
      final Package pkg = projectService.resolvePackage(Paths.convert(path));

      final DefaultIndexBuilder builder = new DefaultIndexBuilder(project, pkg);
      final PackageDescrIndexVisitor visitor =
          new PackageDescrIndexVisitor(dmo, builder, packageDescr);
      visitor.visit();

      index = KObjectUtil.toKObject(path, builder.build());

    } catch (Exception e) {
      logger.error("Unable to index '" + path.toUri().toString() + "'.", e);
    }

    return index;
  }
Exemple #21
0
 private boolean hasKModule(final org.uberfire.java.nio.file.Path path) {
   final org.uberfire.java.nio.file.Path kmodulePath = path.resolve(KMODULE_PATH);
   return Files.exists(kmodulePath);
 }
Exemple #22
0
 private boolean hasPom(final org.uberfire.java.nio.file.Path path) {
   final org.uberfire.java.nio.file.Path pomPath = path.resolve(POM_PATH);
   return Files.exists(pomPath);
 }
 @Override
 public boolean accept(final Path path) {
   final String fileName = path.getFileName().toString();
   return fileName.toLowerCase().endsWith(".rdslr");
 }
Exemple #24
0
  private Package makePackage(final Project project, final Path resource) {
    final Path projectRoot = project.getRootPath();
    final org.uberfire.java.nio.file.Path nioProjectRoot = Paths.convert(projectRoot);
    final org.uberfire.java.nio.file.Path nioMainSrcPath = nioProjectRoot.resolve(MAIN_SRC_PATH);
    final org.uberfire.java.nio.file.Path nioTestSrcPath = nioProjectRoot.resolve(TEST_SRC_PATH);
    final org.uberfire.java.nio.file.Path nioMainResourcesPath =
        nioProjectRoot.resolve(MAIN_RESOURCES_PATH);
    final org.uberfire.java.nio.file.Path nioTestResourcesPath =
        nioProjectRoot.resolve(TEST_RESOURCES_PATH);

    org.uberfire.java.nio.file.Path nioResource = Paths.convert(resource);

    if (Files.isRegularFile(nioResource)) {
      nioResource = nioResource.getParent();
    }

    String packageName = null;
    org.uberfire.java.nio.file.Path packagePath = null;
    if (nioResource.startsWith(nioMainSrcPath)) {
      packagePath = nioMainSrcPath.relativize(nioResource);
      packageName = packagePath.toString().replaceAll("/", ".");
    } else if (nioResource.startsWith(nioTestSrcPath)) {
      packagePath = nioTestSrcPath.relativize(nioResource);
      packageName = packagePath.toString().replaceAll("/", ".");
    } else if (nioResource.startsWith(nioMainResourcesPath)) {
      packagePath = nioMainResourcesPath.relativize(nioResource);
      packageName = packagePath.toString().replaceAll("/", ".");
    } else if (nioResource.startsWith(nioTestResourcesPath)) {
      packagePath = nioTestResourcesPath.relativize(nioResource);
      packageName = packagePath.toString().replaceAll("/", ".");
    }

    // Resource was not inside a package
    if (packageName == null) {
      return null;
    }

    final Path mainSrcPath = Paths.convert(nioMainSrcPath.resolve(packagePath));
    final Path testSrcPath = Paths.convert(nioTestSrcPath.resolve(packagePath));
    final Path mainResourcesPath = Paths.convert(nioMainResourcesPath.resolve(packagePath));
    final Path testResourcesPath = Paths.convert(nioTestResourcesPath.resolve(packagePath));

    final String displayName = getPackageDisplayName(packageName);

    final Package pkg =
        new Package(
            project.getRootPath(),
            mainSrcPath,
            testSrcPath,
            mainResourcesPath,
            testResourcesPath,
            packageName,
            displayName,
            getPackageRelativeCaption(displayName, resource.getFileName()));
    return pkg;
  }
Exemple #25
0
  private String getPackagePathSuffix(
      final org.uberfire.java.nio.file.Path nioProjectRootPath,
      final org.uberfire.java.nio.file.Path nioPackagePath) {
    final org.uberfire.java.nio.file.Path nioMainSrcPath =
        nioProjectRootPath.resolve(MAIN_SRC_PATH);
    final org.uberfire.java.nio.file.Path nioTestSrcPath =
        nioProjectRootPath.resolve(TEST_SRC_PATH);
    final org.uberfire.java.nio.file.Path nioMainResourcesPath =
        nioProjectRootPath.resolve(MAIN_RESOURCES_PATH);
    final org.uberfire.java.nio.file.Path nioTestResourcesPath =
        nioProjectRootPath.resolve(TEST_RESOURCES_PATH);

    String packageName = null;
    org.uberfire.java.nio.file.Path packagePath = null;
    if (nioPackagePath.startsWith(nioMainSrcPath)) {
      packagePath = nioMainSrcPath.relativize(nioPackagePath);
      packageName = packagePath.toString();
    } else if (nioPackagePath.startsWith(nioTestSrcPath)) {
      packagePath = nioTestSrcPath.relativize(nioPackagePath);
      packageName = packagePath.toString();
    } else if (nioPackagePath.startsWith(nioMainResourcesPath)) {
      packagePath = nioMainResourcesPath.relativize(nioPackagePath);
      packageName = packagePath.toString();
    } else if (nioPackagePath.startsWith(nioTestResourcesPath)) {
      packagePath = nioTestResourcesPath.relativize(nioPackagePath);
      packageName = packagePath.toString();
    }

    return packageName;
  }
Exemple #26
0
  public void run(final Path root, final Runnable callback) {
    try {
      if (root == null) {
        return;
      }
      final KCluster cluster = toKCluster(root.getFileSystem());
      indexEngine.startBatch(cluster);
      walkFileTree(
          checkNotNull("root", root),
          new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                throws IOException {
              if (indexDisposed.get()) {
                return FileVisitResult.TERMINATE;
              }
              try {
                checkNotNull("file", file);
                checkNotNull("attrs", attrs);

                if (!file.getFileName().toString().startsWith(".")) {

                  // Default indexing
                  for (final Class<? extends FileAttributeView> view : views) {
                    ioService.getFileAttributeView(file, view);
                  }
                  final FileAttribute<?>[] allAttrs =
                      ioService.convert(ioService.readAttributes(file));
                  if (!indexDisposed.get()) {
                    indexEngine.index(KObjectUtil.toKObject(file, allAttrs));
                  } else {
                    return FileVisitResult.TERMINATE;
                  }

                  // Additional indexing
                  for (Indexer indexer : additionalIndexers) {
                    if (indexer.supportsPath(file)) {
                      final KObject kObject = indexer.toKObject(file);
                      if (kObject != null) {
                        if (!indexDisposed.get()) {
                          indexEngine.index(kObject);
                        } else {
                          return FileVisitResult.TERMINATE;
                        }
                      }
                    }
                  }
                }
              } catch (final Exception ex) {
                if (indexDisposed.get()) {
                  LOG.warn("Batch index couldn't finish. [@" + root.toUri().toString() + "]");
                  return FileVisitResult.TERMINATE;
                } else {
                  LOG.error("Index fails. [@" + file.toString() + "]", ex);
                }
              }
              if (indexDisposed.get()) {
                return FileVisitResult.TERMINATE;
              }
              return FileVisitResult.CONTINUE;
            }
          });
      if (!indexDisposed.get()) {
        indexEngine.commit(cluster);
        if (callback != null) {
          callback.run();
        }
      } else {
        LOG.warn("Batch index couldn't finish. [@" + root.toUri().toString() + "]");
      }
    } catch (final IllegalStateException ex) {
      if (indexDisposed.get()) {
        LOG.warn("Batch index couldn't finish. [@" + root.toUri().toString() + "]");
      } else {
        LOG.error(
            "Index fails - Index has an invalid state. [@" + root.toUri().toString() + "]", ex);
      }
    } catch (final Exception ex) {
      if (indexDisposed.get()) {
        LOG.warn("Batch index couldn't finish. [@" + root.toUri().toString() + "]");
      } else {
        LOG.error("Index fails. [@" + root.toUri().toString() + "]", ex);
      }
    }
  }
 private Path createPath(String uri) {
   Path path = mock(Path.class);
   when(path.toUri()).thenReturn(URI.create(uri));
   when(path.getFileSystem()).thenReturn(fileSystem);
   return path;
 }
  public BuildResults build() {
    synchronized (kieFileSystem) {
      // KieBuilder is not re-usable for successive "full" builds
      kieBuilder = createKieBuilder(kieFileSystem);

      // Record RTEs from KieBuilder - that can fail if a rule uses an inaccessible class
      final BuildResults results = new BuildResults(projectGAV);
      try {
        final Results kieResults = kieBuilder.buildAll().getResults();
        results.addAllBuildMessages(convertMessages(kieResults.getMessages(), handles));

      } catch (LinkageError e) {
        final String msg = MessageFormat.format(ERROR_CLASS_NOT_FOUND, e.getLocalizedMessage());
        logger.warn(msg);
        results.addBuildMessage(makeWarningMessage(msg));

      } catch (Throwable e) {
        final String msg = e.getLocalizedMessage();
        logger.error(msg, e);
        results.addBuildMessage(makeErrorMessage(msg));

      } finally {
        pomModelCache.setEntry(project, ((KieBuilderImpl) kieBuilder).getPomModel());
      }

      // Add validate messages from external helpers
      for (Map.Entry<Path, BuildValidationHelper> e : nonKieResourceValidationHelpers.entrySet()) {
        final org.uberfire.backend.vfs.Path vfsPath = Paths.convert(e.getKey());
        final List<ValidationMessage> validationMessages = e.getValue().validate(vfsPath);
        nonKieResourceValidationHelperMessages.put(e.getKey(), validationMessages);
        results.addAllBuildMessages(convertValidationMessages(validationMessages));
      }

      // Check external imports are available. These are loaded when a DMO is requested, but it's
      // better to report them early
      final org.uberfire.java.nio.file.Path nioExternalImportsPath =
          projectRoot.resolve("project.imports");
      if (Files.exists(nioExternalImportsPath)) {
        final org.uberfire.backend.vfs.Path externalImportsPath =
            Paths.convert(nioExternalImportsPath);
        final ProjectImports projectImports = importsService.load(externalImportsPath);
        final Imports imports = projectImports.getImports();
        for (final Import item : imports.getImports()) {
          final String fullyQualifiedClassName = item.getType();
          try {
            Class clazz = this.getClass().getClassLoader().loadClass(item.getType());

          } catch (ClassNotFoundException cnfe) {
            logger.warn(cnfe.getMessage());
            final String msg = MessageFormat.format(ERROR_CLASS_NOT_FOUND, fullyQualifiedClassName);
            results.addBuildMessage(makeWarningMessage(msg));
          }
        }
      }

      // At the end we are interested to ensure that external .jar files referenced as dependencies
      // don't have
      // referential inconsistencies. We will at least provide a basic algorithm to ensure that if
      // an external class
      // X references another external class Y, Y is also accessible by the class loader.
      final KieModuleMetaData kieModuleMetaData =
          KieModuleMetaData.Factory.newKieModuleMetaData(
              ((InternalKieBuilder) kieBuilder).getKieModuleIgnoringErrors());
      final Set<String> packageNamesWhiteList =
          packageNameWhiteList.filterPackageNames(project, kieModuleMetaData.getPackages());
      // store the project dependencies ClassLoader for optimization purposes.
      updateDependenciesClassLoader(project, kieModuleMetaData);

      for (final String packageName : kieModuleMetaData.getPackages()) {
        if (packageNamesWhiteList.contains(packageName)) {
          for (final String className : kieModuleMetaData.getClasses(packageName)) {
            final String fullyQualifiedClassName = packageName + "." + className;
            try {
              final Class clazz = kieModuleMetaData.getClass(packageName, className);
              if (clazz != null) {
                final TypeSource typeSource = getClassSource(kieModuleMetaData, clazz);
                if (TypeSource.JAVA_DEPENDENCY == typeSource) {
                  verifyExternalClass(clazz);
                }
              } else {
                final String msg =
                    MessageFormat.format(ERROR_EXTERNAL_CLASS_VERIFICATON, fullyQualifiedClassName);
                logger.warn(msg);
              }

            } catch (Throwable e) {
              final String msg =
                  MessageFormat.format(ERROR_EXTERNAL_CLASS_VERIFICATON, fullyQualifiedClassName);
              logger.warn(msg);
              results.addBuildMessage(makeWarningMessage(msg));
            }
          }
        }
      }

      return results;
    }
  }
 public boolean accept(Path path) {
   return path.getFileName().toString().endsWith(extension);
 }