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);
  }
  private void updatePackageBinaries(PackageItem item, PackageAssembler packageAssembler)
      throws DetailedSerializationException {
    try {
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      ObjectOutput out = new DroolsObjectOutputStream(bout);
      out.writeObject(packageAssembler.getBinaryPackage());

      item.updateCompiledPackage(new ByteArrayInputStream(bout.toByteArray()));
      out.flush();
      out.close();

      item.updateBinaryUpToDate(true);

      RuleBase ruleBase =
          RuleBaseFactory.newRuleBase(new RuleBaseConfiguration(getClassLoaders(packageAssembler)));
      ruleBase.addPackage(packageAssembler.getBinaryPackage());

      rulesRepository.save();
    } catch (Exception e) {
      e.printStackTrace();
      log.error(
          "An error occurred building the package [" + item.getName() + "]: " + e.getMessage());
      throw new DetailedSerializationException(
          "An error occurred building the package.", e.getMessage());
    }
  }
  /**
   * This this case we will test errors that occur in rule assets, not in functions or package
   * header.
   */
  public void testErrorsInRuleAsset() throws Exception {

    RulesRepository repo = getRepo();

    // first, setup the package correctly:
    PackageItem pkg = repo.createPackage("testErrorsInRuleAsset", "");
    AssetItem model = pkg.addAsset("model", "qed");
    model.updateFormat(AssetFormats.MODEL);
    model.updateBinaryContentAttachment(this.getClass().getResourceAsStream("/billasurf.jar"));
    model.checkin("");
    ServiceImplementation.updateDroolsHeader(
        "import com.billasurf.Board\n global com.billasurf.Person customer", pkg);
    repo.save();

    AssetItem goodRule = pkg.addAsset("goodRule", "");
    goodRule.updateFormat(AssetFormats.DRL);
    goodRule.updateContent("rule 'yeah' \n when \n Board() \n then \n System.out.println(42); end");
    goodRule.checkin("");

    AssetItem badRule = pkg.addAsset("badRule", "xxx");
    badRule.updateFormat(AssetFormats.DRL);
    badRule.updateContent("if something then another");
    badRule.checkin("");

    ContentPackageAssembler asm = new ContentPackageAssembler(pkg);
    assertTrue(asm.hasErrors());
    assertFalse(asm.isPackageConfigurationInError());

    for (ContentAssemblyError err : asm.getErrors()) {
      assertTrue(err.itemInError.getName().equals(badRule.getName()));
      assertNotEmpty(err.errorReport);
    }
  }
  public void testIgnoreArchivedItems() throws Exception {
    RulesRepository repo = getRepo();

    PackageItem pkg = repo.createPackage("testIgnoreArchivedItems", "");
    AssetItem model = pkg.addAsset("model", "qed");
    model.updateFormat(AssetFormats.MODEL);

    model.updateBinaryContentAttachment(this.getClass().getResourceAsStream("/billasurf.jar"));
    model.checkin("");

    ServiceImplementation.updateDroolsHeader(
        "import com.billasurf.Board\n global com.billasurf.Person customer", pkg);

    AssetItem rule1 = pkg.addAsset("rule_1", "");
    rule1.updateFormat(AssetFormats.DRL);
    rule1.updateContent("rule 'rule1' \n when Board() \n then customer.setAge(42); \n end");
    rule1.checkin("");

    AssetItem rule2 = pkg.addAsset("rule2", "");
    rule2.updateFormat(AssetFormats.DRL);
    rule2.updateContent("agenda-group 'q' \n when \n Boardx() \n then \n System.err.println(42);");
    rule2.checkin("");

    repo.save();

    ContentPackageAssembler asm = new ContentPackageAssembler(pkg);
    assertTrue(asm.hasErrors());

    rule2.archiveItem(true);
    rule2.checkin("");

    assertTrue(rule2.isArchived());
    asm = new ContentPackageAssembler(pkg);
    assertFalse(asm.hasErrors());
  }
  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);
  }
  protected String createPackage(String name, String description, String format, String[] workspace)
      throws RulesRepositoryException {

    log.info("USER: "******" CREATING package [" + name + "]");
    PackageItem item = rulesRepository.createPackage(name, description, format, workspace);

    return item.getUUID();
  }
 /** @deprecated in favour of {@link findAssetPage(AssetPageRequest)} */
 @WebRemote
 @Restrict("#{identity.loggedIn}")
 public TableDataResult listAssetsWithPackageName(
     String packageName, String formats[], int skip, int numRows, String tableConfig)
     throws SerializationException {
   PackageItem pkg = getRulesRepository().loadPackage(packageName);
   return listAssets(pkg.getUUID(), formats, skip, numRows, tableConfig);
 }
  /** @deprecated in favour of {@link loadArchivedAssets(PageRequest)} */
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public TableDataResult loadAssetHistory(String packageUUID, String assetName)
      throws SerializationException {
    PackageItem pi = getRulesRepository().loadPackageByUUID(packageUUID);
    AssetItem assetItem = pi.loadAsset(assetName);
    serviceSecurity.checkSecurityAssetPackagePackageReadOnly(assetItem);

    return repositoryAssetOperations.loadItemHistory(assetItem);
  }
  public void savePackage(PackageConfigData data) throws SerializationException {
    log.info("USER:"******" SAVING package [" + data.getName() + "]");

    PackageItem item = rulesRepository.loadPackage(data.getName());

    // If package is being unarchived.
    boolean unarchived = (!data.isArchived() && item.isArchived());
    Calendar packageLastModified = item.getLastModified();

    DroolsHeader.updateDroolsHeader(data.getHeader(), item);
    updateCategoryRules(data, item);

    item.updateExternalURI(data.getExternalURI());
    item.updateDescription(data.getDescription());
    item.archiveItem(data.isArchived());
    item.updateBinaryUpToDate(false);
    if (!data.getFormat().equals("")) {
      item.updateFormat(data.getFormat());
    }
    RuleBaseCache.getInstance().remove(data.getUuid());
    item.checkin(data.getDescription());

    // If package is archived, archive all the assets under it
    if (data.isArchived()) {
      handleArchivedForSavePackage(data, item);
    } else if (unarchived) {
      handleUnarchivedForSavePackage(data, item, packageLastModified);
    }
  }
  public void testPackageWithRuleflow() throws Exception {
    RulesRepository repo = getRepo();

    PackageItem pkg = repo.createPackage("testPackageWithRuleFlow", "");
    AssetItem model = pkg.addAsset("model", "qed");
    model.updateFormat(AssetFormats.MODEL);

    model.updateBinaryContentAttachment(this.getClass().getResourceAsStream("/billasurf.jar"));
    model.checkin("");

    ServiceImplementation.updateDroolsHeader(
        "import com.billasurf.Board\n global com.billasurf.Person customer", pkg);

    AssetItem rule1 = pkg.addAsset("rule_1", "");
    rule1.updateFormat(AssetFormats.DRL);
    rule1.updateContent("rule 'rule1' \n when Board() \n then customer.setAge(42); \n end");
    rule1.checkin("");

    AssetItem ruleFlow = pkg.addAsset("ruleFlow", "");
    ruleFlow.updateFormat(AssetFormats.RULE_FLOW_RF);

    ruleFlow.updateBinaryContentAttachment(this.getClass().getResourceAsStream("/ruleflow.rfm"));
    ruleFlow.checkin("");

    ContentPackageAssembler asm = new ContentPackageAssembler(pkg);
    assertFalse(asm.hasErrors());
    Map flows = asm.getBinaryPackage().getRuleFlows();
    assertNotNull(flows);

    assertEquals(1, flows.size());
    Object flow = flows.values().iterator().next();
    assertNotNull(flow);
    assertTrue(flow instanceof RuleFlowProcess);

    // now check we can do some MVEL stuff from the classloader...
    List<JarInputStream> jars = BRMSPackageBuilder.getJars(pkg);
    PackageBuilder builder = BRMSPackageBuilder.getInstance(jars);
    ClassLoader newCL = builder.getPackageBuilderConfiguration().getClassLoader();
    ClassLoader oldCL = Thread.currentThread().getContextClassLoader();

    // set the CL for the current thread so MVEL can find it
    Thread.currentThread().setContextClassLoader(newCL);

    Object o = MVEL.eval("new com.billasurf.Board()");
    assertEquals("com.billasurf.Board", o.getClass().getName());
    System.err.println(o.toString());

    Thread.currentThread().setContextClassLoader(oldCL);

    builder.addPackageFromDrl(new StringReader("package foo\n import com.billasurf.Board"));
    Object o2 = builder.getPackageRegistry("foo").getTypeResolver().resolveType("Board");
    assertNotNull(o2);
    assertEquals("com.billasurf.Board", ((Class) o2).getName());
  }
  protected void removePackage(String uuid) {

    try {
      PackageItem item = rulesRepository.loadPackageByUUID(uuid);
      log.info("USER:"******" REMOVEING package [" + item.getName() + "]");
      item.remove();
      rulesRepository.save();
    } catch (RulesRepositoryException e) {
      log.error("Unable to remove package.", e);
      throw e;
    }
  }
  protected PackageConfigData loadGlobalPackage() {
    PackageItem item = rulesRepository.loadGlobalArea();

    PackageConfigData data =
        PackageConfigDataFactory.createPackageConfigDataWithOutDependencies(item);

    if (data.isSnapshot()) {
      data.setSnapshotName(item.getSnapshotName());
    }

    return data;
  }
示例#13
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);
  }
 protected String createSubPackage(String name, String description, String parentNode)
     throws SerializationException {
   log.info(
       "USER: "******" CREATING subPackage ["
           + name
           + "], parent ["
           + parentNode
           + "]");
   PackageItem item = rulesRepository.createSubPackage(name, description, parentNode);
   return item.getUUID();
 }
示例#15
0
  /**
   * This actually does the hard work of loading up an asset based on its format.
   *
   * <p>Role-based Authorization check: This method can be accessed if user has following
   * permissions: 1. The user has a ANALYST_READ role or higher (i.e., ANALYST) and this role has
   * permission to access the category which the asset belongs to. Or. 2. The user has a
   * package.readonly role or higher (i.e., package.admin, package.developer) and this role has
   * permission to access the package which the asset belongs to.
   */
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public RuleAsset loadRuleAsset(String uuid) throws SerializationException {

    long time = System.currentTimeMillis();

    AssetItem item = getRulesRepository().loadAssetByUUID(uuid);
    RuleAsset asset = new RuleAsset();

    asset.uuid = item.getUUID();
    asset.name = item.getName();
    asset.description = item.getDescription();
    asset.lastModified = item.getLastModified().getTime();
    asset.lastContributor = item.getLastContributor();
    asset.state = (item.getState() != null) ? item.getState().getName() : "";
    asset.dateCreated = item.getCreatedDate().getTime();
    asset.checkinComment = item.getCheckinComment();
    asset.versionNumber = item.getVersionNumber();

    // load standard meta data
    asset.metaData = repositoryAssetOperations.populateMetaData(item);

    // Verify if the user has permission to access the asset through package
    // based permission.
    // If failed, then verify if the user has permission to access the asset
    // through category
    // based permission
    if (Contexts.isSessionContextActive()) {

      try {
        Identity.instance()
            .checkPermission(
                new PackageNameType(asset.metaData.packageName), RoleTypes.PACKAGE_READONLY);
      } catch (RuntimeException e) {
        handleLoadRuleAssetException(asset);
      }
    }

    PackageItem pkgItem = handlePackageItem(item, asset);

    log.debug(
        "Package: "
            + pkgItem.getName()
            + ", asset: "
            + item.getName()
            + ". Load time taken for asset: "
            + (System.currentTimeMillis() - time));
    UserInbox.recordOpeningEvent(item);
    return asset;
  }
示例#16
0
  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;
    }
  }
示例#17
0
  private PackageItem handlePackageItem(AssetItem item, RuleAsset asset)
      throws SerializationException {
    PackageItem pkgItem = item.getPackage();

    ContentHandler handler = ContentManager.getHandler(asset.metaData.format);
    handler.retrieveAssetContent(asset, pkgItem, item);

    asset.isreadonly = asset.metaData.hasSucceedingVersion;

    if (pkgItem.isSnapshot()) {
      asset.isreadonly = true;
    }
    return pkgItem;
  }
 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[] {});
 }
示例#19
0
  /**
   * 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 PackageConfigData loadPackageConfig(PackageItem packageItem) {
   PackageConfigData data =
       PackageConfigDataFactory.createPackageConfigDataWithDependencies(packageItem);
   if (data.isSnapshot()) {
     data.setSnapshotName(packageItem.getSnapshotName());
   }
   return data;
 }
示例#21
0
  private void addHeaderToVerifier() {
    StringBuffer header = new StringBuffer();
    header.append("package " + packageItem.getName() + "\n");
    header.append(ServiceImplementation.getDroolsHeader(packageItem) + "\n");

    verifier.addResourcesToVerify(
        ResourceFactory.newReaderResource(new StringReader(header.toString())), ResourceType.DRL);
  }
  public void testCustomSelector() throws Exception {
    RulesRepository repo = getRepo();

    // create our package
    PackageItem pkg = repo.createPackage("testCustomSelector", "");
    ServiceImplementation.updateDroolsHeader("import org.drools.Person", pkg);
    AssetItem rule1 = pkg.addAsset("rule1", "");
    rule1.updateFormat(AssetFormats.DRL);

    rule1.updateContent("when \n Person() \n then \n System.out.println(\"yeah\");\n");
    rule1.checkin("");

    AssetItem rule2 = pkg.addAsset("rule2", "");
    rule2.updateFormat(AssetFormats.DRL);

    rule2.updateContent("when \n Person() \n then \n System.out.println(\"yeah\");\n");
    rule2.checkin("");

    SelectorManager sm = SelectorManager.getInstance();
    sm.selectors.put(
        "testSelect",
        new AssetSelector() {
          public boolean isAssetAllowed(AssetItem asset) {
            return asset.getName().equals("rule2");
          }
        });

    ContentPackageAssembler asm = new ContentPackageAssembler(pkg, "testSelect");

    Package pk = asm.getBinaryPackage();
    assertEquals(1, pk.getRules().length);
    assertEquals("rule2", pk.getRules()[0].getName());

    asm = new ContentPackageAssembler(pkg, null);
    pk = asm.getBinaryPackage();
    assertEquals(2, pk.getRules().length);

    asm = new ContentPackageAssembler(pkg, "nothing valid");
    assertTrue(asm.hasErrors());
    assertEquals(1, asm.getErrors().size());
    assertEquals(pkg, asm.getErrors().get(0).itemInError);

    asm = new ContentPackageAssembler(pkg, "");
    pk = asm.getBinaryPackage();
    assertEquals(2, pk.getRules().length);
  }
  private PackageConfigData[] listSubPackages(
      PackageItem parentPkg, boolean archive, String workspace, RepositoryFilter filter) {
    List<PackageConfigData> children = new LinkedList<PackageConfigData>();

    handleIteratePackages(archive, workspace, filter, children, parentPkg.listSubPackages());

    sortPackages(children);
    return children.toArray(new PackageConfigData[children.size()]);
  }
 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());
     }
   }
 }
  public void testSimplePackageBuildNoErrors() throws Exception {
    RulesRepository repo = getRepo();

    PackageItem pkg = repo.createPackage("testSimplePackageBuildNoErrors", "");
    AssetItem model = pkg.addAsset("model", "qed");
    model.updateFormat(AssetFormats.MODEL);

    model.updateBinaryContentAttachment(this.getClass().getResourceAsStream("/billasurf.jar"));
    model.checkin("");

    ServiceImplementation.updateDroolsHeader(
        "import com.billasurf.Board\n global com.billasurf.Person customer", pkg);

    AssetItem rule1 = pkg.addAsset("rule_1", "");
    rule1.updateFormat(AssetFormats.DRL);
    rule1.updateContent("rule 'rule1' \n when Board() \n then customer.setAge(42); \n end");
    rule1.checkin("");

    AssetItem rule2 = pkg.addAsset("rule2", "");
    rule2.updateFormat(AssetFormats.DRL);
    rule2.updateContent("agenda-group 'q' \n when \n Board() \n then \n System.err.println(42);");
    rule2.checkin("");

    AssetItem rule3 = pkg.addAsset("A file", "");
    rule3.updateFormat(AssetFormats.DRL);
    rule3.updateContent(
        "package testSimplePackageBuildNoErrors\n rule 'rule3' \n when \n then \n customer.setAge(43); \n end \n"
            + "rule 'rule4' \n when \n then \n System.err.println(44); \n end");
    rule3.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());

    assertEquals(4, bin.getRules().length);

    // now create a snapshot
    repo.createPackageSnapshot(pkg.getName(), "SNAP_1");

    // and screw up the the non snapshot one
    ServiceImplementation.updateDroolsHeader("koo koo ca choo", pkg);
    asm = new ContentPackageAssembler(pkg);
    assertTrue(asm.hasErrors());

    // check the snapshot is kosher
    pkg = repo.loadPackageSnapshot(pkg.getName(), "SNAP_1");
    asm = new ContentPackageAssembler(pkg);
    assertFalse(asm.hasErrors());
  }
  /** This time, we mix up stuff a bit */
  public void testRuleAndDSLAndFunction() throws Exception {
    RulesRepository repo = getRepo();

    // first, setup the package correctly:
    PackageItem pkg = repo.createPackage("testRuleAndDSLAndFunction", "");
    AssetItem model = pkg.addAsset("model", "qed");
    model.updateFormat(AssetFormats.MODEL);
    model.updateBinaryContentAttachment(this.getClass().getResourceAsStream("/billasurf.jar"));
    model.checkin("");
    ServiceImplementation.updateDroolsHeader(
        "import com.billasurf.Board\n global com.billasurf.Person customer", pkg);
    repo.save();

    AssetItem func = pkg.addAsset("func", "");
    func.updateFormat(AssetFormats.FUNCTION);
    func.updateContent("function void foo() { System.out.println(42); }");
    func.checkin("");

    AssetItem dsl = pkg.addAsset("myDSL", "");
    dsl.updateFormat(AssetFormats.DSL);
    dsl.updateContent("[then]call a func=foo();");
    dsl.checkin("");

    AssetItem dsl2 = pkg.addAsset("myDSL2", "");
    dsl2.updateFormat(AssetFormats.DSL);
    dsl2.updateContent("[when]There is a board=Board()");
    dsl2.checkin("");

    AssetItem rule = pkg.addAsset("myRule", "");
    rule.updateFormat(AssetFormats.DSL_TEMPLATE_RULE);
    rule.updateContent("when \n There is a board \n then \n call a func");
    rule.checkin("");

    AssetItem rule2 = pkg.addAsset("myRule2", "");
    rule2.updateFormat(AssetFormats.DSL_TEMPLATE_RULE);
    rule2.updateContent(
        "package testRuleAndDSLAndFunction \n rule 'myRule2222' \n when \n There is a board \n then \n call a func \nend");
    rule2.checkin("");

    AssetItem rule3 = pkg.addAsset("myRule3", "");
    rule3.updateFormat(AssetFormats.DRL);
    rule3.updateContent(
        "package testRuleAndDSLAndFunction\n rule 'rule3' \n when \n Board() \n then \n System.err.println(42); end");
    rule3.checkin("");

    repo.save();

    ContentPackageAssembler asm = new ContentPackageAssembler(pkg);
    assertFalse(asm.hasErrors());
    Package bin = asm.getBinaryPackage();
    assertNotNull(bin);
    assertEquals(3, bin.getRules().length);
    assertEquals(1, bin.getFunctions().size());
  }
 @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 testShowSource() throws Exception {
    RulesRepository repo = getRepo();

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

    ServiceImplementation.updateDroolsHeader(
        "import com.billasurf.Board\n global com.billasurf.Person customer", pkg);
    repo.save();

    AssetItem func = pkg.addAsset("func", "");
    func.updateFormat(AssetFormats.FUNCTION);
    func.updateContent("function void foo() { System.out.println(42); }");
    func.checkin("");

    AssetItem dsl = pkg.addAsset("myDSL", "");
    dsl.updateFormat(AssetFormats.DSL);
    dsl.updateContent("[then]call a func=foo();\n[when]foo=FooBarBaz()");
    dsl.checkin("");

    AssetItem rule = pkg.addAsset("rule1", "");
    rule.updateFormat(AssetFormats.DRL);
    rule.updateContent("rule 'foo' when Goo() then end");
    rule.checkin("");

    AssetItem rule2 = pkg.addAsset("rule2", "");
    rule2.updateFormat(AssetFormats.DSL_TEMPLATE_RULE);
    rule2.updateContent("when \n foo \n then \n call a func");
    rule2.checkin("");

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

    assertNotNull(drl);

    assertContains("import com.billasurf.Board\n global com.billasurf.Person customer", drl);
    assertContains("package testShowSource", drl);
    assertContains("function void foo() { System.out.println(42); }", drl);
    assertContains("foo();", drl);
    assertContains("FooBarBaz()", drl);
    assertContains("rule 'foo' when Goo() then end", drl);
  }
  private void handleIteratePackages(
      boolean archive,
      String workspace,
      RepositoryFilter filter,
      List<PackageConfigData> result,
      PackageIterator pkgs) {
    pkgs.setArchivedIterator(archive);
    while (pkgs.hasNext()) {
      PackageItem packageItem = pkgs.next();

      PackageConfigData data = new PackageConfigData();
      data.setUuid(packageItem.getUUID());
      data.setName(packageItem.getName());
      data.setArchived(packageItem.isArchived());
      data.setWorkspaces(packageItem.getWorkspaces());
      handleIsPackagesListed(archive, workspace, filter, result, data);

      data.subPackages = listSubPackages(packageItem, archive, null, filter);
    }
  }
  protected void createPackageSnapshot(
      String packageName, String snapshotName, boolean replaceExisting, String comment) {

    log.info(
        "USER:"******" CREATING PACKAGE SNAPSHOT for package: ["
            + packageName
            + "] snapshot name: ["
            + snapshotName);

    if (replaceExisting) {
      rulesRepository.removePackageSnapshot(packageName, snapshotName);
    }

    rulesRepository.createPackageSnapshot(packageName, snapshotName);
    PackageItem item = rulesRepository.loadPackageSnapshot(packageName, snapshotName);
    item.updateCheckinComment(comment);
    rulesRepository.save();
  }