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);
        }
      }
    }
  }
  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);
  }
  @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 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 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;
  }
  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));
        }
      }
    }
  }
 private Path createPath(String uri) {
   Path path = mock(Path.class);
   when(path.toUri()).thenReturn(URI.create(uri));
   when(path.getFileSystem()).thenReturn(fileSystem);
   return path;
 }
示例#10
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);
      }
    }
  }