/** 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());
    }
  }
  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);
  }
  /**
   * 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 void copyOrRemoveSnapshot(
      String packageName, String snapshotName, boolean delete, String newSnapshotName)
      throws SerializationException {

    if (delete) {
      log.info(
          "USER:"******" REMOVING SNAPSHOT for package: ["
              + packageName
              + "] snapshot: ["
              + snapshotName
              + "]");
      rulesRepository.removePackageSnapshot(packageName, snapshotName);
    } else {
      if (newSnapshotName.equals("")) {
        throw new SerializationException("Need to have a new snapshot name.");
      }
      log.info(
          "USER:"******" COPYING SNAPSHOT for package: ["
              + packageName
              + "] snapshot: ["
              + snapshotName
              + "] to ["
              + newSnapshotName
              + "]");

      rulesRepository.copyPackageSnapshot(packageName, snapshotName, newSnapshotName);
    }
  }
  /**
   * Role-based Authorization check: This method can be accessed if user has following permissions:
   * 1. The user has a Analyst role and this role has permission to access the category which the
   * asset belongs to. Or. 2. The user has a package.developer role or higher (i.e., package.admin)
   * and this role has permission to access the package which the asset belongs to.
   */
  @WebRemote
  @LoggedIn
  public void changeState(String uuid, String newState) {
    AssetItem asset = rulesRepository.loadAssetByUUID(uuid);
    serviceSecurity.checkIsPackageDeveloperOrAnalyst(asset);

    log.info(
        "USER:"******" CHANGING ASSET STATUS. Asset name, uuid: "
            + "["
            + asset.getName()
            + ", "
            + asset.getUUID()
            + "]"
            + " to ["
            + newState
            + "]");
    String oldState = asset.getStateDescription();
    asset.updateState(newState);

    push("statusChange", oldState);
    push("statusChange", newState);

    addToDiscussionForAsset(asset.getUUID(), oldState + " -> " + newState);

    rulesRepository.save();
  }
  /**
   * 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());
    }
  }
  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());
  }
  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());
  }
  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());
  }
  /** 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());
  }
  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;
    }
  }
Beispiel #14
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);
  }
  public void removeState(String name) throws SerializationException {
    log.info("USER:"******" REMOVING state: [" + name + "]");

    try {
      rulesRepository.loadState(name).remove();
      rulesRepository.save();

    } catch (RulesRepositoryException e) {
      throw new DetailedSerializationException(
          "Unable to remove status. It is probably still used (even by archived items).",
          e.getMessage());
    }
  }
 /** For the time being, module == package */
 public void updateWorkspace(
     String workspace, String[] selectedModules, String[] unselectedModules) {
   for (String moduleName : selectedModules) {
     ModuleItem module = rulesRepository.loadModule(moduleName);
     module.addWorkspace(workspace);
     module.checkin("Add workspace");
   }
   for (String moduleName : unselectedModules) {
     ModuleItem module = rulesRepository.loadModule(moduleName);
     module.removeWorkspace(workspace);
     module.checkin("Remove workspace");
   }
 }
  @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 PageResponse<QueryPageRow> queryMetaData(QueryMetadataPageRequest request)
      throws SerializationException {
    if (request == null) {
      throw new IllegalArgumentException("request cannot be null");
    }
    if (request.getPageSize() != null && request.getPageSize() < 0) {
      throw new IllegalArgumentException("pageSize cannot be less than zero.");
    }

    // Setup parameters for generic repository query
    Map<String, String[]> queryMap = createQueryMap(request.getMetadata());

    DateQuery[] dates = createDateQueryForRepository(request);

    long start = System.currentTimeMillis();
    AssetItemIterator iterator = rulesRepository.query(queryMap, request.isSearchArchived(), dates);
    log.debug("Search time: " + (System.currentTimeMillis() - start));

    List<QueryPageRow> rowList =
        new QueryMetadataPageRowBuilder().withPageRequest(request).withContent(iterator).build();
    boolean bHasMoreRows = iterator.hasNext();
    PageResponse<QueryPageRow> response =
        new PageResponseBuilder<QueryPageRow>()
            .withStartRowIndex(request.getStartRowIndex())
            .withPageRowList(rowList)
            .withLastPage(!bHasMoreRows)
            .buildWithTotalRowCount(
                -1); // its impossible to know the exact selected count until we'v reached
    // the end of iterator
    long methodDuration = System.currentTimeMillis() - start;
    log.debug("Queried repository (Metadata) in " + methodDuration + " ms.");
    return response;
  }
  public PageResponse<QueryPageRow> queryFullText(QueryPageRequest request)
      throws SerializationException {
    if (request == null) {
      throw new IllegalArgumentException("request cannot be null");
    }
    if (request.getPageSize() != null && request.getPageSize() < 0) {
      throw new IllegalArgumentException("pageSize cannot be less than zero.");
    }

    long start = System.currentTimeMillis();
    AssetItemIterator iterator =
        rulesRepository.queryFullText(request.getSearchText(), request.isSearchArchived());
    log.debug("Search time: " + (System.currentTimeMillis() - start));

    List<QueryPageRow> rowList =
        new QueryFullTextPageRowBuilder().withPageRequest(request).withContent(iterator).build();
    boolean bHasMoreRows = iterator.hasNext();
    PageResponse<QueryPageRow> response =
        new PageResponseBuilder<QueryPageRow>()
            .withStartRowIndex(request.getStartRowIndex())
            .withPageRowList(rowList)
            .withLastPage(!bHasMoreRows)
            .buildWithTotalRowCount(-1);

    long methodDuration = System.currentTimeMillis() - start;
    log.debug(
        "Queried repository (Full Text) for ("
            + request.getSearchText()
            + ") in "
            + methodDuration
            + " ms.");
    return response;
  }
  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 {
    }
  }
  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());
    }
  }
 @LoggedIn
 public ConversionResult convertAsset(String uuid, String targetFormat)
     throws SerializationException {
   AssetItem item = rulesRepository.loadAssetByUUID(uuid);
   serviceSecurity.checkIsPackageDeveloperOrAnalyst(item);
   return conversionService.convert(item, targetFormat);
 }
  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);
    }
  }
  @Roles({"ADMIN"})
  public void updateUserPermissions(String userName, Map<String, List<String>> perms) {
    PermissionManager pm = new PermissionManager(rulesRepository);

    log.info("Updating user permissions for userName [" + userName + "] to [" + perms + "]");
    pm.updateUserPermissions(userName, perms);
    rulesRepository.save();
  }
  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);
  }
  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();
  }
 public String[] listStates() throws SerializationException {
   StateItem[] states = rulesRepository.listStates();
   String[] result = new String[states.length];
   for (int i = 0; i < states.length; i++) {
     result[i] = states[i].getName();
   }
   return result;
 }
 /** @deprecated in favour of {@link #findAssetPage(AssetPageRequest)} */
 @WebRemote
 @LoggedIn
 public TableDataResult listAssetsWithPackageName(
     String packageName, String formats[], int skip, int numRows, String tableConfig)
     throws SerializationException {
   ModuleItem pkg = rulesRepository.loadModule(packageName);
   return listAssets(pkg.getUUID(), formats, skip, numRows, tableConfig);
 }
 @LoggedIn
 public List<DiscussionRecord> loadDiscussionForAsset(String assetId) {
   return new Discussion()
       .fromString(
           rulesRepository
               .loadAssetByUUID(assetId)
               .getStringProperty(Discussion.DISCUSSION_PROPERTY_KEY));
 }
  @WebRemote
  @LoggedIn
  public String renameAsset(String uuid, String newName) {
    AssetItem item = rulesRepository.loadAssetByUUID(uuid);
    serviceSecurity.checkIsPackageDeveloperOrAnalyst(item);

    return repositoryAssetOperations.renameAsset(uuid, newName);
  }