@GET
  @Path("/{bitstream_id}")
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Bitstream getBitstream(
      @PathParam("bitstream_id") Integer bitstream_id, @QueryParam("expand") String expand) {
    org.dspace.core.Context context = null;
    try {
      context = new org.dspace.core.Context();

      org.dspace.content.Bitstream bitstream =
          org.dspace.content.Bitstream.find(context, bitstream_id);

      if (AuthorizeManager.authorizeActionBoolean(
          context, bitstream, org.dspace.core.Constants.READ)) {
        return new org.dspace.rest.common.Bitstream(bitstream, expand);
      } else {
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
      }
    } catch (SQLException e) {
      log.error(e.getMessage());
      throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    } finally {
      if (context != null) {
        try {
          context.complete();
        } catch (SQLException e) {
          log.error(e.getMessage() + " occurred while trying to close");
        }
      }
    }
  }
Beispiel #2
0
  /**
   * Remove a file from an item
   *
   * @param context current DSpace context
   * @param item Item where file should be removed from
   * @param bitstreamID The id of bitstream representing the file to remove
   * @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 processRemoveFile(Context context, Item item, int bitstreamID)
      throws IOException, SQLException, AuthorizeException {
    Bitstream bitstream;

    // Try to find bitstream
    try {
      bitstream = Bitstream.find(context, bitstreamID);
    } catch (NumberFormatException nfe) {
      bitstream = null;
    }

    if (bitstream == null) {
      // Invalid or mangled bitstream ID
      // throw an error and return immediately
      return STATUS_INTEGRITY_ERROR;
    }

    // remove bitstream from bundle..
    // delete bundle if it's now empty
    Bundle[] bundles = bitstream.getBundles();

    bundles[0].removeBitstream(bitstream);

    Bitstream[] bitstreams = bundles[0].getBitstreams();

    // remove bundle if it's now empty
    if (bitstreams.length < 1) {
      item.removeBundle(bundles[0]);
      item.update();
    }

    // no errors occurred
    return STATUS_COMPLETE;
  }
  /**
   * Delete bitstream from item
   *
   * @param context
   * @param ItemArchive
   * @param isTest
   * @param suppressUndo
   * @throws IllegalArgumentException
   * @throws ParseException
   * @throws IOException
   * @throws AuthorizeException
   * @throws SQLException
   */
  public void execute(Context context, ItemArchive itarch, boolean isTest, boolean suppressUndo)
      throws IllegalArgumentException, IOException, SQLException, AuthorizeException,
          ParseException {
    File f = new File(itarch.getDirectory(), ItemUpdate.DELETE_CONTENTS_FILE);
    if (!f.exists()) {
      ItemUpdate.pr(
          "Warning: Delete_contents file for item " + itarch.getDirectoryName() + " not found.");
    } else {
      List<Integer> list = MetadataUtilities.readDeleteContentsFile(f);
      if (list.isEmpty()) {
        ItemUpdate.pr("Warning: empty delete_contents file for item " + itarch.getDirectoryName());
      } else {
        for (int id : list) {
          try {
            Bitstream bs = Bitstream.find(context, id);
            if (bs == null) {
              ItemUpdate.pr("Bitstream not found by id: " + id);
            } else {
              Bundle[] bundles = bs.getBundles();
              for (Bundle b : bundles) {
                if (isTest) {
                  ItemUpdate.pr("Delete bitstream with id = " + id);
                } else {
                  b.removeBitstream(bs);
                  ItemUpdate.pr("Deleted bitstream with id = " + id);
                }
              }

              if (alterProvenance) {
                DtoMetadata dtom = DtoMetadata.create("dc.description.provenance", "en", "");

                String append =
                    "Bitstream " + bs.getName() + " deleted on " + DCDate.getCurrent() + "; ";
                Item item = bundles[0].getItems()[0];
                ItemUpdate.pr("Append provenance with: " + append);

                if (!isTest) {
                  MetadataUtilities.appendMetadata(item, dtom, false, append);
                }
              }
            }
          } catch (SQLException e) {
            ItemUpdate.pr("Error finding bitstream from id: " + id + " : " + e.toString());
          }
        }
      }
    }
  }
  @GET
  @Path("/{bitstream_id}/retrieve")
  public javax.ws.rs.core.Response getFile(
      @PathParam("bitstream_id") final Integer bitstream_id,
      @QueryParam("userIP") String user_ip,
      @QueryParam("userAgent") String user_agent,
      @QueryParam("xforwarderfor") String xforwarderfor,
      @Context HttpHeaders headers,
      @Context HttpServletRequest request) {
    org.dspace.core.Context context = null;
    try {
      context = new org.dspace.core.Context();

      org.dspace.content.Bitstream bitstream =
          org.dspace.content.Bitstream.find(context, bitstream_id);
      if (AuthorizeManager.authorizeActionBoolean(
          context, bitstream, org.dspace.core.Constants.READ)) {
        if (writeStatistics) {
          writeStats(context, bitstream_id, user_ip, user_agent, xforwarderfor, headers, request);
        }

        return Response.ok(bitstream.retrieve()).type(bitstream.getFormat().getMIMEType()).build();
      } else {
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
      }

    } catch (IOException e) {
      log.error(e.getMessage());
      throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (SQLException e) {
      log.error(e.getMessage());
      throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    } catch (AuthorizeException e) {
      log.error(e.getMessage());
      throw new WebApplicationException(Response.Status.UNAUTHORIZED);
    } finally {
      if (context != null) {
        try {
          context.complete();
        } catch (SQLException e) {
          log.error(e.getMessage() + " occurred while trying to close");
        }
      }
    }
  }
  public Map act(
      Redirector redirector,
      SourceResolver resolver,
      Map objectModel,
      String source,
      Parameters parameters)
      throws Exception {
    Request request = ObjectModelHelper.getRequest(objectModel);

    String requesterName = request.getParameter("requesterName");
    String requesterEmail = request.getParameter("requesterEmail");
    String allFiles = request.getParameter("allFiles");
    String message = request.getParameter("message");
    String bitstreamId = request.getParameter("bitstreamId");

    // User email from context
    Context context = ContextUtil.obtainContext(objectModel);
    EPerson loggedin = context.getCurrentUser();
    String eperson = null;
    if (loggedin != null) {
      eperson = loggedin.getEmail();
    }

    // Check all data is there
    if (StringUtils.isEmpty(requesterName)
        || StringUtils.isEmpty(requesterEmail)
        || StringUtils.isEmpty(allFiles)
        || StringUtils.isEmpty(message)) {
      // Either the user did not fill out the form or this is the
      // first time they are visiting the page.
      Map<String, String> map = new HashMap<String, String>();
      map.put("bitstreamId", bitstreamId);

      if (StringUtils.isEmpty(requesterEmail)) {
        map.put("requesterEmail", eperson);
      } else {
        map.put("requesterEmail", requesterEmail);
      }
      map.put("requesterName", requesterName);
      map.put("allFiles", allFiles);
      map.put("message", message);
      return map;
    }
    DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    if (!(dso instanceof Item)) {
      throw new Exception("Invalid DspaceObject at ItemRequest.");
    }

    Item item = (Item) dso;
    String title = "";
    Metadatum[] titleDC = item.getDC("title", null, Item.ANY);
    if (titleDC == null || titleDC.length == 0) {
      titleDC = item.getDC("title", Item.ANY, Item.ANY); // dc.title with qualifier term
    }
    if (titleDC != null && titleDC.length > 0) {
      title = titleDC[0].value;
    }

    RequestItemAuthor requestItemAuthor =
        new DSpace()
            .getServiceManager()
            .getServiceByName(
                RequestItemAuthorExtractor.class.getName(), RequestItemAuthorExtractor.class)
            .getRequestItemAuthor(context, item);

    RequestItem requestItem =
        new RequestItem(
            item.getID(),
            Integer.parseInt(bitstreamId),
            requesterEmail,
            requesterName,
            message,
            Boolean.getBoolean(allFiles));

    // All data is there, send the email
    Email email =
        Email.getEmail(
            I18nUtil.getEmailFilename(context.getCurrentLocale(), "request_item.author"));
    email.addRecipient(requestItemAuthor.getEmail());

    email.addArgument(requesterName);
    email.addArgument(requesterEmail);
    email.addArgument(
        allFiles.equals("true")
            ? I18nUtil.getMessage("itemRequest.all")
            : Bitstream.find(context, Integer.parseInt(bitstreamId)).getName());
    email.addArgument(HandleManager.getCanonicalForm(item.getHandle()));
    email.addArgument(title); // request item title
    email.addArgument(message); // message
    email.addArgument(getLinkTokenEmail(context, requestItem));
    email.addArgument(requestItemAuthor.getFullName()); //   corresponding author name
    email.addArgument(requestItemAuthor.getEmail()); //   corresponding author email
    email.addArgument(ConfigurationManager.getProperty("dspace.name"));
    email.addArgument(ConfigurationManager.getProperty("mail.helpdesk"));

    email.setReplyTo(requesterEmail);

    email.send();
    // Finished, allow to pass.
    return null;
  }
Beispiel #6
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;
  }