/** This will create a new asset which refers to an existing asset */
  public String createNewImportedRule(String sharedAssetName, String initialPackage)
      throws SerializationException {
    log.info(
        "USER:"******" CREATING shared asset imported from global area named ["
            + sharedAssetName
            + "] in package ["
            + initialPackage
            + "]");

    try {
      ModuleItem packageItem = rulesRepository.loadModule(initialPackage);
      AssetItem asset = packageItem.addAssetImportedFromGlobalArea(sharedAssetName);
      rulesRepository.save();

      return asset.getUUID();
    } catch (RulesRepositoryException e) {
      // If we want to display an explicit error message of "duplicate asset", we can achieve this
      // in client error handler.
      /*            if ( e.getCause() instanceof ItemExistsException ) {
          return "DUPLICATE";
      }*/
      log.error(
          "An error occurred creating shared asset"
              + sharedAssetName
              + "] in package ["
              + initialPackage
              + "]: ",
          e);
      throw new SerializationException(e.getMessage());
    }
  }
  /**
   * This prepares the package builder, loads the jars/classpath.
   *
   * @return true if everything is good to go, false if its all gone horribly wrong, and we can't
   *     even get the package header up.
   */
  private boolean preparePackage() {

    // firstly we loadup the classpath
    builder.addPackage(new PackageDescr(pkg.getName()));

    // now we deal with the header (imports, templates, globals).
    addDrl(ServiceImplementation.getDroolsHeader(pkg));
    loadDeclaredTypes();
    if (builder.hasErrors()) {
      recordBuilderErrors(pkg);
      // if we have any failures, lets drop out now, no point in going
      // any further
      return false;
    }

    loadDSLFiles();

    // finally, any functions we will load at this point.
    AssetItemIterator it = this.pkg.listAssetsByFormat(new String[] {AssetFormats.FUNCTION});
    while (it.hasNext()) {
      AssetItem func = (AssetItem) it.next();
      addDrl(func.getContent());
      if (builder.hasErrors()) {
        recordBuilderErrors(func);
        builder.clearErrors();
      }
    }

    return errors.size() == 0;
  }
  protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
      throws ServletException, IOException {

    final String uuid = req.getParameter("uuid");

    if (uuid == null) {
      res.sendError(SC_BAD_REQUEST);
    }

    final AssetItem asset = repository.loadAssetByUUID(uuid);

    if (asset == null) {
      res.sendError(SC_NO_CONTENT);
      return;
    }

    final ServiceConfig serviceConfig =
        ServiceConfigPersistence.getInstance().unmarshal(asset.getContent());

    try {
      res.setContentType("application/x-download");
      res.setHeader("Content-Disposition", "attachment; filename=drools-service.war;");
      buildWar(serviceConfig, repository, res.getOutputStream());
    } catch (Throwable e) {
      ((OutputStream) res.getOutputStream()).close();
      res.sendError(SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
    }
  }
  @Test
  public void testAddCategories() throws Exception {
    ServiceImplementation impl = getServiceImplementation();
    RepositoryCategoryService repositoryCategoryService = getRepositoryCategoryService();
    impl.getRulesRepository().createPackage("testAddCategoriesPackage", "desc");
    repositoryCategoryService.createCategory("", "testAddCategoriesCat1", "this is a cat");
    repositoryCategoryService.createCategory("", "testAddCategoriesCat2", "this is a cat");

    String uuid =
        impl.createNewRule(
            "testCreateNewRuleName",
            "an initial desc",
            "testAddCategoriesCat1",
            "testAddCategoriesPackage",
            AssetFormats.DSL_TEMPLATE_RULE);

    AssetItem dtItem = impl.getRulesRepository().loadAssetByUUID(uuid);
    dtItem.addCategory("testAddCategoriesCat1");
    impl.getRulesRepository().save();

    AssetItem dtItem1 = impl.getRulesRepository().loadAssetByUUID(uuid);
    assertEquals(1, dtItem1.getCategories().size());
    assertTrue(dtItem1.getCategorySummary().contains("testAddCategoriesCat1"));

    AssetItem dtItem2 = impl.getRulesRepository().loadAssetByUUID(uuid);
    dtItem2.addCategory("testAddCategoriesCat2");
    impl.getRulesRepository().save();

    AssetItem dtItem3 = impl.getRulesRepository().loadAssetByUUID(uuid);
    assertEquals(2, dtItem3.getCategories().size());
    assertTrue(dtItem3.getCategorySummary().contains("testAddCategoriesCat2"));
  }
Example #5
0
 public void storeAssetContent(RuleAsset asset, AssetItem repoAsset)
     throws SerializationException {
   RuleModel data = (RuleModel) asset.getContent();
   if (data.name == null) {
     data.name = repoAsset.getName();
   }
   repoAsset.updateContent(getBrlXmlPersistence().marshal(data));
 }
  /**
   * This will create a new asset. It will be saved, but not checked in. The initial state will be
   * the draft state. Returns the UUID of the asset.
   */
  public String createNewRule(
      NewAssetWithContentConfiguration<? extends PortableObject> configuration)
      throws SerializationException {

    final String assetName = configuration.getAssetName();
    final String description = configuration.getDescription();
    final String initialCategory = configuration.getInitialCategory();
    final String packageName = configuration.getPackageName();
    final String format = configuration.getFormat();
    final PortableObject content = configuration.getContent();

    log.info(
        "USER:"******" CREATING new asset name ["
            + assetName
            + "] in package ["
            + packageName
            + "]");

    try {

      // Create new Asset
      ModuleItem pkg = rulesRepository.loadModule(packageName);
      AssetItem assetItem = pkg.addAsset(assetName, description, initialCategory, format);

      // Set the Assets content - no need to use AssetTemplateCreator().applyPreBuiltTemplates() as
      // we are provided a model
      // Use a transient Asset object so we can use ContentHandler to convert between model and
      // persisted format correctly.
      Asset asset = new AssetPopulator().populateFrom(assetItem);
      ContentHandler handler = ContentManager.getHandler(assetItem.getFormat());
      asset.setContent(content);
      handler.storeAssetContent(asset, assetItem);

      rulesRepository.save();

      push("categoryChange", initialCategory);
      push("packageChange", pkg.getName());

      return assetItem.getUUID();

    } catch (RulesRepositoryException e) {
      // If we want to display an explicit error message of "duplicate asset", we can achieve this
      // in client error handler.
      /*            if ( e.getCause() instanceof ItemExistsException ) {
          return "DUPLICATE";
      }*/
      log.error(
          "An error occurred creating new asset ["
              + assetName
              + "] in package ["
              + packageName
              + "]: ",
          e);
      throw new SerializationException(e.getMessage());
    }
  }
 void handleArchivedForSavePackage(PackageConfigData data, PackageItem item) {
   for (Iterator<AssetItem> iter = item.getAssets(); iter.hasNext(); ) {
     AssetItem assetItem = iter.next();
     if (!assetItem.isArchived()) {
       assetItem.archiveItem(true);
       assetItem.checkin(data.getDescription());
     }
   }
 }
  /** @deprecated in favour of {@link #loadArchivedAssets(PageRequest)} */
  @WebRemote
  @LoggedIn
  public TableDataResult loadAssetHistory(String packageUUID, String assetName)
      throws SerializationException {
    ModuleItem pi = rulesRepository.loadModuleByUUID(packageUUID);
    AssetItem assetItem = pi.loadAsset(assetName);
    serviceSecurity.checkSecurityPackageReadOnlyWithPackageUuid(assetItem.getModule().getUUID());

    return repositoryAssetOperations.loadItemHistory(assetItem);
  }
 @SuppressWarnings("rawtypes")
 private List<String> getDataEnums(PackageItem pkg) {
   Iterator it = pkg.listAssetsByFormat(new String[] {AssetFormats.ENUMERATION});
   List<String> list = new ArrayList<String>();
   while (it.hasNext()) {
     AssetItem item = (AssetItem) it.next();
     list.add(item.getContent());
   }
   return list;
 }
  public void deleteUncheckedRule(String uuid) {
    AssetItem asset = rulesRepository.loadAssetByUUID(uuid);

    ModuleItem packageItem = asset.getModule();
    packageItem.updateBinaryUpToDate(false);

    asset.remove();

    rulesRepository.save();
    push("packageChange", packageItem.getName());
  }
 void handleUnarchivedForSavePackage(
     PackageConfigData data, PackageItem item, Calendar packageLastModified) {
   for (Iterator<AssetItem> iter = item.getAssets(); iter.hasNext(); ) {
     AssetItem assetItem = iter.next();
     // Unarchive the assets archived after the package
     // ( == at the same time that the package was archived)
     if (assetItem.getLastModified().compareTo(packageLastModified) >= 0) {
       assetItem.archiveItem(false);
       assetItem.checkin(data.getDescription());
     }
   }
 }
Example #12
0
  @Test
  public void testEmptyDT() throws Exception {
    RulesRepository repo = getRulesRepository();
    PackageItem pkg = repo.loadDefaultPackage();
    AssetItem asset = pkg.addAsset("testEmptyDT", "");
    asset.updateFormat(AssetFormats.DECISION_TABLE_GUIDED);
    GuidedDecisionTable gt = new GuidedDecisionTable();
    asset.updateContent(GuidedDTXMLPersistence.getInstance().marshal(gt));
    asset.checkin("");

    GuidedDTContentHandler ch = new GuidedDTContentHandler();
    ch.compile(null, asset, null);
  }
 private void loadDeclaredTypes() {
   AssetItemIterator it = this.pkg.listAssetsByFormat(new String[] {AssetFormats.DRL_MODEL});
   while (it.hasNext()) {
     AssetItem as = it.next();
     try {
       builder.addPackageFromDrl(new StringReader(as.getContent()));
     } catch (DroolsParserException e) {
       this.errors.add(new ContentAssemblyError(as, "Parser exception: " + e.getMessage()));
     } catch (IOException e) {
       this.errors.add(new ContentAssemblyError(as, "IOException: " + e.getMessage()));
     }
   }
 }
  private void archiveOrUnarchiveAsset(String uuid, boolean archive) {
    try {
      AssetItem item = getRulesRepository().loadAssetByUUID(uuid);

      serviceSecurity.checkSecurityIsPackageDeveloper(item);

      if (item.getPackage().isArchived()) {
        throw new RulesRepositoryException(
            "The package ["
                + item.getPackageName()
                + "] that asset ["
                + item.getName()
                + "] belongs to is archived. You need to unarchive it first.");
      }

      log.info(
          "USER:"******" ARCHIVING asset: ["
              + item.getName()
              + "] UUID: ["
              + item.getUUID()
              + "] ");

      try {
        ContentHandler handler = getContentHandler(item);
        if (handler instanceof ICanHasAttachment) {
          ((ICanHasAttachment) handler).onAttachmentRemoved(item);
        }
      } catch (IOException e) {
        log.error("Unable to remove asset attachment", e);
      }

      item.archiveItem(archive);
      PackageItem pkg = item.getPackage();
      pkg.updateBinaryUpToDate(false);
      RuleBaseCache.getInstance().remove(pkg.getUUID());
      if (archive) {
        item.checkin("archived");
      } else {
        item.checkin("unarchived");
      }

      push("packageChange", pkg.getName());

    } catch (RulesRepositoryException e) {
      log.error("Unable to get item format.", e);
      throw e;
    }
  }
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public void removeAsset(String uuid) {
    try {
      AssetItem item = getRulesRepository().loadAssetByUUID(uuid);
      serviceSecurity.checkSecurityIsPackageDeveloper(item);

      item.remove();
      getRulesRepository().save();
    } catch (RulesRepositoryException e) {
      log.error("Unable to remove asset.", e);
      throw e;
    }
  }
Example #16
0
  /** Builds assets that are "rule" assets (ie things that are not functions etc). */
  protected void buildAsset(AssetItem asset) {
    ContentHandler contentHandler = ContentManager.getHandler(asset.getFormat());

    if (contentHandler instanceof ICompilable && !asset.getDisabled()) {
      try {
        compile(asset, (ICompilable) contentHandler);
      } catch (DroolsParserException e) {
        errorLogger.addError(asset, e.getMessage());
        throw new RulesRepositoryException(e);
      } catch (IOException e) {
        errorLogger.addError(asset, e.getMessage());
      }
    }
  }
  @WebRemote
  @LoggedIn
  public void removeAsset(String uuid) {
    try {
      AssetItem item = rulesRepository.loadAssetByUUID(uuid);
      serviceSecurity.checkSecurityIsPackageDeveloperWithPackageUuid(item.getModule().getUUID());

      item.remove();
      rulesRepository.save();
    } catch (RulesRepositoryException e) {
      log.error("Unable to remove asset.", e);
      throw e;
    }
  }
  public void testSimplePackageWithDeclaredTypes() throws Exception {
    RulesRepository repo = getRepo();

    PackageItem pkg = repo.createPackage("testSimplePackageWithDeclaredTypes", "");

    AssetItem rule1 = pkg.addAsset("rule_1", "");
    rule1.updateFormat(AssetFormats.DRL);
    rule1.updateContent("rule 'rule1' \n when Album() \n then System.err.println(42); \n end");
    rule1.checkin("");

    AssetItem model = pkg.addAsset("model", "qed");
    model.updateFormat(AssetFormats.DRL_MODEL);

    model.updateContent("declare Album\n genre: String \n end");
    model.checkin("");

    repo.save();

    ContentPackageAssembler asm = new ContentPackageAssembler(pkg);
    assertFalse(asm.hasErrors());
    assertNotNull(asm.getBinaryPackage());
    Package bin = asm.getBinaryPackage();
    assertEquals(pkg.getName(), bin.getName());
    assertTrue(bin.isValid());

    asm = new ContentPackageAssembler(pkg, false);
    String drl = asm.getDRL();

    assertTrue(drl.indexOf("declare Album") > -1);
  }
Example #19
0
  /**
   * Get the function DRLs as one string because they might be calling each others.
   *
   * @return
   */
  private StringBuilder getAllFunctionsAsOneString() {
    AssetItemIterator functionsIterator =
        this.packageItem.listAssetsWithVersionsSpecifiedByDependenciesByFormat(
            AssetFormats.FUNCTION);
    StringBuilder stringBuilder = new StringBuilder();

    while (functionsIterator.hasNext()) {
      AssetItem function = functionsIterator.next();
      if (!function.getDisabled()) {
        stringBuilder.append(function.getContent());
      }
    }

    return stringBuilder;
  }
 protected String[] listImagesInPackage(String packageName) throws SerializationException {
   // load package
   PackageItem item = rulesRepository.loadPackage(packageName);
   List<String> retList = new ArrayList<String>();
   Iterator<AssetItem> iter = item.getAssets();
   while (iter.hasNext()) {
     AssetItem pitem = iter.next();
     if (pitem.getFormat().equalsIgnoreCase("png")
         || pitem.getFormat().equalsIgnoreCase("gif")
         || pitem.getFormat().equalsIgnoreCase("jpg")) {
       retList.add(pitem.getName());
     }
   }
   return (String[]) retList.toArray(new String[] {});
 }
Example #21
0
  private void addDRLRulesToVerifier() {

    AssetItemIterator rules = packageItem.listAssetsByFormat(AssetFormats.DRL);

    while (rules.hasNext()) {
      AssetItem rule = rules.next();

      ContentHandler contentHandler = ContentManager.getHandler(rule.getFormat());
      if (contentHandler.isRuleAsset()) {
        IRuleAsset ruleAsset = (IRuleAsset) contentHandler;
        String drl = ruleAsset.getRawDRL(rule);
        verifier.addResourcesToVerify(
            ResourceFactory.newReaderResource(new StringReader(drl)), ResourceType.DRL);
      }
    }
  }
Example #22
0
  public void retrieveAssetContent(RuleAsset asset, AssetItem item) throws SerializationException {
    RuleModel ruleModel = getBrlXmlPersistence().unmarshal(item.getContent());

    ruleModel.name = asset.getName();

    asset.setContent(ruleModel);
  }
  /** Use this if you want to build and compile just the one asset. */
  public ContentPackageAssembler(AssetItem assetToBuild) {
    this.pkg = assetToBuild.getPackage();
    createBuilder();

    if (preparePackage()) {
      buildAsset(assetToBuild);
    }
  }
  public void testXLSDecisionTable() throws Exception {

    RulesRepository repo = getRepo();

    // first, setup the package correctly:
    PackageItem pkg = repo.createPackage("testXLSDecisionTable", "");

    ServiceImplementation.updateDroolsHeader(
        "import org.acme.insurance.Policy\n import org.acme.insurance.Driver", pkg);
    repo.save();

    InputStream xls = this.getClass().getResourceAsStream("/SampleDecisionTable.xls");
    assertNotNull(xls);

    AssetItem asset = pkg.addAsset("MyDT", "");
    asset.updateFormat(AssetFormats.DECISION_SPREADSHEET_XLS);
    asset.updateBinaryContentAttachment(xls);
    asset.checkin("");

    ContentPackageAssembler asm = new ContentPackageAssembler(pkg);
    if (asm.hasErrors()) {
      System.err.println(asm.getErrors().get(0).errorReport);
      System.err.println(asm.getDRL());
    }
    assertFalse(asm.hasErrors());

    String drl = asm.getDRL();

    assertContains("policy: Policy", drl);

    Package bin = asm.getBinaryPackage();

    RuleBase rb = RuleBaseFactory.newRuleBase();
    rb.addPackage(bin);

    WorkingMemory wm = rb.newStatefulSession();

    // now create some test data
    Driver driver = new Driver();
    Policy policy = new Policy();

    wm.insert(driver);
    wm.insert(policy);

    wm.fireAllRules();

    assertEquals(120, policy.getBasePrice());

    asset.updateBinaryContentAttachment(
        this.getClass().getResourceAsStream("/SampleDecisionTable_WithError.xls"));
    asset.checkin("");
    asm = new ContentPackageAssembler(pkg);
    assertTrue(asm.hasErrors());
    assertEquals(asset.getName(), asm.getErrors().get(0).itemInError.getName());
    asm = new ContentPackageAssembler(pkg, false);
    assertFalse(asm.hasErrors());
    drl = asm.getDRL();
    assertNotNull(drl);
    assertContains("Driverx", drl);
  }
Example #25
0
  private void loadDeclaredTypes() {
    AssetItemIterator declaredTypesIterator =
        this.packageItem.listAssetsWithVersionsSpecifiedByDependenciesByFormat(
            AssetFormats.DRL_MODEL);

    while (declaredTypesIterator.hasNext()) {
      AssetItem assetItem = declaredTypesIterator.next();
      if (!assetItem.getDisabled()) {
        try {
          addDrl(assetItem.getContent());
        } catch (DroolsParserException e) {
          errorLogger.addError(assetItem, "Parser exception: " + e.getMessage());
        } catch (IOException e) {
          errorLogger.addError(assetItem, "IOException: " + e.getMessage());
        }
      }
    }
  }
  /** This will build the package. */
  private void buildPackage() {
    AssetSelector selector = SelectorManager.getInstance().getSelector(selectorConfigName);
    if (selector == null) {
      this.errors.add(
          new ContentAssemblyError(
              this.pkg, "The selector named " + selectorConfigName + " is not available."));
      return;
    }
    Iterator it = pkg.getAssets();
    while (it.hasNext()) {

      AssetItem asset = (AssetItem) it.next();

      if (!asset.isArchived() && (selector.isAssetAllowed(asset))) {
        buildAsset(asset);
      }
    }
  }
  /**
   * This will create a new asset. It will be saved, but not checked in. The initial state will be
   * the draft state. Returns the UUID of the asset.
   */
  public String createNewRule(
      String ruleName,
      String description,
      String initialCategory,
      String initialPackage,
      String format)
      throws SerializationException {
    log.info(
        "USER:"******" CREATING new asset name ["
            + ruleName
            + "] in package ["
            + initialPackage
            + "]");

    try {

      ModuleItem pkg = rulesRepository.loadModule(initialPackage);
      AssetItem asset = pkg.addAsset(ruleName, description, initialCategory, format);

      new AssetTemplateCreator().applyPreBuiltTemplates(ruleName, format, asset);
      rulesRepository.save();

      push("categoryChange", initialCategory);
      push("packageChange", pkg.getName());

      return asset.getUUID();
    } catch (RulesRepositoryException e) {
      // If we want to display an explicit error message of "duplicate asset", we can achieve this
      // in client error handler.
      /*            if ( e.getCause() instanceof ItemExistsException ) {
          return "DUPLICATE";
      }*/
      log.error(
          "An error occurred creating new asset"
              + ruleName
              + "] in package ["
              + initialPackage
              + "]: ",
          e);
      throw new SerializationException(e.getMessage());
    }
  }
  protected InputStream generateZip() {
    List<AssetItem> jarAssets = new LinkedList<AssetItem>();
    AssetZipper assetZipper = null;

    Iterator<AssetItem> assetItemIterator = getAssetItemIterator("jar", "wsdl", "xmlschema");
    while (assetItemIterator.hasNext()) {
      AssetItem assetItem = assetItemIterator.next();
      if (!assetItem.isArchived() && !assetItem.getDisabled()) {
        jarAssets.add(assetItem);
      }
    }
    if (jarAssets.size() != 0) {
      assetZipper = new AssetZipper(jarAssets, null);

      return assetZipper.zipAssets();
    }

    // REVISIT: return an empty zip instead?
    return null;
  }
Example #29
0
  public void testAddFiles() throws Exception {
    RulesRepository repo = RepositorySessionUtil.getRepository();

    repo.createPackage("testAddFiles.package", "just for testing");

    JcrActionFactory fact = new JcrActionFactory(repo);

    byte[] data = "this is content".getBytes();
    ScmAction action = fact.addFile("testAddFiles/package", "someFile.drl", data);

    fact.execute(action, "some message");

    PackageItem pk = repo.loadPackage("testAddFiles.package");
    AssetItem asset = pk.loadAsset("someFile");

    assertEquals("drl", asset.getFormat());
    assertEquals("this is content", asset.getContent());
    assertEquals("some message", asset.getDescription());
    assertEquals("Draft", asset.getStateDescription());
  }
Example #30
0
  private void addToVerifier(AssetItemIterator assets, ResourceType resourceType) {
    while (assets.hasNext()) {
      AssetItem asset = assets.next();
      if (!asset.isArchived() && !asset.getDisabled()) {
        if (resourceType == ResourceType.DTABLE) {
          DecisionTableConfiguration dtableconfiguration =
              KnowledgeBuilderFactory.newDecisionTableConfiguration();
          dtableconfiguration.setInputType(DecisionTableInputType.XLS);

          verifier.addResourcesToVerify(
              ResourceFactory.newByteArrayResource(asset.getBinaryContentAsBytes()),
              resourceType,
              (ResourceConfiguration) dtableconfiguration);
        } else {
          verifier.addResourcesToVerify(
              ResourceFactory.newReaderResource(new StringReader(asset.getContent())),
              resourceType);
        }
      }
    }
  }