/** Add a page title and trail links. */
  public void addPageMeta(PageMeta pageMeta)
      throws SAXException, WingException, UIException, SQLException, IOException,
          AuthorizeException {
    DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    if (!(dso instanceof Collection)) return;

    Collection collection = (Collection) dso;

    // Set the page title
    pageMeta.addMetadata("title").addContent(collection.getMetadata("name"));

    pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
    HandleUtil.buildHandleTrail(collection, pageMeta, contextPath);

    // Add RSS links if available
    String formats = ConfigurationManager.getProperty("webui.feed.formats");
    if (formats != null) {
      for (String format : formats.split(",")) {
        // Remove the protocol number, i.e. just list 'rss' or' atom'
        String[] parts = format.split("_");
        if (parts.length < 1) continue;

        String feedFormat = parts[0].trim() + "+xml";

        String feedURL = contextPath + "/feed/" + collection.getHandle() + "/" + format.trim();
        pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
      }
    }
  }
  /**
   * Return the workflow item to the workspace of the submitter. The workflow item is removed, and a
   * workspace item created.
   *
   * @param c Context
   * @param wfi WorkflowItem to be 'dismantled'
   * @return the workspace item
   */
  private static WorkspaceItem returnToWorkspace(Context c, WorkflowItem wfi)
      throws SQLException, IOException, AuthorizeException {
    Item myitem = wfi.getItem();
    Collection mycollection = wfi.getCollection();

    // FIXME: How should this interact with the workflow system?
    // FIXME: Remove license
    // FIXME: Provenance statement?
    // Create the new workspace item row
    TableRow row = DatabaseManager.create(c, "workspaceitem");
    row.setColumn("item_id", myitem.getID());
    row.setColumn("collection_id", mycollection.getID());
    DatabaseManager.update(c, row);

    int wsi_id = row.getIntColumn("workspace_item_id");
    WorkspaceItem wi = WorkspaceItem.find(c, wsi_id);
    wi.setMultipleFiles(wfi.hasMultipleFiles());
    wi.setMultipleTitles(wfi.hasMultipleTitles());
    wi.setPublishedBefore(wfi.isPublishedBefore());
    wi.update();

    // myitem.update();
    log.info(
        LogManager.getHeader(
            c,
            "return_to_workspace",
            "workflow_item_id=" + wfi.getID() + "workspace_item_id=" + wi.getID()));

    // Now remove the workflow object manually from the database
    DatabaseManager.updateQuery(c, "DELETE FROM WorkflowItem WHERE workflow_id=" + wfi.getID());

    return wi;
  }
  /**
   * Commit the contained item to the main archive. The item is associated with the relevant
   * collection, added to the search index, and any other tasks such as assigning dates are
   * performed.
   *
   * @return the fully archived item.
   */
  @Override
  public Item archive(Context context, BasicWorkflowItem workflowItem)
      throws SQLException, IOException, AuthorizeException {
    // FIXME: Check auth
    Item item = workflowItem.getItem();
    Collection collection = workflowItem.getCollection();

    log.info(
        LogManager.getHeader(
            context,
            "archive_item",
            "workflow_item_id="
                + workflowItem.getID()
                + "item_id="
                + item.getID()
                + "collection_id="
                + collection.getID()));

    installItemService.installItem(context, workflowItem);

    // Log the event
    log.info(
        LogManager.getHeader(
            context,
            "install_item",
            "workflow_id=" + workflowItem.getID() + ", item_id=" + item.getID() + "handle=FIXME"));

    return item;
  }
  @Override
  public void addBody(Body body)
      throws SAXException, WingException, SQLException, IOException, AuthorizeException {
    Item item = workflowItem.getItem();
    Collection collection = workflowItem.getCollection();
    Request request = ObjectModelHelper.getRequest(objectModel);

    String actionURL = contextPath + "/handle/" + collection.getHandle() + "/xmlworkflow";

    // Retrieve our pagenumber
    int page = ReviewAction.MAIN_PAGE;
    if (request.getAttribute("page") != null) {
      page = Integer.parseInt(request.getAttribute("page").toString());
    }

    // Generate a from asking the user two questions: multiple
    // titles & published before.
    Division div =
        body.addInteractiveDivision(
            "perform-task", actionURL, Division.METHOD_POST, "primary workflow");
    div.setHead(T_HEAD);

    addWorkflowItemInformation(div, item, request);

    switch (page) {
      case org.dspace.xmlworkflow.state.actions.processingaction.AcceptEditRejectAction.MAIN_PAGE:
        renderMainPage(div);
        break;
      case ReviewAction.REJECT_PAGE:
        renderRejectPage(div);
        break;
    }

    div.addHidden("submission-continue").setValue(knot.getId());
  }
  /**
   * Change default privileges from the anonymous group to a new group that will be created and
   * appropriate privileges assigned. The id of this new group will be returned.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @return The group ID of the new group.
   */
  public static int createCollectionDefaultReadGroup(Context context, int collectionID)
      throws SQLException, AuthorizeException, UIException {
    int roleID = getCollectionDefaultRead(context, collectionID);

    if (roleID != 0) {
      throw new UIException(
          "Unable to create a new default read group because either the group already exists or multiple groups are assigned the default privileges.");
    }

    Collection collection = Collection.find(context, collectionID);
    Group role = Group.create(context);
    role.setName("COLLECTION_" + collection.getID() + "_DEFAULT_READ");

    // Remove existing privileges from the anonymous group.
    AuthorizeManager.removePoliciesActionFilter(context, collection, Constants.DEFAULT_ITEM_READ);
    AuthorizeManager.removePoliciesActionFilter(
        context, collection, Constants.DEFAULT_BITSTREAM_READ);

    // Grant our new role the default privileges.
    AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, role);
    AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, role);

    // Commit the changes
    role.update();
    context.commit();

    return role.getID();
  }
  /**
   * Commit the contained item to the main archive. The item is associated with the relevant
   * collection, added to the search index, and any other tasks such as assigning dates are
   * performed.
   *
   * @return the fully archived item.
   */
  private static Item archive(Context c, WorkflowItem wfi)
      throws SQLException, IOException, AuthorizeException {
    // FIXME: Check auth
    Item item = wfi.getItem();
    Collection collection = wfi.getCollection();

    log.info(
        LogManager.getHeader(
            c,
            "archive_item",
            "workflow_item_id="
                + wfi.getID()
                + "item_id="
                + item.getID()
                + "collection_id="
                + collection.getID()));

    InstallItem.installItem(c, wfi);

    // Log the event
    log.info(
        LogManager.getHeader(
            c,
            "install_item",
            "workflow_id=" + wfi.getID() + ", item_id=" + item.getID() + "handle=FIXME"));

    return item;
  }
 @Override
 public void deleteCollection(Context context, Collection collection)
     throws SQLException, IOException, AuthorizeException {
   collection.setWorkflowGroup(1, null);
   collection.setWorkflowGroup(2, null);
   collection.setWorkflowGroup(3, null);
   workflowItemService.deleteByCollection(context, collection);
 }
Example #8
0
  /* (non-Javadoc)
   * @see org.dspace.app.dav.DAVDSpaceObject#propfindInternal(org.jdom.Element)
   */
  @Override
  protected Element propfindInternal(Element property)
      throws SQLException, AuthorizeException, IOException, DAVStatusException {
    String value = null;

    /*
     * FIXME: This implements permission check that really belongs in
     * business logic. Although communities and collections don't check for
     * read auth, Item may contain sensitive data and should always check
     * for READ permission. Exception: allow "withdrawn" property to be
     * checked regardless of authorization since all permissions are removed
     * when item is withdrawn.
     */
    if (!elementsEqualIsh(property, withdrawnProperty)) {
      AuthorizeManager.authorizeAction(this.context, this.item, Constants.READ);
    }

    if (elementsEqualIsh(property, withdrawnProperty)) {
      value = String.valueOf(this.item.isWithdrawn());
    } else if (elementsEqualIsh(property, displaynameProperty)) {
      // displayname - title or handle.
      DCValue titleDc[] = this.item.getDC("title", Item.ANY, Item.ANY);
      value = titleDc.length > 0 ? titleDc[0].value : this.item.getHandle();
    } else if (elementsEqualIsh(property, handleProperty)) {
      value = canonicalizeHandle(this.item.getHandle());
    } else if (elementsEqualIsh(property, submitterProperty)) {
      EPerson ep = this.item.getSubmitter();
      if (ep != null) {
        value = hrefToEPerson(ep);
      }
    } else if (elementsEqualIsh(property, owning_collectionProperty)) {
      Collection owner = this.item.getOwningCollection();
      if (owner != null) {
        value = canonicalizeHandle(owner.getHandle());
      }
    } else if (elementsEqualIsh(property, getlastmodifiedProperty)) {
      value = DAV.HttpDateFormat.format(this.item.getLastModified());
    } else if (elementsEqualIsh(property, licenseProperty)) {
      value = getLicenseAsString();
    } else if (elementsEqualIsh(property, cc_license_textProperty)) {
      value = LicenceController.getLicenseText(this.item);
    } else if (elementsEqualIsh(property, cc_license_rdfProperty)) {
      value = LicenceController.getLicenseRDF(this.item);
    } else if (elementsEqualIsh(property, cc_license_urlProperty)) {
      value = LicenceController.getLicenseURL(this.item);
    } else {
      return super.propfindInternal(property);
    }

    // value was set up by "if" clause:
    if (value == null) {
      throw new DAVStatusException(HttpServletResponse.SC_NOT_FOUND, "Not found.");
    }
    Element p = new Element(property.getName(), property.getNamespace());
    p.setText(filterForXML(value));
    return p;
  }
  protected void notifyOfReject(
      Context context, BasicWorkflowItem workflowItem, EPerson e, String reason) {
    try {
      // Get the item title
      String title = getItemTitle(workflowItem);

      // Get the collection
      Collection coll = workflowItem.getCollection();

      // Get rejector's name
      String rejector = getEPersonName(e);
      Locale supportedLocale = I18nUtil.getEPersonLocale(e);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_reject"));

      email.addRecipient(workflowItem.getSubmitter().getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(rejector);
      email.addArgument(reason);
      email.addArgument(getMyDSpaceLink());

      email.send();
    } catch (RuntimeException re) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + re.getMessage()));

      throw re;
    } catch (Exception ex) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + ex.getMessage()));
    }
  }
Example #10
0
  /**
   * Search for first collection with passed name.
   *
   * @param name Name of collection.
   * @param headers If you want to access to collection under logged user into context. In headers
   *     must be set header "rest-dspace-token" with passed token from login method.
   * @return It returns null if collection was not found. Otherwise returns first founded
   *     collection.
   * @throws WebApplicationException
   */
  @POST
  @Path("/find-collection")
  @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Collection findCollectionByName(String name, @Context HttpHeaders headers)
      throws WebApplicationException {
    log.info("Searching for first collection with name=" + name + ".");
    org.dspace.core.Context context = null;
    Collection collection = null;

    try {
      context = createContext(getUser(headers));
      org.dspace.content.Collection[] dspaceCollections;

      dspaceCollections = org.dspace.content.Collection.findAll(context);

      for (org.dspace.content.Collection dspaceCollection : dspaceCollections) {
        if (AuthorizeManager.authorizeActionBoolean(
            context, dspaceCollection, org.dspace.core.Constants.READ)) {
          if (dspaceCollection.getName().equals(name)) {
            collection = new Collection(dspaceCollection, "", context, 100, 0);
            break;
          }
        }
      }

      context.complete();

    } catch (SQLException e) {
      processException(
          "Something went wrong while searching for collection(name="
              + name
              + ") from database. Message: "
              + e,
          context);
    } catch (ContextException e) {
      processException(
          "Something went wrong while searching for collection(name="
              + name
              + "), ContextError. Message: "
              + e.getMessage(),
          context);
    } finally {
      processFinally(context);
    }

    if (collection == null) {
      log.info("Collection was not found.");
    } else {
      log.info("Collection was found with id(" + collection.getId() + ").");
    }
    return collection;
  }
Example #11
0
  /**
   * Delete one of collection's roles
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ.
   * @param groupID The id of the group associated with this role.
   * @return A process result's object.
   */
  public static FlowResult processDeleteCollectionRole(
      Context context, int collectionID, String roleName, int groupID)
      throws SQLException, UIException, IOException, AuthorizeException,
          WorkflowConfigurationException {
    FlowResult result = new FlowResult();

    Collection collection = Collection.find(context, collectionID);
    Group role = Group.find(context, groupID);

    // First, Unregister the role
    if (ROLE_ADMIN.equals(roleName)) {
      collection.removeAdministrators();
    } else if (ROLE_SUBMIT.equals(roleName)) {
      collection.removeSubmitters();
    } else {
      WorkflowUtils.deleteRoleGroup(context, collection, roleName);
    }
    //		else if (ROLE_WF_STEP1.equals(roleName))
    //		{
    //			collection.setWorkflowGroup(1, null);
    //		}
    //		else if (ROLE_WF_STEP2.equals(roleName))
    //		{
    //			collection.setWorkflowGroup(2, null);
    //		}
    //		else if (ROLE_WF_STEP3.equals(roleName))
    //		{
    //			collection.setWorkflowGroup(3, null);
    //
    //		}

    // Second, remove all authorizations for this role by searching for all policies that this
    // group has on the collection and remove them otherwise the delete will fail because
    // there are dependencies.
    @SuppressWarnings("unchecked") // the cast is correct
    List<ResourcePolicy> policies = AuthorizeManager.getPolicies(context, collection);
    for (ResourcePolicy policy : policies) {
      if (policy.getGroupID() == groupID) {
        policy.delete();
      }
    }

    // Finally, Delete the role's actual group.
    collection.update();
    role.delete();
    context.commit();

    result.setContinue(true);
    result.setOutcome(true);
    result.setMessage(new Message("default", "The role was successfully deleted."));
    return result;
  }
Example #12
0
  /**
   * Delete a collection's template item (which is not a member of the collection).
   *
   * @param context
   * @param collectionID
   * @throws SQLException
   * @throws AuthorizeException
   * @throws IOException
   */
  public static FlowResult processDeleteTemplateItem(Context context, int collectionID)
      throws SQLException, AuthorizeException, IOException {
    FlowResult result = new FlowResult();

    Collection collection = Collection.find(context, collectionID);

    collection.removeTemplateItem();
    context.commit();

    result.setContinue(true);
    result.setOutcome(true);
    return result;
  }
Example #13
0
  /**
   * Add options to the search scope field. This field determines in what communities or collections
   * to search for the query.
   *
   * <p>The scope list will depend upon the current search scope. There are three cases:
   *
   * <p>No current scope: All top level communities are listed.
   *
   * <p>The current scope is a community: All collections contained within the community are listed.
   *
   * <p>The current scope is a collection: All parent communities are listed.
   *
   * @param scope The current scope field.
   */
  protected void buildScopeList(Select scope) throws SQLException, WingException {

    DSpaceObject scopeDSO = getScope();
    if (scopeDSO == null) {
      // No scope, display all root level communities
      scope.addOption("/", T_all_of_dspace);
      scope.setOptionSelected("/");
      for (Community community : Community.findAllTop(context)) {
        scope.addOption(community.getHandle(), community.getMetadata("name"));
      }
    } else if (scopeDSO instanceof Community) {
      // The scope is a community, display all collections contained
      // within
      Community community = (Community) scopeDSO;
      scope.addOption("/", T_all_of_dspace);
      scope.addOption(community.getHandle(), community.getMetadata("name"));
      scope.setOptionSelected(community.getHandle());

      for (Collection collection : community.getCollections()) {
        scope.addOption(collection.getHandle(), collection.getMetadata("name"));
      }
    } else if (scopeDSO instanceof Collection) {
      // The scope is a collection, display all parent collections.
      Collection collection = (Collection) scopeDSO;
      scope.addOption("/", T_all_of_dspace);
      scope.addOption(collection.getHandle(), collection.getMetadata("name"));
      scope.setOptionSelected(collection.getHandle());

      Community[] communities = collection.getCommunities()[0].getAllParents();
      for (Community community : communities) {
        scope.addOption(community.getHandle(), community.getMetadata("name"));
      }
    }
  }
  @Override
  public void update(Collection collection) throws AuthorizeException {
    try {
      TableRow row = DatabaseManager.find(context, "collection", collection.getID());

      if (row != null) {
        populateTableRowFromCollection(collection, row);
        DatabaseManager.update(context, row);
      } else {
        throw new RuntimeException("Didn't find collection " + collection.getID());
      }
    } catch (SQLException sqle) {
      throw new RuntimeException(sqle);
    }
  }
Example #15
0
  /**
   * Use the collection's harvest settings to immediately perform a harvest cycle.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @param request the Cocoon request object
   * @return A process result's object.
   * @throws TransformerException
   * @throws SAXException
   * @throws ParserConfigurationException
   * @throws CrosswalkException
   */
  public static FlowResult processRunCollectionHarvest(
      Context context, int collectionID, Request request)
      throws SQLException, IOException, AuthorizeException, CrosswalkException,
          ParserConfigurationException, SAXException, TransformerException {
    FlowResult result = new FlowResult();
    OAIHarvester harvester;
    List<String> testErrors = new ArrayList<String>();
    Collection collection = Collection.find(context, collectionID);
    HarvestedCollection hc = HarvestedCollection.find(context, collectionID);

    // TODO: is there a cleaner way to do this?
    try {
      if (!HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_STOPPED)) {
        synchronized (HarvestScheduler.lock) {
          HarvestScheduler.setInterrupt(
              HarvestScheduler.HARVESTER_INTERRUPT_INSERT_THREAD, collectionID);
          HarvestScheduler.lock.notify();
        }
      } else {
        harvester = new OAIHarvester(context, collection, hc);
        harvester.runHarvest();
      }
    } catch (Exception e) {
      testErrors.add(e.getMessage());
      result.setErrors(testErrors);
      result.setContinue(false);
      return result;
    }

    result.setContinue(true);

    return result;
  }
  /**
   * Get all workflow items for a particular collection.
   *
   * @param context the context object
   * @param c the collection
   * @return array of the corresponding workflow items
   */
  public static WorkflowItem[] findByCollection(Context context, Collection c) throws SQLException {
    List wsItems = new ArrayList();

    TableRowIterator tri =
        DatabaseManager.queryTable(
            context,
            "workflowitem",
            "SELECT workflowitem.* FROM workflowitem WHERE " + "workflowitem.collection_id= ? ",
            c.getID());

    try {
      while (tri.hasNext()) {
        TableRow row = tri.next();

        // Check the cache
        WorkflowItem wi =
            (WorkflowItem) context.fromCache(WorkflowItem.class, row.getIntColumn("workflow_id"));

        // not in cache? turn row into workflowitem
        if (wi == null) {
          wi = new WorkflowItem(context, row);
        }

        wsItems.add(wi);
      }
    } finally {
      if (tri != null) tri.close();
    }

    WorkflowItem[] wsArray = new WorkflowItem[wsItems.size()];
    wsArray = (WorkflowItem[]) wsItems.toArray(wsArray);

    return wsArray;
  }
Example #17
0
  /**
   * Change the default read privileges to the anonymous group.
   *
   * <p>If getCollectionDefaultRead() returns -1 or the anonymous group then nothing is done.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @return A process result's object.
   */
  public static FlowResult changeCollectionDefaultReadToAnonymous(Context context, int collectionID)
      throws SQLException, AuthorizeException, UIException {
    FlowResult result = new FlowResult();

    int roleID = getCollectionDefaultRead(context, collectionID);

    if (roleID < 1) {
      throw new UIException(
          "Unable to delete the default read role because the role is either already assigned to the anonymous group or multiple groups are assigned the default privileges.");
    }

    Collection collection = Collection.find(context, collectionID);
    Group role = Group.find(context, roleID);
    Group anonymous = Group.find(context, 0);

    // Delete the old role, this will remove the default privileges.
    role.delete();

    // Set anonymous as the default read group.
    AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, anonymous);
    AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, anonymous);

    // Commit the changes
    context.commit();

    result.setContinue(true);
    result.setOutcome(true);
    result.setMessage(
        new Message(
            "default",
            "All new items submitted to this collection will default to anonymous read."));
    return result;
  }
Example #18
0
  /**
   * Look up the id of a group authorized for one of the given roles. If no group is currently
   * authorized to perform this role then a new group will be created and assigned the role.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @return The id of the group associated with that particular role or -1
   */
  public static int getCollectionDefaultRead(Context context, int collectionID)
      throws SQLException, AuthorizeException {
    Collection collection = Collection.find(context, collectionID);

    Group[] itemGroups =
        AuthorizeManager.getAuthorizedGroups(context, collection, Constants.DEFAULT_ITEM_READ);
    Group[] bitstreamGroups =
        AuthorizeManager.getAuthorizedGroups(context, collection, Constants.DEFAULT_BITSTREAM_READ);

    int itemGroupID = -1;

    // If there are more than one groups assigned either of these privileges then this role based
    // method will not work.
    // The user will need to go to the authorization section to manually straighten this out.
    if (itemGroups.length != 1 || bitstreamGroups.length != 1) {
      // do nothing the itemGroupID is already set to -1
    } else {
      Group itemGroup = itemGroups[0];
      Group bitstreamGroup = bitstreamGroups[0];

      // If the same group is not assigned both of these privileges then this role based method will
      // not work. The user
      // will need to go to the authorization section to manually straighten this out.
      if (itemGroup.getID() != bitstreamGroup.getID()) {
        // do nothing the itemGroupID is already set to -1
      } else {
        itemGroupID = itemGroup.getID();
      }
    }

    return itemGroupID;
  }
 @Override
 public Group getWorkflowRoleGroup(
     Context context, Collection collection, String roleName, Group roleGroup)
     throws SQLException, IOException, WorkflowException, AuthorizeException {
   try {
     Role role = WorkflowUtils.getCollectionAndRepositoryRoles(collection).get(roleName);
     if (role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY) {
       roleGroup = WorkflowUtils.getRoleGroup(context, collection, role);
       if (roleGroup == null) {
         authorizeService.authorizeAction(context, collection, Constants.WRITE);
         roleGroup = groupService.create(context);
         if (role.getScope() == Role.Scope.COLLECTION) {
           groupService.setName(
               roleGroup,
               "COLLECTION_" + collection.getID().toString() + "_WORKFLOW_ROLE_" + roleName);
         } else {
           groupService.setName(roleGroup, role.getName());
         }
         groupService.update(context, roleGroup);
         authorizeService.addPolicy(context, collection, Constants.ADD, roleGroup);
         if (role.getScope() == Role.Scope.COLLECTION) {
           WorkflowUtils.createCollectionWorkflowRole(context, collection, roleName, roleGroup);
         }
       }
     }
     return roleGroup;
   } catch (WorkflowConfigurationException e) {
     throw new WorkflowException(e);
   }
 }
Example #20
0
  /**
   * processCurateCollection
   *
   * <p>Utility method to process curation tasks submitted via the DSpace GUI
   *
   * @param context
   * @param dsoID
   * @param request
   */
  public static FlowResult processCurateCollection(Context context, int dsoID, Request request)
      throws AuthorizeException, IOException, SQLException, Exception {
    String task = request.getParameter("curate_task");
    Curator curator = FlowCurationUtils.getCurator(task);

    try {
      Collection collection = Collection.find(context, dsoID);
      if (collection != null) {
        // Call curate(context,ID) to ensure a Task Performer (Eperson) is set in Curator
        curator.curate(context, collection.getHandle());
      }
      return FlowCurationUtils.getRunFlowResult(task, curator, true);
    } catch (Exception e) {
      curator.setResult(task, e.getMessage());
      return FlowCurationUtils.getRunFlowResult(task, curator, false);
    }
  }
  private void populateTableRowFromItem(Item item, TableRow row) {
    EPerson submitter = item.getSubmitter();
    Collection owningCollection = item.getOwningCollection();

    row.setColumn("item_id", item.getID());
    row.setColumn("in_archive", item.isArchived());
    row.setColumn("withdrawn", item.isWithdrawn());
    row.setColumn("last_modified", item.getLastModified());

    if (submitter != null) {
      row.setColumn("submitter_id", submitter.getID());
    }

    if (owningCollection != null) {
      row.setColumn("owning_collection", owningCollection.getID());
    }
  }
  private Collection retrieve(TableRow row) {
    if (row == null) {
      return null;
    }

    int id = row.getIntColumn("collection_id");
    Collection collection = new Collection(context, id);
    populateCollectionFromTableRow(collection, row);

    // FIXME: I'd like to bump the rest of this up into the superclass
    // so we don't have to do it for every implementation, but I can't
    // figure out a clean way of doing this yet.
    List<ExternalIdentifier> identifiers = identifierDAO.getExternalIdentifiers(collection);
    collection.setExternalIdentifiers(identifiers);

    return collection;
  }
Example #23
0
  /**
   * Look up the id of a group authorized for one of the given roles. If no group is currently
   * authorized to perform this role then a new group will be created and assigned the role.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ.
   * @return The id of the group associated with that particular role, or -1 if the role was not
   *     found.
   */
  public static int getCollectionRole(Context context, int collectionID, String roleName)
      throws SQLException, AuthorizeException, IOException, TransformerException, SAXException,
          WorkflowConfigurationException, ParserConfigurationException {
    Collection collection = Collection.find(context, collectionID);

    // Determine the group based upon wich role we are looking for.
    Group roleGroup = null;
    if (ROLE_ADMIN.equals(roleName)) {
      roleGroup = collection.getAdministrators();
      if (roleGroup == null) {
        roleGroup = collection.createAdministrators();
      }
    } else if (ROLE_SUBMIT.equals(roleName)) {
      roleGroup = collection.getSubmitters();
      if (roleGroup == null) roleGroup = collection.createSubmitters();
    } else {
      if (ConfigurationManager.getProperty("workflow", "workflow.framework")
          .equals("xmlworkflow")) { // Resolve our id to a role
        roleGroup = getXMLWorkflowRole(context, collectionID, roleName, collection, roleGroup);
      } else {
        roleGroup = getOriginalWorkflowRole(roleName, collection, roleGroup);
      }
    }

    // In case we needed to create a group, save our changes
    collection.update();
    context.commit();

    // If the role name was valid then role should be non null,
    if (roleGroup != null) return roleGroup.getID();

    return -1;
  }
  /**
   * Send a collection backup file and respective children to cloud to be preserved.
   *
   * @param context context DSpace
   * @param ref ID of the collection
   * @param establishConnection true if pretend establish connection to cloud
   * @return true if file correctly sent to cloud, or false if not
   */
  public Boolean sendCollectionAndChilds(
      Context context, Integer ref, Boolean establishConnection) {
    // if first, make connection and get collection and item files preserved in cloud
    if (establishConnection == true) {
      this.makeConnection();
      this.filesInCloud.putAll(this.newCloudConnection.getInfoFilesIn(Constants.COLLECTION));
      this.filesInCloud.putAll(this.newCloudConnection.getInfoFilesIn(Constants.ITEM));
    }

    // send to cloud atual collection
    sendCollection(context, ref, false);

    Collection obj;
    ItemIterator items;

    // get the items presents in the collection
    try {
      obj = Collection.find(context, ref);
      items = obj.getAllItems();
    } catch (Exception ex) {
      Logger.getLogger(ActualContentManagement.class.getName()).log(Level.SEVERE, null, ex);
      // it means it is the first father in the order, so close connection
      if (establishConnection == true) this.closeConnection();
      return false;
    }

    // send to cloud, one by one, each item
    try {
      if (items.hasNext()) {
        Item newObj = items.next();
        sendItem(context, newObj.getID(), false);
      }
    } catch (Exception ex) {
      Logger.getLogger(ActualContentManagement.class.getName()).log(Level.SEVERE, null, ex);
      // it means it is the first father in the order, so close connection
      if (establishConnection == true) this.closeConnection();
      return false;
    }

    // it means it is the first father in the order
    if (establishConnection == true) this.closeConnection();

    return true;
  }
Example #25
0
 /** queues curation tasks */
 public static FlowResult processQueueCollection(Context context, int dsoID, Request request)
     throws AuthorizeException, IOException, SQLException, Exception {
   String task = request.getParameter("curate_task");
   Curator curator = FlowCurationUtils.getCurator(task);
   String objId = String.valueOf(dsoID);
   String taskQueueName = ConfigurationManager.getProperty("curate", "ui.queuename");
   boolean status = false;
   Collection collection = Collection.find(context, dsoID);
   if (collection != null) {
     objId = collection.getHandle();
     try {
       curator.queue(context, objId, taskQueueName);
       status = true;
     } catch (IOException ioe) {
       // no-op
     }
   }
   return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName);
 }
  @Override
  public Group getWorkflowRoleGroup(
      Context context, Collection collection, String roleName, Group roleGroup)
      throws SQLException, AuthorizeException {
    if ("WF_STEP1".equals(roleName)) {
      roleGroup = collection.getWorkflowStep1();
      if (roleGroup == null)
        roleGroup = collectionService.createWorkflowGroup(context, collection, 1);

    } else if ("WF_STEP2".equals(roleName)) {
      roleGroup = collection.getWorkflowStep2();
      if (roleGroup == null)
        roleGroup = collectionService.createWorkflowGroup(context, collection, 2);
    } else if ("WF_STEP3".equals(roleName)) {
      roleGroup = collection.getWorkflowStep3();
      if (roleGroup == null)
        roleGroup = collectionService.createWorkflowGroup(context, collection, 3);
    }
    return roleGroup;
  }
Example #27
0
  /**
   * Delete collection itself
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @return A process result's object.
   */
  public static FlowResult processDeleteCollection(Context context, int collectionID)
      throws SQLException, AuthorizeException, IOException {
    FlowResult result = new FlowResult();

    Collection collection = Collection.find(context, collectionID);

    Community[] parents = collection.getCommunities();

    for (Community parent : parents) {
      parent.removeCollection(collection);
      parent.update();
    }

    context.commit();

    result.setContinue(true);
    result.setOutcome(true);
    result.setMessage(new Message("default", "The collection was successfully deleted."));

    return result;
  }
  /**
   * startWorkflow() begins a workflow - in a single transaction do away with the PersonalWorkspace
   * entry and turn it into a WorkflowItem.
   *
   * @param c Context
   * @param wsi The WorkspaceItem to convert to a workflow item
   * @return The resulting workflow item
   */
  public static WorkflowItem start(Context c, WorkspaceItem wsi)
      throws SQLException, AuthorizeException, IOException {
    // FIXME Check auth
    Item myitem = wsi.getItem();
    Collection collection = wsi.getCollection();

    log.info(
        LogManager.getHeader(
            c,
            "start_workflow",
            "workspace_item_id="
                + wsi.getID()
                + "item_id="
                + myitem.getID()
                + "collection_id="
                + collection.getID()));

    // record the start of the workflow w/provenance message
    recordStart(c, myitem);

    // create the WorkflowItem
    TableRow row = DatabaseManager.create(c, "workflowitem");
    row.setColumn("item_id", myitem.getID());
    row.setColumn("collection_id", wsi.getCollection().getID());

    WorkflowItem wfi = new WorkflowItem(c, row);

    wfi.setMultipleFiles(wsi.hasMultipleFiles());
    wfi.setMultipleTitles(wsi.hasMultipleTitles());
    wfi.setPublishedBefore(wsi.isPublishedBefore());

    // remove the WorkspaceItem
    wsi.deleteWrapper();

    // now get the worflow started
    doState(c, wfi, WFSTATE_STEP1POOL, null);

    // Return the workflow item
    return wfi;
  }
  /**
   * Commit the contained item to the main archive. The item is associated with the relevant
   * collection, added to the search index, and any other tasks such as assigning dates are
   * performed.
   *
   * @param context The relevant DSpace Context.
   * @param wfi workflow item
   * @return the fully archived item.
   * @throws IOException A general class of exceptions produced by failed or interrupted I/O
   *     operations.
   * @throws SQLException An exception that provides information on a database access error or other
   *     errors.
   * @throws AuthorizeException Exception indicating the current user of the context does not have
   *     permission to perform a particular action.
   */
  @Override
  public Item archive(Context context, XmlWorkflowItem wfi)
      throws SQLException, IOException, AuthorizeException {
    // FIXME: Check auth
    Item item = wfi.getItem();
    Collection collection = wfi.getCollection();

    // Remove (if any) the workflowItemroles for this item
    workflowItemRoleService.deleteForWorkflowItem(context, wfi);

    log.info(
        LogManager.getHeader(
            context,
            "archive_item",
            "workflow_item_id="
                + wfi.getID()
                + "item_id="
                + item.getID()
                + "collection_id="
                + collection.getID()));

    installItemService.installItem(context, wfi);

    // Notify
    notifyOfArchive(context, item, collection);

    // Clear any remaining workflow metadata
    itemService.clearMetadata(
        context, item, WorkflowRequirementsService.WORKFLOW_SCHEMA, Item.ANY, Item.ANY, Item.ANY);
    itemService.update(context, item);

    // Log the event
    log.info(
        LogManager.getHeader(
            context,
            "install_item",
            "workflow_item_id=" + wfi.getID() + ", item_id=" + item.getID() + "handle=FIXME"));

    return item;
  }
  /**
   * Get an array of all the collections that the current SWORD context will allow deposit onto in
   * the given DSpace context
   *
   * <p>IF: the authenticated user is an administrator AND: (the on-behalf-of user is an
   * administrator OR the on-behalf-of user is authorised to ADD OR the on-behalf-of user is null)
   * OR IF: the authenticated user is authorised to ADD AND: (the on-behalf-of user is an
   * administrator OR the on-behalf-of user is authorised to ADD OR the on-behalf-of user is null)
   *
   * @param swordContext
   * @return the array of allowed collections
   * @throws DSpaceSwordException
   */
  public List<org.dspace.content.Collection> getAllowedCollections(
      SwordContext swordContext, Community community) throws DSpaceSwordException {
    // a collection is allowed if the following conditions are met
    //
    // - the authenticated user is an administrator
    // -- the on-behalf-of user is an administrator
    // -- the on-behalf-of user is authorised to ADD
    // -- the on-behalf-of user is null
    // - the authenticated user is authorised to ADD
    // -- the on-behalf-of user is an administrator
    // -- the on-behalf-of user is authorised to ADD
    // -- the on-behalf-of user is null

    try {
      // get the context of the authenticated user
      Context authContext = swordContext.getAuthenticatorContext();

      // short cut by obtaining the collections to which the authenticated user can submit
      org.dspace.content.Collection[] cols =
          org.dspace.content.Collection.findAuthorized(authContext, community, Constants.ADD);
      List<org.dspace.content.Collection> allowed = new ArrayList<org.dspace.content.Collection>();

      // now find out if the obo user is allowed to submit to any of these collections
      for (int i = 0; i < cols.length; i++) {
        boolean oboAllowed = false;

        // check for obo null
        if (swordContext.getOnBehalfOf() == null) {
          oboAllowed = true;
        }

        // if we have not already determined that the obo user is ok to submit, look up the READ
        // policy on the
        // community.  THis will include determining if the user is an administrator.
        if (!oboAllowed) {
          oboAllowed =
              AuthorizeManager.authorizeActionBoolean(
                  swordContext.getOnBehalfOfContext(), cols[i], Constants.ADD);
        }

        // final check to see if we are allowed to READ
        if (oboAllowed) {
          allowed.add(cols[i]);
        }
      }
      return allowed;

    } catch (SQLException e) {
      log.error("Caught exception: ", e);
      throw new DSpaceSwordException(e);
    }
  }