示例#1
0
  /**
   * 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();
  }
示例#2
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;
  }
示例#3
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;
  }
  /**
   * Delete the specified handle. It is assumed that the user has already confirmed this selection.
   *
   * @param context The current DSpace context.
   * @param handleID ID of handle to be removed.
   * @return A results object.
   */
  public static FlowResult processDeleteHandle(Context context, int handleID)
      throws SQLException, AuthorizeException, IOException {
    FlowResult result = new FlowResult();

    result.setContinue(true);
    result.setOutcome(true);
    result.setMessage(T_handle_deletion_failed);

    try {

      Handle handleDeleted = Handle.find(context, handleID);

      HandleManager.changeHandle(context, handleDeleted.getHandle(), null, false);

      handleDeleted.delete();

      context.commit();

      result.setContinue(true);
      result.setOutcome(true);
      result.setMessage(T_handle_successfully_deleted);
    } catch (Exception e) {
      log.error(e.getMessage());
      context.abort();
    }

    return result;
  }
示例#5
0
  /**
   * Do any processing of the information input by the user, and/or perform step processing (if no
   * user interaction required)
   *
   * <p>It is this method's job to save any data to the underlying database, as necessary, and
   * return error messages (if any) which can then be processed by the appropriate user interface
   * (JSP-UI or XML-UI)
   *
   * <p>NOTE: If this step is a non-interactive step (i.e. requires no UI), then it should perform
   * *all* of its processing in this method!
   *
   * @param context current DSpace context
   * @param request current servlet request object
   * @param response current servlet response object
   * @param subInfo submission info object
   * @return Status or error flag which will be processed by doPostProcessing() below! (if
   *     STATUS_COMPLETE or 0 is returned, no errors occurred!)
   */
  public int doProcessing(
      Context context,
      HttpServletRequest request,
      HttpServletResponse response,
      SubmissionInfo subInfo)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // The Submission is COMPLETE!!
    log.info(
        LogManager.getHeader(
            context,
            "submission_complete",
            "Completed submission with id=" + subInfo.getSubmissionItem().getID()));

    // Start the workflow for this Submission
    boolean success = false;
    try {
      WorkflowManager.start(context, (WorkspaceItem) subInfo.getSubmissionItem());
      success = true;
    } catch (Exception e) {
      log.error("Caught exception in submission step: ", e);
      throw new ServletException(e);
    } finally {
      // commit changes to database
      if (success) {
        context.commit();
      } else {
        context.getDBConnection().rollback();
      }
    }
    return STATUS_COMPLETE;
  }
示例#6
0
  /**
   * Delete one of a community's roles
   *
   * @param context The current DSpace context.
   * @param communityID The community id.
   * @param roleName ADMIN.
   * @param groupID The id of the group associated with this role.
   * @return A process result's object.
   */
  public static FlowResult processDeleteCommunityRole(
      Context context, int communityID, String roleName, int groupID)
      throws SQLException, UIException, IOException, AuthorizeException {
    FlowResult result = new FlowResult();

    Community community = Community.find(context, communityID);
    Group role = Group.find(context, groupID);

    // First, unregister the role
    if (ROLE_ADMIN.equals(roleName)) {
      community.removeAdministrators();
    }

    // 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, community);
    for (ResourcePolicy policy : policies) {
      if (policy.getGroupID() == groupID) {
        policy.delete();
      }
    }

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

    result.setContinue(true);
    result.setOutcome(true);
    result.setMessage(new Message("default", "The role was successfully deleted."));
    return result;
  }
示例#7
0
  /**
   * Process the collection harvesting options form.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @param request the Cocoon request object
   * @return A process result's object.
   */
  public static FlowResult processSetupCollectionHarvesting(
      Context context, int collectionID, Request request)
      throws SQLException, IOException, AuthorizeException {
    FlowResult result = new FlowResult();
    HarvestedCollection hc = HarvestedCollection.find(context, collectionID);

    String contentSource = request.getParameter("source");

    // First, if this is not a harvested collection (anymore), set the harvest type to 0; possibly
    // also wipe harvest settings
    if (contentSource.equals("source_normal")) {
      if (hc != null) {
        hc.delete();
      }

      result.setContinue(true);
    } else {
      FlowResult subResult = testOAISettings(context, request);

      // create a new harvest instance if all the settings check out
      if (hc == null) {
        hc = HarvestedCollection.create(context, collectionID);
      }

      // if the supplied options all check out, set the harvesting parameters on the collection
      if (subResult.getErrors().isEmpty()) {
        String oaiProvider = request.getParameter("oai_provider");
        boolean oaiAllSets = "all".equals(request.getParameter("oai-set-setting"));
        String oaiSetId;
        if (oaiAllSets) {
          oaiSetId = "all";
        } else {
          oaiSetId = request.getParameter("oai_setid");
        }

        String metadataKey = request.getParameter("metadata_format");
        String harvestType = request.getParameter("harvest_level");

        hc.setHarvestParams(Integer.parseInt(harvestType), oaiProvider, oaiSetId, metadataKey);
        hc.setHarvestStatus(HarvestedCollection.STATUS_READY);
      } else {
        result.setErrors(subResult.getErrors());
        result.setContinue(false);
        return result;
      }

      hc.update();
    }

    // Save everything
    context.commit();

    // No notice...
    // result.setMessage(new Message("default","Harvesting options successfully modified."));
    result.setOutcome(true);
    result.setContinue(true);

    return result;
  }
 public static void applyFiltersItem(Context c, Item item) throws Exception {
   if (filterItem(c, item)) {
     // commit changes after each filtered item
     c.commit();
     // increment processed count
     ++processed;
   }
   // clear item objects from context cache
   item.decache();
 }
示例#9
0
  private String showMainPage(
      Context context, ModelMap model, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    Group[] groups = Group.findAll(context, Group.NAME);

    // if( groups == null ) { System.out.println("groups are null"); }
    // else System.out.println("# of groups: " + groups.length);
    model.addAttribute("groups", groups);
    context.commit();
    return "pages/admin/group-list";
  }
示例#10
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;
  }
示例#11
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;
  }
示例#12
0
  /**
   * Delete community itself
   *
   * @param context The current DSpace context.
   * @param communityID The community id.
   * @return A process result's object.
   */
  public static FlowResult processDeleteCommunity(Context context, int communityID)
      throws SQLException, AuthorizeException, IOException {
    FlowResult result = new FlowResult();

    Community community = Community.find(context, communityID);

    community.delete();
    context.commit();

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

    return result;
  }
示例#13
0
  /**
   * Look up the id of the template item for a given collection.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @return The id of the template item.
   * @throws IOException
   */
  public static int getTemplateItemID(Context context, int collectionID)
      throws SQLException, AuthorizeException, IOException {
    Collection collection = Collection.find(context, collectionID);
    Item template = collection.getTemplateItem();

    if (template == null) {
      collection.createTemplateItem();
      template = collection.getTemplateItem();

      collection.update();
      template.update();
      context.commit();
    }

    return template.getID();
  }
示例#14
0
  /**
   * Process input from the "change file description" page
   *
   * @param context current DSpace context
   * @param request current servlet request object
   * @param response current servlet response object
   * @param subInfo submission info object
   * @return Status or error flag which will be processed by UI-related code! (if STATUS_COMPLETE or
   *     0 is returned, no errors occurred!)
   */
  protected int processSaveFileDescription(
      Context context,
      HttpServletRequest request,
      HttpServletResponse response,
      SubmissionInfo subInfo)
      throws ServletException, IOException, SQLException, AuthorizeException {
    if (subInfo.getBitstream() != null) {
      subInfo.getBitstream().setDescription(request.getParameter("description"));
      subInfo.getBitstream().update();

      context.commit();
    } else {
      return STATUS_INTEGRITY_ERROR;
    }

    return STATUS_COMPLETE;
  }
  /** Return the list of running applications. */
  public static List<AbstractDSpaceWebapp> getApps() {
    ArrayList<AbstractDSpaceWebapp> apps = new ArrayList<AbstractDSpaceWebapp>();
    TableRowIterator tri;

    Context context = null;
    HttpMethod request = null;
    try {
      context = new Context();
      tri = DatabaseManager.queryTable(context, "Webapp", "SELECT * FROM Webapp");

      for (TableRow row : tri.toList()) {
        DSpaceWebapp app = new DSpaceWebapp();
        app.kind = row.getStringColumn("AppName");
        app.url = row.getStringColumn("URL");
        app.started = row.getDateColumn("Started");
        app.uiQ = row.getBooleanColumn("isUI");

        HttpClient client = new HttpClient();
        request = new HeadMethod(app.url);
        int status = client.executeMethod(request);
        request.getResponseBody();
        if (status != HttpStatus.SC_OK) {
          DatabaseManager.delete(context, row);
          context.commit();
          continue;
        }

        apps.add(app);
      }
    } catch (SQLException e) {
      log.error("Unable to list running applications", e);
    } catch (HttpException e) {
      log.error("Failure checking for a running webapp", e);
    } catch (IOException e) {
      log.error("Failure checking for a running webapp", e);
    } finally {
      if (null != request) {
        request.releaseConnection();
      }
      if (null != context) {
        context.abort();
      }
    }

    return apps;
  }
  /**
   * Change handle prefix. It is assumed that the user has already confirmed this selection.
   *
   * @param context The current DSpace context.
   * @param oldPrefix The prefix to be replace.
   * @param newPrefix The prefix to be used.
   * @param archiveOldHandles Should the former handles be archived?
   * @return A results object.
   */
  public static FlowResult changeHandlePrefix(
      Context context, String oldPrefix, String newPrefix, boolean archiveOldHandles)
      throws SQLException, AuthorizeException, IOException {
    FlowResult result = new FlowResult();

    result.setContinue(false);
    result.setOutcome(false);

    // If we have errors, the form needs to be resubmitted to fix those problems
    if (StringUtils.isEmpty(oldPrefix)) {
      result.addError("old_prefix_empty");
    }
    if (StringUtils.isEmpty(newPrefix)) {
      result.addError("new_prefix_empty");
    }
    if (result.getErrors() == null && oldPrefix.equals(newPrefix)) {
      result.addError("old_prefix_equals_new_prefix");
    }

    if (result.getErrors() == null) {
      try {
        // change prefixes
        HandleManager.changePrefix(context, oldPrefix, newPrefix, archiveOldHandles);
        context.commit();

        // reindex
        IndexBrowse.main(new String[] {"-i"});

        result.setContinue(true);
        result.setOutcome(true);
        result.setMessage(T_prefix_successfully_changed);

      } catch (Exception e) {
        result.setMessage(T_prefix_change_failed);
        log.error(e.getMessage());
        context.abort();
      }
    }

    return result;
  }
示例#17
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;
  }
示例#18
0
  /**
   * Purge the collection of all items, then run a fresh 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
   * @throws BrowseException
   */
  public static FlowResult processReimportCollection(
      Context context, int collectionID, Request request)
      throws SQLException, IOException, AuthorizeException, CrosswalkException,
          ParserConfigurationException, SAXException, TransformerException, BrowseException {
    Collection collection = Collection.find(context, collectionID);
    HarvestedCollection hc = HarvestedCollection.find(context, collectionID);

    ItemIterator it = collection.getAllItems();
    // IndexBrowse ib = new IndexBrowse(context);
    while (it.hasNext()) {
      Item item = it.next();
      // System.out.println("Deleting: " + item.getHandle());
      // ib.itemRemoved(item);
      collection.removeItem(item);
    }
    hc.setHarvestResult(null, "");
    hc.update();
    collection.update();
    context.commit();

    return processRunCollectionHarvest(context, collectionID, request);
  }
示例#19
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 communityID The collection id.
   * @param roleName ADMIN.
   * @return The id of the group associated with that particular role, or -1 if the role was not
   *     found.
   */
  public static int getCommunityRole(Context context, int communityID, String roleName)
      throws SQLException, AuthorizeException, IOException {
    Community community = Community.find(context, communityID);

    // Determine the group based upon which role we are looking for.
    Group role = null;
    if (ROLE_ADMIN.equals(roleName)) {
      role = community.getAdministrators();
      if (role == null) {
        role = community.createAdministrators();
      }
    }

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

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

    return -1;
  }
示例#20
0
  /**
   * Do any processing of the information input by the user, and/or perform step processing (if no
   * user interaction required)
   *
   * <p>It is this method's job to save any data to the underlying database, as necessary, and
   * return error messages (if any) which can then be processed by the appropriate user interface
   * (JSP-UI or XML-UI)
   *
   * <p>NOTE: If this step is a non-interactive step (i.e. requires no UI), then it should perform
   * *all* of its processing in this method!
   *
   * @param context current DSpace context
   * @param request current servlet request object
   * @param response current servlet response object
   * @param subInfo submission info object
   * @return Status or error flag which will be processed by doPostProcessing() below! (if
   *     STATUS_COMPLETE or 0 is returned, no errors occurred!)
   */
  public int doProcessing(
      Context context,
      HttpServletRequest request,
      HttpServletResponse response,
      SubmissionInfo subInfo)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // get button user pressed
    String buttonPressed = Util.getSubmitButton(request, NEXT_BUTTON);

    // get reference to item
    Item item = subInfo.getSubmissionItem().getItem();

    // -----------------------------------
    // Step #0: Upload new files (if any)
    // -----------------------------------
    String contentType = request.getContentType();

    // if multipart form, then we are uploading a file
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) {
      // This is a multipart request, so it's a file upload
      // (return any status messages or errors reported)
      int status = processUploadFile(context, request, response, subInfo);

      // if error occurred, return immediately
      if (status != STATUS_COMPLETE) {
        return status;
      }
    }

    // if user pressed jump-to button in process bar,
    // return success (so that jump will occur)
    if (buttonPressed.startsWith(PROGRESS_BAR_PREFIX)) {
      // check if a file is required to be uploaded
      if (fileRequired && !item.hasUploadedFiles()) {
        return STATUS_NO_FILES_ERROR;
      } else {
        return STATUS_COMPLETE;
      }
    }

    // ---------------------------------------------
    // Step #1: Check if this was just a request to
    // edit file information.
    // (or canceled editing information)
    // ---------------------------------------------
    // check if we're already editing a specific bitstream
    if (request.getParameter("bitstream_id") != null) {
      if (buttonPressed.equals(CANCEL_EDIT_BUTTON)) {
        // canceled an edit bitstream request
        subInfo.setBitstream(null);

        // this flag will just return us to the normal upload screen
        return STATUS_EDIT_COMPLETE;
      } else {
        // load info for bitstream we are editing
        Bitstream b =
            Bitstream.find(context, Integer.parseInt(request.getParameter("bitstream_id")));

        // save bitstream to submission info
        subInfo.setBitstream(b);
      }
    } else if (buttonPressed.startsWith("submit_edit_")) {
      // get ID of bitstream that was requested for editing
      String bitstreamID = buttonPressed.substring("submit_edit_".length());

      Bitstream b = Bitstream.find(context, Integer.parseInt(bitstreamID));

      // save bitstream to submission info
      subInfo.setBitstream(b);

      // return appropriate status flag to say we are now editing the
      // bitstream
      return STATUS_EDIT_BITSTREAM;
    }

    // ---------------------------------------------
    // Step #2: Process any remove file request(s)
    // ---------------------------------------------
    // Remove-selected requests come from Manakin
    if (buttonPressed.equalsIgnoreCase("submit_remove_selected")) {
      // this is a remove multiple request!

      if (request.getParameter("remove") != null) {
        // get all files to be removed
        String[] removeIDs = request.getParameterValues("remove");

        // remove each file in the list
        for (int i = 0; i < removeIDs.length; i++) {
          int id = Integer.parseInt(removeIDs[i]);

          int status = processRemoveFile(context, item, id);

          // if error occurred, return immediately
          if (status != STATUS_COMPLETE) {
            return status;
          }
        }

        // remove current bitstream from Submission Info
        subInfo.setBitstream(null);
      }
    } else if (buttonPressed.startsWith("submit_remove_")) {
      // A single file "remove" button must have been pressed

      int id = Integer.parseInt(buttonPressed.substring(14));
      int status = processRemoveFile(context, item, id);

      // if error occurred, return immediately
      if (status != STATUS_COMPLETE) {
        return status;
      }

      // remove current bitstream from Submission Info
      subInfo.setBitstream(null);
    }

    // -------------------------------------------------
    // Step #3: Check for a change in file description
    // -------------------------------------------------
    String fileDescription = request.getParameter("description");

    if (fileDescription != null && fileDescription.length() > 0) {
      // save this file description
      int status = processSaveFileDescription(context, request, response, subInfo);

      // if error occurred, return immediately
      if (status != STATUS_COMPLETE) {
        return status;
      }
    }

    // ------------------------------------------
    // Step #4: Check for a file format change
    // (if user had to manually specify format)
    // ------------------------------------------
    int formatTypeID = Util.getIntParameter(request, "format");
    String formatDesc = request.getParameter("format_description");

    // if a format id or description was found, then save this format!
    if (formatTypeID >= 0 || (formatDesc != null && formatDesc.length() > 0)) {
      // save this specified format
      int status = processSaveFileFormat(context, request, response, subInfo);

      // if error occurred, return immediately
      if (status != STATUS_COMPLETE) {
        return status;
      }
    }

    // ---------------------------------------------------
    // Step #5: Check if primary bitstream has changed
    // -------------------------------------------------
    if (request.getParameter("primary_bitstream_id") != null) {
      Bundle[] bundles = item.getBundles("ORIGINAL");
      if (bundles.length > 0) {
        bundles[0].setPrimaryBitstreamID(
            Integer.valueOf(request.getParameter("primary_bitstream_id")).intValue());
        bundles[0].update();
      }
    }

    // ---------------------------------------------------
    // Step #6: Determine if there is an error because no
    // files have been uploaded.
    // ---------------------------------------------------
    // check if a file is required to be uploaded
    if (fileRequired && !item.hasUploadedFiles()) {
      return STATUS_NO_FILES_ERROR;
    }

    // commit all changes to database
    context.commit();

    return STATUS_COMPLETE;
  }
示例#21
0
  @RequestMapping(method = RequestMethod.POST)
  protected String processPost(
      @RequestAttribute Context context,
      ModelMap model,
      HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {

    Group group = null;
    group = checkGroup(context, request);

    if (group != null) {

      // is this user authorized to edit this group?
      AuthorizeManager.authorizeAction(context, group, Constants.ADD);

      boolean submit_edit = (request.getParameter("submit_edit") != null);
      boolean submit_group_update = (request.getParameter("submit_group_update") != null);
      boolean submit_group_delete = (request.getParameter("submit_group_delete") != null);
      boolean submit_confirm_delete = (request.getParameter("submit_confirm_delete") != null);
      boolean submit_cancel_delete = (request.getParameter("submit_cancel_delete") != null);

      // just chosen a group to edit - get group and pass it to
      // group-edit.jsp
      if (submit_edit && !submit_group_update && !submit_group_delete) {
        model.addAttribute("group", group);
        model.addAttribute("members", group.getMembers());
        model.addAttribute("membergroups", group.getMemberGroups());
        String utilsGrpName = Utils.addEntities(group.getName());
        model.addAttribute("utilsGrpName", utilsGrpName);

        return "pages/admin/group-edit";
      } // update the members of the group
      else if (submit_group_update) {
        // first off, did we change the group name?
        String newName = request.getParameter("group_name");

        if (!newName.equals(group.getName())) {
          group.setName(newName);
          group.update();
        }

        int[] eperson_ids = Util.getIntParameters(request, "eperson_id");
        int[] group_ids = Util.getIntParameters(request, "group_ids");

        // now get members, and add new ones and remove missing ones
        EPerson[] members = group.getMembers();
        Group[] membergroups = group.getMemberGroups();

        if (eperson_ids != null) {
          // some epeople were listed, now make group's epeople match
          // given epeople
          Set memberSet = new HashSet();
          Set epersonIDSet = new HashSet();

          // add all members to a set
          for (int x = 0; x < members.length; x++) {
            Integer epersonID = Integer.valueOf(members[x].getID());
            memberSet.add(epersonID);
          }

          // now all eperson_ids are put in a set
          for (int x = 0; x < eperson_ids.length; x++) {
            epersonIDSet.add(Integer.valueOf(eperson_ids[x]));
          }

          // process eperson_ids, adding those to group not already
          // members
          Iterator i = epersonIDSet.iterator();

          while (i.hasNext()) {
            Integer currentID = (Integer) i.next();

            if (!memberSet.contains(currentID)) {
              group.addMember(EPerson.find(context, currentID.intValue()));
            }
          }

          // process members, removing any that aren't in eperson_ids
          for (int x = 0; x < members.length; x++) {
            EPerson e = members[x];

            if (!epersonIDSet.contains(Integer.valueOf(e.getID()))) {
              group.removeMember(e);
            }
          }
        } else {
          // no members found (ids == null), remove them all!

          for (int y = 0; y < members.length; y++) {
            group.removeMember(members[y]);
          }
        }

        if (group_ids != null) {
          // some groups were listed, now make group's member groups
          // match given group IDs
          Set memberSet = new HashSet();
          Set groupIDSet = new HashSet();

          // add all members to a set
          for (int x = 0; x < membergroups.length; x++) {
            Integer myID = Integer.valueOf(membergroups[x].getID());
            memberSet.add(myID);
          }

          // now all eperson_ids are put in a set
          for (int x = 0; x < group_ids.length; x++) {
            groupIDSet.add(Integer.valueOf(group_ids[x]));
          }

          // process group_ids, adding those to group not already
          // members
          Iterator i = groupIDSet.iterator();

          while (i.hasNext()) {
            Integer currentID = (Integer) i.next();

            if (!memberSet.contains(currentID)) {
              group.addMember(Group.find(context, currentID.intValue()));
            }
          }

          // process members, removing any that aren't in eperson_ids
          for (int x = 0; x < membergroups.length; x++) {
            Group g = membergroups[x];

            if (!groupIDSet.contains(Integer.valueOf(g.getID()))) {
              group.removeMember(g);
            }
          }

        } else {
          // no members found (ids == null), remove them all!
          for (int y = 0; y < membergroups.length; y++) {
            group.removeMember(membergroups[y]);
          }
        }

        group.update();

        model.addAttribute("group", group);
        model.addAttribute("members", group.getMembers());
        model.addAttribute("membergroups", group.getMemberGroups());
        String utilsGrpName = Utils.addEntities(group.getName());
        model.addAttribute("utilsGrpName", utilsGrpName);

        context.commit();
        return "pages/admin/group-edit";
      } else if (submit_group_delete) {
        // direct to a confirmation step
        model.addAttribute("group", group);
        return "pages/admin/group-confirm-delete";
      } else if (submit_confirm_delete) {
        // phony authorize, only admins can do this
        AuthorizeManager.authorizeAction(context, group, Constants.WRITE);

        // delete group, return to group-list.jsp
        group.delete();

        return showMainPage(context, model, request, response);
      } else if (submit_cancel_delete) {
        // show group list
        return showMainPage(context, model, request, response);
      } else {
        // unknown action, show edit page
        model.addAttribute("group", group);
        model.addAttribute("members", group.getMembers());
        model.addAttribute("membergroups", group.getMemberGroups());
        String utilsGrpName = Utils.addEntities(group.getName());
        model.addAttribute("utilsGrpName", utilsGrpName);

        return "pages/admin/group-edit";
      }
    } else {

      // want to add a group - create a blank one, and pass to
      // group_edit.jsp
      String button = UIUtil.getSubmitButton(request, "submit");

      if (button.equals("submit_add")) {
        group = Group.create(context);

        group.setName("new group" + group.getID());
        group.update();

        model.addAttribute("group", group);
        model.addAttribute("members", group.getMembers());
        model.addAttribute("membergroups", group.getMemberGroups());
        String utilsGrpName = Utils.addEntities(group.getName());
        model.addAttribute("utilsGrpName", utilsGrpName);

        context.commit();
        return "pages/admin/group-edit";

      } else {
        // show the main page (select groups)
        return showMainPage(context, model, request, response);
      }
    } // end
  } // end processGet
示例#22
0
  private void processArchive(
      Context context,
      String sourceDirPath,
      String itemField,
      String metadataIndexName,
      boolean alterProvenance,
      boolean isTest)
      throws Exception {
    // open and process the source directory
    File sourceDir = new File(sourceDirPath);

    if ((sourceDir == null) || !sourceDir.exists() || !sourceDir.isDirectory()) {
      pr("Error, cannot open archive source directory " + sourceDirPath);
      throw new Exception("error with archive source directory " + sourceDirPath);
    }

    String[] dircontents = sourceDir.list(directoryFilter); // just the names, not the path
    Arrays.sort(dircontents);

    // Undo is suppressed to prevent undo of undo
    boolean suppressUndo = false;
    File fSuppressUndo = new File(sourceDir, SUPPRESS_UNDO_FILENAME);
    if (fSuppressUndo.exists()) {
      suppressUndo = true;
    }

    File undoDir = null; // sibling directory of source archive

    if (!suppressUndo && !isTest) {
      undoDir = initUndoArchive(sourceDir);
    }

    int itemCount = 0;
    int successItemCount = 0;

    for (String dirname : dircontents) {
      itemCount++;
      pr("");
      pr("processing item " + dirname);

      try {
        ItemArchive itarch = ItemArchive.create(context, new File(sourceDir, dirname), itemField);

        for (UpdateAction action : actionMgr) {
          pr("action: " + action.getClass().getName());
          action.execute(context, itarch, isTest, suppressUndo);
          if (!isTest && !suppressUndo) {
            itarch.writeUndo(undoDir);
          }
        }
        if (!isTest) {
          Item item = itarch.getItem();
          item.update(); // need to update before commit
          context.commit();
          item.decache();
        }
        ItemUpdate.pr("Item " + dirname + " completed");
        successItemCount++;
      } catch (Exception e) {
        pr("Exception processing item " + dirname + ": " + e.toString());
      }
    }

    if (!suppressUndo && !isTest) {
      StringBuilder sb = new StringBuilder("dsrun org.dspace.app.itemupdate.ItemUpdate ");
      sb.append(" -e ").append(this.eperson);
      sb.append(" -s ").append(undoDir);

      if (itemField != null) {
        sb.append(" -i ").append(itemField);
      }

      if (!alterProvenance) {
        sb.append(" -P ");
      }
      if (isTest) {
        sb.append(" -t ");
      }

      for (String actionOption : undoActionList) {
        sb.append(actionOption);
      }

      PrintWriter pw = null;
      try {
        File cmdFile = new File(undoDir.getParent(), undoDir.getName() + "_command.sh");
        pw = new PrintWriter(new BufferedWriter(new FileWriter(cmdFile)));
        pw.println(sb.toString());
      } finally {
        pw.close();
      }
    }

    pr("");
    pr(
        "Done processing.  Successful items: "
            + successItemCount
            + " of "
            + itemCount
            + " items in source archive");
    pr("");
  }
  /**
   * Save the handle.
   *
   * <p>If the handleID is -1 then a new handle is created.
   *
   * @param context The current dspace context
   * @param handleID The handle ID, or -1 for a new handle.
   * @param url The handle URL
   * @param resourceTypeID The type of referenced resource
   * @param resourceID ID of referenced resource
   * @return A result
   */
  public static FlowResult processSaveHandle(
      Context context,
      int handleID,
      String handle,
      String url,
      int resourceTypeID,
      int resourceID,
      boolean archiveOldHandle)
      throws SQLException, AuthorizeException, UIException {
    FlowResult result = new FlowResult();
    result.setParameter("handle_id", handleID);

    result.setContinue(false);
    result.setOutcome(false);

    // If we have errors, the form needs to be resubmitted to fix those problems
    if (StringUtils.isEmpty(handle)) {
      result.addError("handle_empty");
    }
    if (resourceTypeID == -1 && resourceID == -1 && StringUtils.isEmpty(url)) {
      result.addError("url_empty");
    } else if (StringUtils.isEmpty(url)) {
      if (resourceTypeID == -1) {
        result.addError("resource_type_id_empty");
      }
      if (resourceID == -1) {
        result.addError("resource_id_empty");
      }
    }

    if (result.getErrors() == null) {

      try {

        Handle h = null;
        if (handleID == -1) {
          h = Handle.create(context, null, handle);
        } else {
          h = Handle.find(context, handleID);
          if (h.getHandle() != handle) {
            HandleManager.changeHandle(context, h.getHandle(), handle, archiveOldHandle);
          }
        }

        h.setHandle(handle);
        h.setURL(url);
        h.setResourceTypeID(resourceTypeID);
        h.setResourceID(resourceID);
        h.update();

        context.commit();

        result.setContinue(true);
        result.setOutcome(true);
        result.setMessage(T_handle_successfully_saved);
      } catch (Exception e) {
        result.setMessage(T_handle_saving_failed);
        log.error(e.getMessage());
        context.abort();
      }
    }

    return result;
  }
示例#24
0
  /**
   * Create new Item out of the ingested package, in the indicated collection. It creates a
   * workspace item, which the application can then install if it chooses to bypass Workflow.
   *
   * <p>This is a VERY crude import of a single Adobe PDF (Portable Document Format) file, using the
   * document's embedded metadata for package metadata. If the PDF file hasn't got the minimal
   * metadata available, it is rejected.
   *
   * <p>
   *
   * @param context DSpace context.
   * @param collection collection under which to create new item.
   * @param pkg input stream containing package to ingest.
   * @param params package parameters (none recognized)
   * @param license may be null, which takes default license.
   * @return workspace item created by ingest.
   * @throws PackageException if package is unacceptable or there is a fatal error turning it into
   *     an Item.
   */
  public WorkspaceItem ingest(
      Context context,
      Collection collection,
      InputStream pkg,
      PackageParameters params,
      String license)
      throws PackageValidationException, CrosswalkException, AuthorizeException, SQLException,
          IOException {
    InputStream bis = null;
    COSDocument cos = null;
    boolean success = false;
    Bundle original = null;
    Bitstream bs = null;
    WorkspaceItem wi = null;

    /**
     * XXX comment out for now // XXX for debugging of parameter handling if (params != null) {
     * Enumeration pe = params.propertyNames(); while (pe.hasMoreElements()) { String name =
     * (String)pe.nextElement(); String v[] = params.getProperties(name); StringBuffer msg = new
     * StringBuffer("PackageParam: "); msg.append(name).append(" = "); for (int i = 0; i < v.length;
     * ++i) { if (i > 0) msg.append(", "); msg.append(v[i]); } log.debug(msg); } }
     */
    try {
      // Save the PDF in a bitstream first, since the parser
      // has to read it as well, and we cannot "rewind" it after that.
      wi = WorkspaceItem.create(context, collection, false);
      Item myitem = wi.getItem();
      original = myitem.createBundle("ORIGINAL");
      bs = original.createBitstream(pkg);
      pkg.close();
      bs.setName("package.pdf");
      setFormatToMIMEType(context, bs, "application/pdf");
      bs.update();
      log.debug("Created bitstream ID=" + String.valueOf(bs.getID()) + ", parsing...");

      crosswalkPDF(context, myitem, bs.retrieve());

      wi.update();
      context.commit();
      success = true;
      log.info(
          LogManager.getHeader(
              context,
              "ingest",
              "Created new Item, db ID="
                  + String.valueOf(myitem.getID())
                  + ", WorkspaceItem ID="
                  + String.valueOf(wi.getID())));
      return wi;
    } finally {
      try {
        // Close bitstream input stream and PDF file.
        if (bis != null) bis.close();
        if (cos != null) cos.close();
      } catch (IOException ie) {
      }

      // get rid of bitstream and item if ingest fails
      if (!success) {
        if (original != null && bs != null) original.removeBitstream(bs);
        if (wi != null) wi.deleteAll();
      }
      context.commit();
    }
  }
示例#25
0
  /**
   * item? try and add it to the archive.
   *
   * @param mycollections - add item to these Collections.
   * @param path - directory containing the item directories.
   * @param itemname handle - non-null means we have a pre-defined handle already
   * @param mapOut - mapfile we're writing
   */
  private Item addItem(
      Context c,
      Collection[] mycollections,
      String path,
      String itemname,
      PrintWriter mapOut,
      boolean template)
      throws Exception {
    String mapOutput = null;

    System.out.println("Adding item from directory " + itemname);

    // create workspace item
    Item myitem = null;
    WorkspaceItem wi = null;

    if (!isTest) {
      wi = WorkspaceItem.create(c, mycollections[0], template);
      myitem = wi.getItem();
    }

    // now fill out dublin core for item
    loadMetadata(c, myitem, path + File.separatorChar + itemname + File.separatorChar);

    // and the bitstreams from the contents file
    // process contents file, add bitstreams and bundles, return any
    // non-standard permissions
    List<String> options =
        processContentsFile(c, myitem, path + File.separatorChar + itemname, "contents");

    if (useWorkflow) {
      // don't process handle file
      // start up a workflow
      if (!isTest) {
        // Should we send a workflow alert email or not?
        if (ConfigurationManager.getProperty("workflow", "workflow.framework")
            .equals("xmlworkflow")) {
          if (useWorkflowSendEmail) {
            XmlWorkflowManager.start(c, wi);
          } else {
            XmlWorkflowManager.startWithoutNotify(c, wi);
          }
        } else {
          if (useWorkflowSendEmail) {
            WorkflowManager.start(c, wi);
          } else {
            WorkflowManager.startWithoutNotify(c, wi);
          }
        }

        // send ID to the mapfile
        mapOutput = itemname + " " + myitem.getID();
      }
    } else {
      // only process handle file if not using workflow system
      String myhandle =
          processHandleFile(c, myitem, path + File.separatorChar + itemname, "handle");

      // put item in system
      if (!isTest) {
        InstallItem.installItem(c, wi, myhandle);

        // find the handle, and output to map file
        myhandle = HandleManager.findHandle(c, myitem);

        mapOutput = itemname + " " + myhandle;
      }

      // set permissions if specified in contents file
      if (options.size() > 0) {
        System.out.println("Processing options");
        processOptions(c, myitem, options);
      }
    }

    // now add to multiple collections if requested
    if (mycollections.length > 1) {
      for (int i = 1; i < mycollections.length; i++) {
        if (!isTest) {
          mycollections[i].addItem(myitem);
        }
      }
    }

    // made it this far, everything is fine, commit transaction
    if (mapOut != null) {
      mapOut.println(mapOutput);
    }

    c.commit();

    return myitem;
  }
示例#26
0
  /**
   * Process the upload of a new file!
   *
   * @param context current DSpace context
   * @param request current servlet request object
   * @param response current servlet response object
   * @param subInfo submission info object
   * @return Status or error flag which will be processed by UI-related code! (if STATUS_COMPLETE or
   *     0 is returned, no errors occurred!)
   */
  protected int processUploadFile(
      Context context,
      HttpServletRequest request,
      HttpServletResponse response,
      SubmissionInfo subInfo)
      throws ServletException, IOException, SQLException, AuthorizeException {
    boolean formatKnown = true;
    boolean fileOK = false;
    BitstreamFormat bf = null;
    Bitstream b = null;

    // NOTE: File should already be uploaded.
    // Manakin does this automatically via Cocoon.
    // For JSP-UI, the SubmissionController.uploadFiles() does the actual upload

    Enumeration attNames = request.getAttributeNames();

    // loop through our request attributes
    while (attNames.hasMoreElements()) {
      String attr = (String) attNames.nextElement();

      // if this ends with "-path", this attribute
      // represents a newly uploaded file
      if (attr.endsWith("-path")) {
        // strip off the -path to get the actual parameter
        // that the file was uploaded as
        String param = attr.replace("-path", "");

        // Load the file's path and input stream and description
        String filePath = (String) request.getAttribute(param + "-path");
        InputStream fileInputStream = (InputStream) request.getAttribute(param + "-inputstream");

        // attempt to get description from attribute first, then direct from a parameter
        String fileDescription = (String) request.getAttribute(param + "-description");
        if (fileDescription == null || fileDescription.length() == 0) {
          fileDescription = request.getParameter("description");
        }

        // if information wasn't passed by User Interface, we had a problem
        // with the upload
        if (filePath == null || fileInputStream == null) {
          return STATUS_UPLOAD_ERROR;
        }

        if (subInfo == null) {
          // In any event, if we don't have the submission info, the request
          // was malformed
          return STATUS_INTEGRITY_ERROR;
        }

        // Create the bitstream
        Item item = subInfo.getSubmissionItem().getItem();

        // do we already have a bundle?
        Bundle[] bundles = item.getBundles("ORIGINAL");

        if (bundles.length < 1) {
          // set bundle's name to ORIGINAL
          b = item.createSingleBitstream(fileInputStream, "ORIGINAL");
        } else {
          // we have a bundle already, just add bitstream
          b = bundles[0].createBitstream(fileInputStream);
        }

        // Strip all but the last filename. It would be nice
        // to know which OS the file came from.
        String noPath = filePath;

        while (noPath.indexOf('/') > -1) {
          noPath = noPath.substring(noPath.indexOf('/') + 1);
        }

        while (noPath.indexOf('\\') > -1) {
          noPath = noPath.substring(noPath.indexOf('\\') + 1);
        }

        b.setName(noPath);
        b.setSource(filePath);
        b.setDescription(fileDescription);

        // Identify the format
        bf = FormatIdentifier.guessFormat(context, b);
        b.setFormat(bf);

        // Update to DB
        b.update();
        item.update();

        if ((bf != null) && (bf.isInternal())) {
          log.warn("Attempt to upload file format marked as internal system use only");
          backoutBitstream(subInfo, b, item);
          return STATUS_UPLOAD_ERROR;
        }

        // Check for virus
        if (ConfigurationManager.getBooleanProperty("submission-curation", "virus-scan")) {
          Curator curator = new Curator();
          curator.addTask("vscan").curate(item);
          int status = curator.getStatus("vscan");
          if (status == Curator.CURATE_ERROR) {
            backoutBitstream(subInfo, b, item);
            return STATUS_VIRUS_CHECKER_UNAVAILABLE;
          } else if (status == Curator.CURATE_FAIL) {
            backoutBitstream(subInfo, b, item);
            return STATUS_CONTAINS_VIRUS;
          }
        }

        // If we got this far then everything is more or less ok.

        // Comment - not sure if this is the right place for a commit here
        // but I'm not brave enough to remove it - Robin.
        context.commit();

        // save this bitstream to the submission info, as the
        // bitstream we're currently working with
        subInfo.setBitstream(b);

        // if format was not identified
        if (bf == null) {
          return STATUS_UNKNOWN_FORMAT;
        }
      } // end if attribute ends with "-path"
    } // end while

    return STATUS_COMPLETE;
  }
示例#27
0
  /**
   * Process the community metadata edit form.
   *
   * @param context The current DSpace context.
   * @param communityID The community id.
   * @param deleteLogo Determines if the logo should be deleted along with the metadata editing
   *     action.
   * @param request the Cocoon request object
   * @return A process result's object.
   */
  public static FlowResult processEditCommunity(
      Context context, int communityID, boolean deleteLogo, Request request)
      throws AuthorizeException, IOException, SQLException {
    FlowResult result = new FlowResult();

    Community community = Community.find(context, communityID);

    String name = request.getParameter("name");
    String shortDescription = request.getParameter("short_description");
    String introductoryText = request.getParameter("introductory_text");
    String copyrightText = request.getParameter("copyright_text");
    String sideBarText = request.getParameter("side_bar_text");

    // If they don't have a name then make it untitled.
    if (name == null || name.length() == 0) {
      name = "Untitled";
    }

    // If empty, make it null.
    if (shortDescription != null && shortDescription.length() == 0) {
      shortDescription = null;
    }
    if (introductoryText != null && introductoryText.length() == 0) {
      introductoryText = null;
    }
    if (copyrightText != null && copyrightText.length() == 0) {
      copyrightText = null;
    }
    if (sideBarText != null && sideBarText.length() == 0) {
      sideBarText = null;
    }

    // Save the data
    community.setMetadata("name", name);
    community.setMetadata("short_description", shortDescription);
    community.setMetadata("introductory_text", introductoryText);
    community.setMetadata("copyright_text", copyrightText);
    community.setMetadata("side_bar_text", sideBarText);

    if (deleteLogo) {
      // Remove the logo
      community.setLogo(null);
    } else {
      // Update the logo
      Object object = request.get("logo");
      Part filePart = null;
      if (object instanceof Part) {
        filePart = (Part) object;
      }

      if (filePart != null && filePart.getSize() > 0) {
        InputStream is = filePart.getInputStream();

        community.setLogo(is);
      }
    }

    // Save everything
    community.update();
    context.commit();

    // No notice...
    result.setContinue(true);
    return result;
  }
示例#28
0
  /**
   * Create a new community
   *
   * @param context The current DSpace context.
   * @param communityID The id of the parent community (-1 for a top-level community).
   * @return A process result's object.
   */
  public static FlowResult processCreateCommunity(Context context, int communityID, Request request)
      throws AuthorizeException, IOException, SQLException {
    FlowResult result = new FlowResult();

    Community parent = Community.find(context, communityID);
    Community newCommunity;

    if (parent != null) {
      newCommunity = parent.createSubcommunity();
    } else {
      newCommunity = Community.create(null, context);
    }

    String name = request.getParameter("name");
    String shortDescription = request.getParameter("short_description");
    String introductoryText = request.getParameter("introductory_text");
    String copyrightText = request.getParameter("copyright_text");
    String sideBarText = request.getParameter("side_bar_text");

    // If they don't have a name then make it untitled.
    if (name == null || name.length() == 0) {
      name = "Untitled";
    }

    // If empty, make it null.
    if (shortDescription != null && shortDescription.length() == 0) {
      shortDescription = null;
    }
    if (introductoryText != null && introductoryText.length() == 0) {
      introductoryText = null;
    }
    if (copyrightText != null && copyrightText.length() == 0) {
      copyrightText = null;
    }
    if (sideBarText != null && sideBarText.length() == 0) {
      sideBarText = null;
    }

    newCommunity.setMetadata("name", name);
    newCommunity.setMetadata("short_description", shortDescription);
    newCommunity.setMetadata("introductory_text", introductoryText);
    newCommunity.setMetadata("copyright_text", copyrightText);
    newCommunity.setMetadata("side_bar_text", sideBarText);

    // Upload the logo
    Object object = request.get("logo");
    Part filePart = null;
    if (object instanceof Part) {
      filePart = (Part) object;
    }

    if (filePart != null && filePart.getSize() > 0) {
      InputStream is = filePart.getInputStream();

      newCommunity.setLogo(is);
    }

    // Save everything
    newCommunity.update();
    context.commit();
    // success
    result.setContinue(true);
    result.setOutcome(true);
    result.setMessage(new Message("default", "The community was successfully created."));
    result.setParameter("communityID", newCommunity.getID());

    return result;
  }