public KnowledgeBase getKnowledgeBase() {
    if (this.kbase != null) {
      return kbase;
    }
    knownPackages = new CopyOnWriteArraySet<String>();
    Properties consoleProperties = PropertyLoader.getJbpmConsoleProperties();
    GuvnorConnectionUtils guvnorUtils = new GuvnorConnectionUtils();
    if (guvnorUtils.guvnorExists()) {
      kagent = buildKnowledgeAgent(guvnorUtils);
      if (kagent != null) {
        kbase = kagent.getKnowledgeBase();
      }
    } else {
      logger.warn("Could not connect to Guvnor.");
    }

    // Create a kbase if we couldn't do that with Guvnor
    if (kbase == null) {
      kbase = KnowledgeBaseFactory.newKnowledgeBase();
    }

    // load processes from local file system
    addProcessesFromConsoleDirectory(kbase, consoleProperties);

    // add known packages
    for (KnowledgePackage pkg : kbase.getKnowledgePackages()) {
      knownPackages.add(pkg.getName());
    }
    return kbase;
  }
 protected KnowledgeAgent buildKnowledgeAgent(GuvnorConnectionUtils guvnorUtils) {
   try {
     ResourceChangeScannerConfiguration sconf =
         ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration();
     sconf.setProperty("drools.resource.scanner.interval", "10");
     ResourceFactory.getResourceChangeScannerService().configure(sconf);
     ResourceFactory.getResourceChangeScannerService().start();
     ResourceFactory.getResourceChangeNotifierService().start();
     KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
     aconf.setProperty("drools.agent.newInstance", "false");
     KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("Guvnor default", aconf);
     kagent.applyChangeSet(ResourceFactory.newReaderResource(guvnorUtils.createChangeSet()));
     return kagent;
   } catch (Throwable t) {
     logger.error("Could not load processes from Guvnor: " + t.getMessage(), t);
     return null;
   }
 }
  public synchronized void syncPackages() {
    try {
      GuvnorConnectionUtils guvnorUtils = new GuvnorConnectionUtils();
      if (guvnorUtils.guvnorExists()) {

        if (kagent == null) {
          kagent = buildKnowledgeAgent(guvnorUtils);
        }
        List<String> guvnorPackages = guvnorUtils.getBuiltPackageNames();

        guvnorPackages.removeAll(knownPackages);

        if (guvnorPackages.size() > 0 && kagent != null) {
          kagent.applyChangeSet(
              ResourceFactory.newReaderResource(guvnorUtils.createChangeSet(guvnorPackages)));
          knownPackages.addAll(guvnorPackages);
        }
      }
    } catch (Exception e) {
      logger.error("Error while checking packages from Guvnor", e);
    }
  }