Ejemplo n.º 1
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;
    }
  }
Ejemplo n.º 2
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;
  }
Ejemplo n.º 3
0
  /**
   * 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();
  }
  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);
    }
  }
Ejemplo n.º 6
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));
 }
 private AdminArchivedPageRow makeAdminArchivedPageRow(AssetItem assetItem) {
   AdminArchivedPageRow row = new AdminArchivedPageRow();
   row.setUuid(assetItem.getUUID());
   row.setFormat(assetItem.getFormat());
   row.setName(assetItem.getName());
   row.setPackageName(assetItem.getPackageName());
   row.setLastContributor(assetItem.getLastContributor());
   row.setLastModified(assetItem.getLastModified().getTime());
   return row;
 }
Ejemplo n.º 8
0
  public static Asset toAsset(AssetItem a, UriInfo uriInfo) {
    AssetMetadata metadata = new AssetMetadata();
    metadata.setUuid(a.getUUID());
    metadata.setCreated(a.getCreatedDate().getTime());
    metadata.setDisabled(a.getDisabled());
    metadata.setFormat(a.getFormat());
    metadata.setNote("<![CDATA[ " + a.getCheckinComment() + " ]]>");
    metadata.setCheckInComment(a.getCheckinComment());
    metadata.setVersionNumber(a.getVersionNumber());
    List<CategoryItem> categories = a.getCategories();
    // TODO: Is this a bug since cat's are never assigned to metadata after this?
    String[] cats = new String[categories.size()];
    int counter = 0;
    for (CategoryItem c : categories) {
      cats[counter++] = c.getName();
    }

    Asset ret = new Asset();
    ret.setTitle(a.getTitle());
    ret.setBinaryContentAttachmentFileName(a.getBinaryContentAttachmentFileName());
    ret.setPublished(a.getLastModified().getTime());
    ret.setAuthor(a.getLastContributor());
    ret.setMetadata(metadata);
    ret.setDescription(a.getDescription());
    ret.setRefLink(
        uriInfo
            .getBaseUriBuilder()
            .path("/packages/{packageName}/assets/{assetName}")
            .build(a.getModule().getName(), a.getName()));
    ret.setBinaryLink(
        uriInfo
            .getBaseUriBuilder()
            .path("/packages/{packageName}/assets/{assetName}/binary")
            .build(a.getModule().getName(), a.getName()));
    ret.setSourceLink(
        uriInfo
            .getBaseUriBuilder()
            .path("/packages/{packageName}/assets/{assetName}/source")
            .build(a.getModule().getName(), a.getName()));
    return ret;
  }
 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[] {});
 }
Ejemplo n.º 10
0
  @Test
  public void testValidating() throws Exception {
    RulesRepository repo = getRulesRepository();
    PackageItem pkg = repo.loadDefaultPackage();
    AssetItem asset = pkg.addAsset("testValidatingEnum", "");
    asset.updateFormat(AssetFormats.ENUMERATION);
    asset.updateContent("'Person.age' : [1, 2, 3]");

    EnumerationContentHandler ch = new EnumerationContentHandler();
    BuilderResult result = ch.validateAsset(asset);
    assertNotNull(result);
    assertEquals(0, result.getLines().size());

    asset.updateContent("goober boy");
    result = ch.validateAsset(asset);
    assertFalse(result.getLines().size() == 0);
    assertEquals(asset.getName(), result.getLines().get(0).getAssetName());
    assertEquals(asset.getFormat(), result.getLines().get(0).getAssetFormat());
    assertNotNull(result.getLines().get(0).getMessage());
    assertEquals(asset.getUUID(), result.getLines().get(0).getUuid());
  }
Ejemplo n.º 11
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
  @LoggedIn
  public Asset loadRuleAsset(String uuid) throws SerializationException {

    long time = System.currentTimeMillis();

    AssetItem item = rulesRepository.loadAssetByUUID(uuid);
    Asset asset = new AssetPopulator().populateFrom(item);

    asset.setMetaData(repositoryAssetOperations.populateMetaData(item));

    serviceSecurity.checkIsPackageReadOnlyOrAnalystReadOnly(asset);
    ModuleItem 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 boolean isPackageItemDeleted(PackageItem rightPackage, AssetItem left) {
   return !rightPackage.containsAsset(left.getName());
 }
  /** @deprecated in favour of {@link compareSnapshots(SnapshotComparisonPageRequest)} */
  protected SnapshotDiffs compareSnapshots(
      String packageName, String firstSnapshotName, String secondSnapshotName) {
    SnapshotDiffs diffs = new SnapshotDiffs();
    List<SnapshotDiff> list = new ArrayList<SnapshotDiff>();

    PackageItem leftPackage = rulesRepository.loadPackageSnapshot(packageName, firstSnapshotName);
    PackageItem rightPackage = rulesRepository.loadPackageSnapshot(packageName, secondSnapshotName);

    // Older one has to be on the left.
    if (isRightOlderThanLeft(leftPackage, rightPackage)) {
      PackageItem temp = leftPackage;
      leftPackage = rightPackage;
      rightPackage = temp;

      diffs.leftName = secondSnapshotName;
      diffs.rightName = firstSnapshotName;
    } else {
      diffs.leftName = firstSnapshotName;
      diffs.rightName = secondSnapshotName;
    }

    Iterator<AssetItem> leftExistingIter = leftPackage.getAssets();
    while (leftExistingIter.hasNext()) {
      AssetItem left = leftExistingIter.next();
      if (isPackageItemDeleted(rightPackage, left)) {
        SnapshotDiff diff = new SnapshotDiff();

        diff.name = left.getName();
        diff.diffType = SnapshotDiff.TYPE_DELETED;
        diff.leftUuid = left.getUUID();

        list.add(diff);
      }
    }

    Iterator<AssetItem> rightExistingIter = rightPackage.getAssets();
    while (rightExistingIter.hasNext()) {
      AssetItem right = rightExistingIter.next();
      AssetItem left = null;
      if (right != null && leftPackage.containsAsset(right.getName())) {
        left = leftPackage.loadAsset(right.getName());
      }

      // Asset is deleted or added
      if (right == null || left == null) {
        SnapshotDiff diff = new SnapshotDiff();

        if (left == null) {
          diff.name = right.getName();
          diff.diffType = SnapshotDiff.TYPE_ADDED;
          diff.rightUuid = right.getUUID();
        }

        list.add(diff);
      } else if (isAssetArchivedOrRestored(right, left)) { // Has the asset
        // been archived
        // or restored
        SnapshotDiff diff = new SnapshotDiff();

        diff.name = right.getName();
        diff.leftUuid = left.getUUID();
        diff.rightUuid = right.getUUID();

        if (left.isArchived()) {
          diff.diffType = SnapshotDiff.TYPE_RESTORED;
        } else {
          diff.diffType = SnapshotDiff.TYPE_ARCHIVED;
        }

        list.add(diff);
      } else if (isAssetItemUpdated(right, left)) { // Has the asset been
        // updated
        SnapshotDiff diff = new SnapshotDiff();

        diff.name = right.getName();
        diff.leftUuid = left.getUUID();
        diff.rightUuid = right.getUUID();
        diff.diffType = SnapshotDiff.TYPE_UPDATED;

        list.add(diff);
      }
    }

    diffs.diffs = list.toArray(new SnapshotDiff[list.size()]);
    return diffs;
  }
  /** Test package configuration errors, including header, functions, DSL files. */
  public void testPackageConfigWithErrors() throws Exception {
    // test the config, no rule assets yet
    RulesRepository repo = getRepo();
    PackageItem pkg = repo.createPackage("testBuilderPackageConfig", "x");
    ServiceImplementation.updateDroolsHeader("import java.util.List", pkg);
    AssetItem func = pkg.addAsset("func1", "a function");
    func.updateFormat(AssetFormats.FUNCTION);
    func.updateContent(
        "function void doSomething() { \n System.err.println(List.class.toString()); }");
    func.checkin("yeah");

    func = pkg.addAsset("func2", "q");
    func.updateFormat(AssetFormats.FUNCTION);
    func.updateContent("function void foo() { \nSystem.err.println(42); \n}");
    func.checkin("");

    AssetItem ass = pkg.addAsset("dsl", "m");
    ass.updateFormat(AssetFormats.DSL);
    ass.updateContent("[when]Foo bar=String()");
    ass.checkin("");
    repo.save();

    // now lets light it up
    ContentPackageAssembler assembler = new ContentPackageAssembler(pkg);
    assertFalse(assembler.hasErrors());
    Package bin = assembler.getBinaryPackage();
    assertNotNull(bin);
    assertEquals("testBuilderPackageConfig", bin.getName());
    assertEquals(2, bin.getFunctions().size());

    assertTrue(bin.isValid());
    assertEquals(1, assembler.builder.getDSLMappingFiles().size());

    ServiceImplementation.updateDroolsHeader("koo koo ca choo", pkg);
    assembler = new ContentPackageAssembler(pkg);
    assertTrue(assembler.hasErrors());
    assertTrue(assembler.isPackageConfigurationInError());

    ServiceImplementation.updateDroolsHeader("import java.util.Date", pkg);
    assembler = new ContentPackageAssembler(pkg);
    assertTrue(assembler.hasErrors());
    assertTrue(assembler.getErrors().get(0).itemInError instanceof AssetItem);

    assertEquals("func1", assembler.getErrors().get(0).itemInError.getName());
    try {
      assembler.getBinaryPackage();
      fail("should not work as is in error.");
    } catch (IllegalStateException e) {
      assertNotNull(e.getMessage());
    }

    // fix it up
    ServiceImplementation.updateDroolsHeader("import java.util.List", pkg);
    assembler = new ContentPackageAssembler(pkg);
    assertFalse(assembler.hasErrors());

    // now break a DSL and check the error
    ass.updateContent("rubbish");
    ass.checkin("");
    assembler = new ContentPackageAssembler(pkg);
    assertTrue(assembler.hasErrors());
    assertTrue(assembler.getErrors().get(0).itemInError.getName().equals(ass.getName()));
    assertNotEmpty(assembler.getErrors().get(0).errorReport);
    assertFalse(assembler.isPackageConfigurationInError());

    // now fix it up
    ass.updateContent("[when]foo=String()");
    ass.checkin("");
    assembler = new ContentPackageAssembler(pkg);
    assertFalse(assembler.hasErrors());

    // break a func, and check for error
    func.updateContent("goo");
    func.checkin("");
    assembler = new ContentPackageAssembler(pkg);
    assertTrue(assembler.hasErrors());
    assertFalse(assembler.isPackageConfigurationInError());
    assertTrue(assembler.getErrors().get(0).itemInError.getName().equals(func.getName()));
    assertNotEmpty(assembler.getErrors().get(0).errorReport);
  }
Ejemplo n.º 15
0
  /**
   * 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
  @Restrict("#{identity.loggedIn}")
  public void changeState(String uuid, String newState) {
    AssetItem asset = getRulesRepository().loadAssetByUUID(uuid);

    // 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()) {
      boolean passed = false;

      try {
        Identity.instance()
            .checkPermission(
                new PackageUUIDType(asset.getPackage().getUUID()), RoleTypes.PACKAGE_DEVELOPER);
      } catch (RuntimeException e) {
        if (asset.getCategories().size() == 0) {
          Identity.instance().checkPermission(new CategoryPathType(null), RoleTypes.ANALYST);
        } else {
          RuntimeException exception = null;

          for (CategoryItem cat : asset.getCategories()) {
            try {
              Identity.instance()
                  .checkPermission(new CategoryPathType(cat.getName()), RoleTypes.ANALYST);
              passed = true;
            } catch (RuntimeException re) {
              exception = re;
            }
          }
          if (!passed) {
            throw exception;
          }
        }
      }
    }

    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);

    getRulesRepository().save();
  }
Ejemplo n.º 16
0
 protected RuleModel buildModelFromAsset(AssetItem asset) {
   RuleModel model = getBrlXmlPersistence().unmarshal(asset.getContent());
   model.name = asset.getName();
   model.parentName = this.parentNameFromCategory(asset, model.parentName);
   return model;
 }
Ejemplo n.º 17
0
  /*    public static Entry ToPackageEntry(PackageItem p, UriInfo uriInfo) {
      UriBuilder base;
      if(p.isHistoricalVersion()) {
          base = uriInfo.getBaseUriBuilder().path("packages").path(p.getName()).path("versions").path(Long.toString(p.getVersionNumber()));
      } else {
          base = uriInfo.getBaseUriBuilder().path("packages").path(p.getName());
      }

      //NOTE: Entry extension is not supported in RESTEasy. We need to either use Abdera or get extension
      //supported in RESTEasy
      //PackageMetadata metadata = new PackageMetadata();
      //metadata.setUuid(p.getUUID());
      //metadata.setCreated(p.getCreatedDate().getTime());
      //metadata.setLastModified(p.getLastModified().getTime());
      //metadata.setLastContributor(p.getLastContributor());
      //c.setJAXBObject(metadata);

      Entry e =new Entry();
      e.setTitle(p.getTitle());
      e.setSummary(p.getDescription());
      e.setPublished(new Date(p.getLastModified().getTimeInMillis()));
      e.setBase(base.clone().build());

      e.setId(base.clone().build());

      Iterator<AssetItem> i = p.getAssets();
      while (i.hasNext()) {
          AssetItem item = i.next();
          Link link = new Link();
          link.setHref((base.clone().path("assets").path(item.getName())).build());
          link.setTitle(item.getTitle());
          link.setRel("asset");
          e.getLinks().add(link);
      }

      Content c = new Content();
      c.setType(MediaType.APPLICATION_OCTET_STREAM_TYPE);
      c.setSrc(base.clone().path("binary").build());
      e.setContent(c);

      return e;
  }*/
  public static Entry toAssetEntryAbdera(AssetItem a, UriInfo uriInfo) {
    URI baseURL;
    if (a.isHistoricalVersion()) {
      baseURL =
          uriInfo
              .getBaseUriBuilder()
              .path("packages/{packageName}/assets/{assetName}/versions/{version}")
              .build(a.getModuleName(), a.getName(), Long.toString(a.getVersionNumber()));
    } else {
      baseURL =
          uriInfo
              .getBaseUriBuilder()
              .path("packages/{packageName}/assets/{assetName}")
              .build(a.getModuleName(), a.getName());
    }

    Factory factory = Abdera.getNewFactory();

    org.apache.abdera.model.Entry e = factory.getAbdera().newEntry();
    e.setTitle(a.getTitle());
    e.setSummary(a.getDescription());
    e.setPublished(new Date(a.getLastModified().getTimeInMillis()));
    e.setBaseUri(baseURL.toString());
    e.addAuthor(a.getLastContributor());

    e.setId(baseURL.toString());

    // generate meta data
    ExtensibleElement extension = e.addExtension(METADATA);
    ExtensibleElement childExtension = extension.addExtension(ARCHIVED);
    // childExtension.setAttributeValue("type", ArtifactsRepository.METADATA_TYPE_STRING);
    childExtension.addSimpleExtension(VALUE, a.isArchived() ? "true" : "false");

    childExtension = extension.addExtension(UUID);
    childExtension.addSimpleExtension(VALUE, a.getUUID());

    childExtension = extension.addExtension(STATE);
    childExtension.addSimpleExtension(VALUE, a.getState() == null ? "" : a.getState().getName());

    childExtension = extension.addExtension(FORMAT);
    childExtension.addSimpleExtension(VALUE, a.getFormat());

    childExtension = extension.addExtension(VERSION_NUMBER);
    childExtension.addSimpleExtension(VALUE, String.valueOf(a.getVersionNumber()));

    childExtension = extension.addExtension(CHECKIN_COMMENT);
    childExtension.addSimpleExtension(VALUE, a.getCheckinComment());

    List<CategoryItem> categories = a.getCategories();
    childExtension = extension.addExtension(CATEGORIES);
    for (CategoryItem c : categories) {
      childExtension.addSimpleExtension(VALUE, c.getName());
    }

    org.apache.abdera.model.Content content = factory.newContent();
    content.setSrc(UriBuilder.fromUri(baseURL).path("binary").build().toString());
    content.setMimeType("application/octet-stream");
    content.setContentType(Type.MEDIA);
    e.setContentElement(content);

    return e;
  }
Ejemplo n.º 18
0
  public static Entry toPackageEntryAbdera(ModuleItem p, UriInfo uriInfo) {
    URI baseURL;
    if (p.isHistoricalVersion()) {
      baseURL =
          uriInfo
              .getBaseUriBuilder()
              .path("packages/{packageName}/versions/{version}")
              .build(p.getName(), Long.toString(p.getVersionNumber()));
    } else {
      baseURL = uriInfo.getBaseUriBuilder().path("packages/{packageName}").build(p.getName());
    }

    Factory factory = Abdera.getNewFactory();

    org.apache.abdera.model.Entry e = factory.getAbdera().newEntry();
    e.setTitle(p.getTitle());
    e.setSummary(p.getDescription());
    e.setPublished(new Date(p.getLastModified().getTimeInMillis()));
    e.setBaseUri(baseURL.toString());
    e.addAuthor(p.getLastContributor());

    e.setId(baseURL.toString());

    Iterator<AssetItem> i = p.getAssets();
    while (i.hasNext()) {
      AssetItem item = i.next();
      org.apache.abdera.model.Link l = factory.newLink();

      l.setHref(
          UriBuilder.fromUri(baseURL).path("assets/{assetName}").build(item.getName()).toString());
      l.setTitle(item.getTitle());
      l.setRel("asset");
      e.addLink(l);
    }

    // generate meta data
    ExtensibleElement extension = e.addExtension(METADATA);
    ExtensibleElement childExtension = extension.addExtension(ARCHIVED);
    // childExtension.setAttributeValue("type", ArtifactsRepository.METADATA_TYPE_STRING);
    childExtension.addSimpleExtension(VALUE, p.isArchived() ? "true" : "false");

    childExtension = extension.addExtension(UUID);
    childExtension.addSimpleExtension(VALUE, p.getUUID());

    childExtension = extension.addExtension(STATE);
    childExtension.addSimpleExtension(VALUE, p.getState() == null ? "" : p.getState().getName());

    childExtension = extension.addExtension(VERSION_NUMBER);
    childExtension.addSimpleExtension(VALUE, String.valueOf(p.getVersionNumber()));

    childExtension = extension.addExtension(CHECKIN_COMMENT);
    childExtension.addSimpleExtension(VALUE, p.getCheckinComment());

    org.apache.abdera.model.Content content = factory.newContent();
    content.setSrc(UriBuilder.fromUri(baseURL).path("binary").build().toString());
    content.setMimeType("application/octet-stream");
    content.setContentType(Type.MEDIA);
    e.setContentElement(content);

    return e;
  }
Ejemplo n.º 19
0
 private void logErrors(AssetItem asset) {
   this.recordBuilderErrors(asset.getFormat(), asset.getName(), asset.getUUID(), false, true);
 }