/**
   * 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 which refers to an existing asset */
  public String createNewImportedRule(String sharedAssetName, String initialPackage)
      throws SerializationException {
    log.info(
        "USER:"******" CREATING shared asset imported from global area named ["
            + sharedAssetName
            + "] in package ["
            + initialPackage
            + "]");

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

      return asset.getUUID();
    } catch (RulesRepositoryException e) {
      // If we want to display an explicit error message of "duplicate asset", we can achieve this
      // in client error handler.
      /*            if ( e.getCause() instanceof ItemExistsException ) {
          return "DUPLICATE";
      }*/
      log.error(
          "An error occurred creating shared asset"
              + sharedAssetName
              + "] in package ["
              + initialPackage
              + "]: ",
          e);
      throw new SerializationException(e.getMessage());
    }
  }
  /**
   * This 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());
    }
  }
 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;
 }
  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;
  }
  /**
   * This will create a new asset. It will be saved, but not checked in. The initial state will be
   * the draft state. Returns the UUID of the asset.
   */
  public String createNewRule(
      String ruleName,
      String description,
      String initialCategory,
      String initialPackage,
      String format)
      throws SerializationException {
    log.info(
        "USER:"******" CREATING new asset name ["
            + ruleName
            + "] in package ["
            + initialPackage
            + "]");

    try {

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

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

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

      return asset.getUUID();
    } catch (RulesRepositoryException e) {
      // If we want to display an explicit error message of "duplicate asset", we can achieve this
      // in client error handler.
      /*            if ( e.getCause() instanceof ItemExistsException ) {
          return "DUPLICATE";
      }*/
      log.error(
          "An error occurred creating new asset"
              + ruleName
              + "] in package ["
              + initialPackage
              + "]: ",
          e);
      throw new SerializationException(e.getMessage());
    }
  }
Beispiel #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;
  }
Beispiel #9
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());
  }
  /** @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;
  }
Beispiel #11
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;
  }
 private void logErrors(AssetItem asset) {
   this.recordBuilderErrors(asset.getFormat(), asset.getName(), asset.getUUID(), false, true);
 }
  /**
   * 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();
  }