@Test
  public void testBuildCommandFail() {
    BuildMessage message = mock(BuildMessage.class);
    List<BuildMessage> messages = new ArrayList<BuildMessage>();
    messages.add(message);

    BuildResults results = mock(BuildResults.class);
    when(results.getErrorMessages()).thenReturn(messages);

    when(buildService.buildAndDeploy(any(Project.class))).thenReturn(results);

    presenter.triggerBuild();

    verify(notificationEvent)
        .fire(
            argThat(
                new ArgumentMatcher<NotificationEvent>() {
                  @Override
                  public boolean matches(final Object argument) {
                    final NotificationEvent event = (NotificationEvent) argument;
                    final String notification = event.getNotification();
                    final NotificationEvent.NotificationType type = event.getType();

                    return notification.equals(ProjectEditorResources.CONSTANTS.BuildFailed())
                        && type.equals(NotificationEvent.NotificationType.ERROR);
                  }
                }));

    verify(view, times(1)).showBusyIndicator(eq(ProjectEditorResources.CONSTANTS.Building()));
    // There are two calls to "hide" by this stage; one from the view initialisation one for the
    // build
    verify(view, times(2)).hideBusyIndicator();
  }
  @Test
  public void testNonPackageResourceUpdated() throws Exception {
    // This tests changes to a resource that is neither pom.xml nor kmodule.xml nor within a Package
    final Bean buildChangeListenerBean =
        (Bean)
            beanManager
                .getBeans(org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class)
                .iterator()
                .next();
    final CreationalContext cc = beanManager.createCreationalContext(buildChangeListenerBean);
    final org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder buildChangeListener =
        (org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder)
            beanManager.getReference(
                buildChangeListenerBean,
                org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class,
                cc);

    final URL resourceUrl = this.getClass().getResource("/BuildChangeListenerRepo/project.imports");
    final org.uberfire.java.nio.file.Path nioResourcePath = fs.getPath(resourceUrl.toURI());
    final Path resourcePath = paths.convert(nioResourcePath);

    // Force full build before attempting incremental changes
    final KieProject project = projectService.resolveProject(resourcePath);
    final BuildResults buildResults = buildService.build(project);
    assertNotNull(buildResults);
    assertEquals(0, buildResults.getErrorMessages().size());
    assertEquals(1, buildResults.getInformationMessages().size());

    // Perform incremental build (Without a full Build first)
    buildChangeListener.updateResource(resourcePath);

    final IncrementalBuildResults incrementalBuildResults =
        buildResultsObserver.getIncrementalBuildResults();
    assertNull(incrementalBuildResults);
  }
  public KieContainer getKieContainer() {
    BuildResults results = null;

    // Kie classes are only available once built
    if (!isBuilt()) {
      results = build();
    } else {
      results = new BuildResults();
      results.addAllBuildMessages(convertMessages(kieBuilder.getResults().getMessages(), handles));
    }
    // It's impossible to retrieve a KieContainer if the KieModule contains errors
    if (results.getErrorMessages().isEmpty()) {
      // Do not retrieve the KieContainer with KieServices.newKieContainer(releaseId) since this
      // looks-up the KieModule to
      // create the KieContainer from KieRepository. This holds the most recent KieModule (for the
      // ReleaseId) that was built with
      // kieBuilder.buildAll() which *may* be a KieModule created during asset validation and hence
      // will lack many assets.
      // See https://bugzilla.redhat.com/show_bug.cgi?id=1202551
      final KieModule kieModule = kieBuilder.getKieModule();
      final ReleaseId releaseId = kieModule.getReleaseId();
      final org.drools.compiler.kie.builder.impl.KieProject kieProject =
          new KieModuleKieProject((InternalKieModule) kieBuilder.getKieModule(), null);
      final KieContainer kieContainer =
          new KieContainerImpl(kieProject, KieServices.Factory.get().getRepository(), releaseId);
      return kieContainer;
    } else {
      return null;
    }
  }
  @Test
  public void testResourceDeleted() throws Exception {
    final Bean buildChangeListenerBean =
        (Bean)
            beanManager
                .getBeans(org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class)
                .iterator()
                .next();
    final CreationalContext cc = beanManager.createCreationalContext(buildChangeListenerBean);
    final org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder buildChangeListener =
        (org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder)
            beanManager.getReference(
                buildChangeListenerBean,
                org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class,
                cc);

    final URL resourceUrl =
        this.getClass().getResource("/BuildChangeListenerRepo/src/main/resources/delete.drl");
    final org.uberfire.java.nio.file.Path nioResourcePath = fs.getPath(resourceUrl.toURI());
    final Path resourcePath = paths.convert(nioResourcePath);

    // Force full build before attempting incremental changes
    final KieProject project = projectService.resolveProject(resourcePath);
    final BuildResults buildResults = buildService.build(project);
    assertNotNull(buildResults);
    assertEquals(0, buildResults.getErrorMessages().size());
    assertEquals(1, buildResults.getInformationMessages().size());

    // Perform incremental build
    buildChangeListener.deleteResource(resourcePath);

    final IncrementalBuildResults incrementalBuildResults =
        buildResultsObserver.getIncrementalBuildResults();
    assertNotNull(incrementalBuildResults);
    assertEquals(0, incrementalBuildResults.getAddedMessages().size());
    assertEquals(0, incrementalBuildResults.getRemovedMessages().size());
  }
  @Test
  public void testBatchResourceChanges() throws Exception {
    final Bean buildChangeListenerBean =
        (Bean)
            beanManager
                .getBeans(org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class)
                .iterator()
                .next();
    final CreationalContext cc = beanManager.createCreationalContext(buildChangeListenerBean);
    final org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder buildChangeListener =
        (org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder)
            beanManager.getReference(
                buildChangeListenerBean,
                org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class,
                cc);

    final URL resourceUrl1 =
        this.getClass().getResource("/BuildChangeListenerRepo/src/main/resources/add.drl");
    final org.uberfire.java.nio.file.Path nioResourcePath1 = fs.getPath(resourceUrl1.toURI());
    final Path resourcePath1 = paths.convert(nioResourcePath1);

    final URL resourceUrl2 =
        this.getClass().getResource("/BuildChangeListenerRepo/src/main/resources/update.drl");
    final org.uberfire.java.nio.file.Path nioResourcePath2 = fs.getPath(resourceUrl2.toURI());
    final Path resourcePath2 = paths.convert(nioResourcePath2);

    final URL resourceUrl3 =
        this.getClass().getResource("/BuildChangeListenerRepo/src/main/resources/delete.drl");
    final org.uberfire.java.nio.file.Path nioResourcePath3 = fs.getPath(resourceUrl3.toURI());
    final Path resourcePath3 = paths.convert(nioResourcePath3);

    //        final Set<ResourceChange> batch = new HashSet<ResourceChange>();
    //        batch.add( new ResourceChange( ChangeType.ADD,
    //                                       resourcePath1,
    //                                       new SessionInfoImpl( "id",
    //                                                            new IdentityImpl( "user",
    //
    // Collections.<Role>emptyList() ) ) ) );
    //        batch.add( new ResourceChange( ChangeType.UPDATE,
    //                                       resourcePath2,
    //                                       new SessionInfoImpl( "id",
    //                                                            new IdentityImpl( "user",
    //
    // Collections.<Role>emptyList() ) ) ) );
    //        batch.add( new ResourceChange( ChangeType.DELETE,
    //                                       resourcePath3,
    //                                       new SessionInfoImpl( "id",
    //                                                            new IdentityImpl( "user",
    //
    // Collections.<Role>emptyList() ) ) ) );
    final Map<Path, Collection<ResourceChange>> batch =
        new HashMap<Path, Collection<ResourceChange>>();
    batch.put(
        resourcePath1,
        new ArrayList<ResourceChange>() {
          {
            add(new ResourceAdded());
          }
        });

    batch.put(
        resourcePath2,
        new ArrayList<ResourceChange>() {
          {
            add(new ResourceUpdated());
          }
        });

    batch.put(
        resourcePath3,
        new ArrayList<ResourceChange>() {
          {
            add(new ResourceUpdated());
          }
        });

    // Force full build before attempting incremental changes
    final KieProject project = projectService.resolveProject(resourcePath1);
    final BuildResults buildResults = buildService.build(project);
    assertNotNull(buildResults);
    assertEquals(0, buildResults.getErrorMessages().size());
    assertEquals(1, buildResults.getInformationMessages().size());

    // Perform incremental build
    buildChangeListener.batchResourceChanges(batch);

    final IncrementalBuildResults incrementalBuildResults =
        buildResultsObserver.getIncrementalBuildResults();
    assertNotNull(incrementalBuildResults);
    assertEquals(0, incrementalBuildResults.getAddedMessages().size());
    assertEquals(0, incrementalBuildResults.getRemovedMessages().size());
  }
  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;
    }
  }