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 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;
  }
  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());
    }
  }
  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);
  }
  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);
  }
  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;
    }
  }
  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;
    }
  }
  /**
   * 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;
  }
  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);
    }
  }
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public void changePackageState(String uuid, String newState) {

    serviceSecurity.checkSecurityIsPackageDeveloper(uuid);

    PackageItem pkg = getRulesRepository().loadPackageByUUID(uuid);
    log.info(
        "USER:"******" CHANGING Package STATUS. Asset name, uuid: "
            + "["
            + pkg.getName()
            + ", "
            + pkg.getUUID()
            + "]"
            + " to ["
            + newState
            + "]");
    pkg.changeStatus(newState);

    getRulesRepository().save();
  }