private boolean allowedToMediate(Context context) {
    // get the configuration
    String mediatorCfg =
        ConfigurationManager.getProperty("swordv2-server", "on-behalf-of.update.mediators");
    if (mediatorCfg == null) {
      // if there's no explicit list of mediators, then anyone can mediate
      return true;
    }

    // get the email and netid of the mediator
    EPerson eperson = context.getCurrentUser();
    if (eperson == null) {
      return false;
    }
    String email = eperson.getEmail();
    String netid = eperson.getNetid();

    String[] mediators = mediatorCfg.split(",");
    for (String mediator : mediators) {
      String m = mediator.trim();
      if (email != null && m.equals(email.trim())) {
        return true;
      }
      if (netid != null && m.equals(netid.trim())) {
        return true;
      }
    }

    return false;
  }
Exemple #2
0
  /**
   * Claim-tasks action.
   *
   * @param redirector unused.
   * @param resolver unused.
   * @param objectModel Cocoon's object model.
   * @param source unused.
   * @param parameters unused.
   * @return null.
   * @throws java.lang.Exception passed through.
   */
  @Override
  public Map act(
      Redirector redirector,
      SourceResolver resolver,
      Map objectModel,
      String source,
      Parameters parameters)
      throws Exception {
    Request request = ObjectModelHelper.getRequest(objectModel);
    Context context = ContextUtil.obtainContext(objectModel);

    // Or the user selected a checkbox full of workflow IDs
    String[] workflowIDs = request.getParameterValues("workflowID");
    if (workflowIDs != null) {
      for (String workflowID : workflowIDs) {
        BasicWorkflowItem workflowItem =
            basicWorkflowItemService.find(context, Integer.valueOf(workflowID));

        int state = workflowItem.getState();
        // Only unclaim tasks that are already claimed.
        if (state == BasicWorkflowServiceImpl.WFSTATE_STEP1POOL
            || state == BasicWorkflowServiceImpl.WFSTATE_STEP2POOL
            || state == BasicWorkflowServiceImpl.WFSTATE_STEP3POOL) {
          basicWorkflowService.claim(context, workflowItem, context.getCurrentUser());
        }
      }
    }

    return null;
  }
 /*
  * Add authenticated users to the group defined in dspace.cfg by
  * the login.specialgroup key.
  */
 @Override
 public List<Group> getSpecialGroups(Context context, HttpServletRequest request) {
   // Prevents anonymous users from being added to this group, and the second check
   // ensures they are LDAP users
   try {
     if (!context.getCurrentUser().getNetid().equals("")) {
       String groupName =
           ConfigurationManager.getProperty("authentication-ldap", "login.specialgroup");
       if ((groupName != null) && (!groupName.trim().equals(""))) {
         Group ldapGroup = groupService.findByName(context, groupName);
         if (ldapGroup == null) {
           // Oops - the group isn't there.
           log.warn(
               LogManager.getHeader(
                   context,
                   "ldap_specialgroup",
                   "Group defined in login.specialgroup does not exist"));
           return ListUtils.EMPTY_LIST;
         } else {
           return Arrays.asList(ldapGroup);
         }
       }
     }
   } catch (Exception npe) {
     // The user is not an LDAP user, so we don't need to worry about them
   }
   return ListUtils.EMPTY_LIST;
 }
Exemple #4
0
  /**
   * Method to check current status of the service and logged in user.
   *
   * <p>okay: true | false authenticated: true | false epersonEMAIL: [email protected] epersonNAME:
   * John Doe
   *
   * @param headers Request header which contains the header named "rest-dspace-token" containing
   *     the token as value.
   * @return status the Status object with information about REST API
   * @throws UnsupportedEncodingException The Character Encoding is not supported.
   */
  @GET
  @Path("/status")
  @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Status status(@Context HttpHeaders headers) throws UnsupportedEncodingException {
    org.dspace.core.Context context = null;

    try {
      context = Resource.createContext();
      EPerson ePerson = context.getCurrentUser();

      if (ePerson != null) {
        // DB EPerson needed since token won't have full info, need context
        EPerson dbEPerson = epersonService.findByEmail(context, ePerson.getEmail());

        Status status = new Status(dbEPerson.getEmail(), dbEPerson.getFullName());
        return status;
      }
    } catch (ContextException e) {
      Resource.processException("Status context error: " + e.getMessage(), context);
    } catch (SQLException e) {
      Resource.processException("Status eperson db lookup error: " + e.getMessage(), context);
    } finally {
      context.abort();
    }

    // fallback status, unauth
    return new Status();
  }
Exemple #5
0
  /**
   * fast check to see if an eperson is a member called with eperson id, does database lookup
   * without instantiating all of the epeople objects and is thus a static method
   *
   * @param c context
   * @param groupid group ID to check
   */
  public static boolean isMember(Context c, int groupid) throws SQLException {
    // special, everyone is member of group 0 (anonymous)
    if (groupid == 0) {
      return true;
    }

    EPerson currentuser = c.getCurrentUser();

    return epersonInGroup(c, groupid, currentuser);
  }
  /*
   * Add authenticated users to the group defined in dspace.cfg by
   * the authentication-ldap.login.groupmap.* key.
   */
  private void assignGroups(String dn, String group, Context context) {
    if (StringUtils.isNotBlank(dn)) {
      System.out.println("dn:" + dn);
      int i = 1;
      String groupMap =
          ConfigurationManager.getProperty("authentication-ldap", "login.groupmap." + i);

      boolean cmp;

      while (groupMap != null) {
        String t[] = groupMap.split(":");
        String ldapSearchString = t[0];
        String dspaceGroupName = t[1];

        if (group == null) {
          cmp = StringUtils.containsIgnoreCase(dn, ldapSearchString + ",");
        } else {
          cmp = StringUtils.equalsIgnoreCase(group, ldapSearchString);
        }

        if (cmp) {
          // assign user to this group
          try {
            Group ldapGroup = groupService.findByName(context, dspaceGroupName);
            if (ldapGroup != null) {
              groupService.addMember(context, ldapGroup, context.getCurrentUser());
              groupService.update(context, ldapGroup);
            } else {
              // The group does not exist
              log.warn(
                  LogManager.getHeader(
                      context,
                      "ldap_assignGroupsBasedOnLdapDn",
                      "Group defined in authentication-ldap.login.groupmap."
                          + i
                          + " does not exist :: "
                          + dspaceGroupName));
            }
          } catch (AuthorizeException ae) {
            log.debug(
                LogManager.getHeader(
                    context,
                    "assignGroupsBasedOnLdapDn could not authorize addition to group",
                    dspaceGroupName));
          } catch (SQLException e) {
            log.debug(
                LogManager.getHeader(
                    context, "assignGroupsBasedOnLdapDn could not find group", dspaceGroupName));
          }
        }

        groupMap = ConfigurationManager.getProperty("authentication-ldap", "login.groupmap." + ++i);
      }
    }
  }
  /**
   * Check to see if the current user is a System Admin. Always return <code>true</code> if
   * c.ignoreAuthorization is set. Anonymous users can't be Admins (EPerson set to NULL)
   *
   * @param c current context
   * @return <code>true</code> if user is an admin or ignore authorization flag set
   */
  public static boolean isAdmin(Context c) throws SQLException {
    // if we're ignoring authorization, user is member of admin
    if (c.ignoreAuthorization()) {
      return true;
    }

    EPerson e = c.getCurrentUser();

    if (e == null) {
      return false; // anonymous users can't be admins....
    } else {
      return Group.isMember(c, 1);
    }
  }
Exemple #8
0
  /**
   * Send an alert to the designated "alert recipient" - that is, when a database error or internal
   * error occurs, this person is sent an e-mail with details.
   *
   * <p>The recipient is configured via the "alert.recipient" property in <code>dspace.cfg</code>.
   * If this property is omitted, no alerts are sent.
   *
   * <p>This method "swallows" any exception that might occur - it will just be logged. This is
   * because this method will usually be invoked as part of an error handling routine anyway.
   *
   * @param request the HTTP request leading to the error
   * @param exception the exception causing the error, or null
   */
  public static void sendAlert(HttpServletRequest request, Exception exception) {
    String logInfo = UIUtil.getRequestLogInfo(request);
    Context c = (Context) request.getAttribute("dspace.context");
    Locale locale = getSessionLocale(request);
    EPerson user = null;

    try {
      String recipient = ConfigurationManager.getProperty("alert.recipient");

      if (recipient != null) {
        Email email =
            ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, "internal_error"));
        email.addRecipient(recipient);
        email.addArgument(ConfigurationManager.getProperty("dspace.url"));
        email.addArgument(new Date());
        email.addArgument(request.getSession().getId());
        email.addArgument(logInfo);

        String stackTrace;

        if (exception != null) {
          StringWriter sw = new StringWriter();
          PrintWriter pw = new PrintWriter(sw);
          exception.printStackTrace(pw);
          pw.flush();
          stackTrace = sw.toString();
        } else {
          stackTrace = "No exception";
        }

        email.addArgument(stackTrace);
        try {
          user = c.getCurrentUser();
        } catch (Exception e) {
          log.warn("No context, the database might be down or the connection pool exhausted.");
        }

        if (user != null) {
          email.addArgument(user.getFullName() + " (" + user.getEmail() + ")");
        } else {
          email.addArgument("Anonymous");
        }
        email.addArgument(request.getRemoteAddr());
        email.send();
      }
    } catch (Exception e) {
      // Not much we can do here!
      log.warn("Unable to send email alert", e);
    }
  }
  protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // Process the POSTed email and password
    String netid = request.getParameter("login_netid");
    String password = request.getParameter("login_password");
    String jsp = null;

    // Locate the eperson
    int status = AuthenticationManager.authenticate(context, netid, password, null, request);

    if (status == AuthenticationMethod.SUCCESS) {
      // Logged in OK.
      Authenticate.loggedIn(context, request, context.getCurrentUser());

      // Set the Locale according to user preferences
      Locale epersonLocale = I18nUtil.getEPersonLocale(context.getCurrentUser());
      context.setCurrentLocale(epersonLocale);
      Config.set(request.getSession(), Config.FMT_LOCALE, epersonLocale);

      log.info(LogManager.getHeader(context, "login", "type=explicit"));

      // resume previous request
      Authenticate.resumeInterruptedRequest(request, response);

      return;
    } else if (status == AuthenticationMethod.CERT_REQUIRED) {
      jsp = "/error/require-certificate.jsp";
    } else {
      jsp = "/login/incorrect.jsp";
    }

    // If we reach here, supplied email/password was duff.
    log.info(
        LogManager.getHeader(
            context, "failed_login", "netid=" + netid + ", result=" + String.valueOf(status)));
    JSPManager.showJSP(request, response, jsp);
  }
Exemple #10
0
  /**
   * Check to see if the current user is an Administrator of a given object within DSpace. Always
   * return <code>true</code> if the user is a System Admin
   *
   * @param c current context
   * @param o current DSpace Object, if <code>null</code> the call will be equivalent to a call to
   *     the <code>isAdmin(Context c)</code> method
   * @return <code>true</code> if user has administrative privileges on the given DSpace object
   */
  public static boolean isAdmin(Context c, DSpaceObject o) throws SQLException {

    // return true if user is an Administrator
    if (isAdmin(c)) {
      return true;
    }

    if (o == null) {
      return false;
    }

    // is eperson set? if not, userid = 0 (anonymous)
    int userid = 0;
    EPerson e = c.getCurrentUser();
    if (e != null) {
      userid = e.getID();
    }

    //
    // First, check all Resource Policies directly on this object
    //
    List<ResourcePolicy> policies = getPoliciesActionFilter(c, o, Constants.ADMIN);

    for (ResourcePolicy rp : policies) {
      // check policies for date validity
      if (rp.isDateValid()) {
        if ((rp.getEPersonID() != -1) && (rp.getEPersonID() == userid)) {
          return true; // match
        }

        if ((rp.getGroupID() != -1) && (Group.isMember(c, rp.getGroupID()))) {
          // group was set, and eperson is a member
          // of that group
          return true;
        }
      }
    }

    // If user doesn't have specific Admin permissions on this object,
    // check the *parent* objects of this object.  This allows Admin
    // permissions to be inherited automatically (e.g. Admin on Community
    // is also an Admin of all Collections/Items in that Community)
    DSpaceObject parent = o.getParentObject();
    if (parent != null) {
      return isAdmin(c, parent);
    }

    return false;
  }
Exemple #11
0
  /**
   * Find collection from DSpace database. It is encapsulation of method
   * org.dspace.content.Collection.find with checking if item exist and if user logged into context
   * has permission to do passed action.
   *
   * @param context Context of actual logged user.
   * @param id Id of collection in DSpace.
   * @param action Constant from org.dspace.core.Constants.
   * @return It returns DSpace collection.
   * @throws WebApplicationException Is thrown when item with passed id is not exists and if user
   *     has no permission to do passed action.
   */
  private org.dspace.content.Collection findCollection(
      org.dspace.core.Context context, int id, int action) throws WebApplicationException {
    org.dspace.content.Collection collection = null;
    try {
      collection = org.dspace.content.Collection.find(context, id);

      if (collection == null) {
        context.abort();
        log.warn("Collection(id=" + id + ") was not found!");
        throw new WebApplicationException(Response.Status.NOT_FOUND);
      } else if (!AuthorizeManager.authorizeActionBoolean(context, collection, action)) {
        context.abort();
        if (context.getCurrentUser() != null) {
          log.error(
              "User("
                  + context.getCurrentUser().getEmail()
                  + ") has not permission to "
                  + getActionString(action)
                  + " collection!");
        } else {
          log.error(
              "User(anonymous) has not permission to " + getActionString(action) + " collection!");
        }
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
      }

    } catch (SQLException e) {
      processException(
          "Something get wrong while finding collection(id="
              + id
              + "). SQLException, Message: "
              + e,
          context);
    }
    return collection;
  }
  public boolean isCollectionAdmin(Context c) throws SQLException {
    EPerson e = c.getCurrentUser();

    if (e != null) {
      List<ResourcePolicy> policies =
          resourcePolicyService.find(
              c, e, groupService.allMemberGroups(c, e), Constants.ADMIN, Constants.COLLECTION);

      if (CollectionUtils.isNotEmpty(policies)) {
        return true;
      }
    }

    return false;
  }
  /**
   * Stop the DSpace workflow, and return the item to the user workspace
   *
   * @param item
   * @throws DSpaceSwordException
   */
  public void stopWorkflow(Context context, Item item) throws DSpaceSwordException {
    try {
      // find the item in the workflow if it exists
      WorkflowItem wfi = this.getWorkflowItem(context, item);

      // abort the workflow
      if (wfi != null) {
        WorkflowManager.abort(context, wfi, context.getCurrentUser());
      }
    } catch (SQLException e) {
      throw new DSpaceSwordException(e);
    } catch (AuthorizeException e) {
      throw new DSpaceSwordException(e);
    } catch (IOException e) {
      throw new DSpaceSwordException(e);
    }
  }
  @Override
  public boolean isAdmin(Context c, DSpaceObject o) throws SQLException {

    // return true if user is an Administrator
    if (isAdmin(c)) {
      return true;
    }

    if (o == null) {
      return false;
    }

    //
    // First, check all Resource Policies directly on this object
    //
    List<ResourcePolicy> policies = getPoliciesActionFilter(c, o, Constants.ADMIN);

    for (ResourcePolicy rp : policies) {
      // check policies for date validity
      if (resourcePolicyService.isDateValid(rp)) {
        if (rp.getEPerson() != null && rp.getEPerson().equals(c.getCurrentUser())) {
          return true; // match
        }

        if ((rp.getGroup() != null) && (groupService.isMember(c, rp.getGroup()))) {
          // group was set, and eperson is a member
          // of that group
          return true;
        }
      }
    }

    // If user doesn't have specific Admin permissions on this object,
    // check the *parent* objects of this object.  This allows Admin
    // permissions to be inherited automatically (e.g. Admin on Community
    // is also an Admin of all Collections/Items in that Community)
    DSpaceObject parent = serviceFactory.getDSpaceObjectService(o).getParentObject(c, o);
    if (parent != null) {
      return isAdmin(c, parent);
    }

    return false;
  }
  /**
   * Handles the model processing required for the submissions page. - Workflow tasks owned by user
   * - Workflow tasks available in pool - Unfinished submissions - Archived submissions
   *
   * <p>TODO: Need to perform auth check
   */
  @RequestMapping("/submissions/**")
  protected String displaySubmissions(
      @RequestAttribute Context context, ModelMap model, HttpServletRequest request)
      throws Exception {
    List<WorkflowItem> ownedItems =
        WorkflowManager.getOwnedTasks(context, context.getCurrentUser());
    model.addAttribute("ownedItems", ownedItems);

    List<WorkflowItem> pooledItems =
        WorkflowManager.getPooledTasks(context, context.getCurrentUser());
    model.addAttribute("pooledItems", pooledItems);

    WorkspaceItem[] unfinishedItems =
        WorkspaceItem.findByEPerson(context, context.getCurrentUser());
    model.addAttribute("unfinishedItems", unfinishedItems);

    SupervisedItem[] supervisedItems =
        SupervisedItem.findbyEPerson(context, context.getCurrentUser());
    model.addAttribute("supervisedItems", supervisedItems);

    WorkflowItem[] inprogressItems = WorkflowItem.findByEPerson(context, context.getCurrentUser());
    model.addAttribute("inprogressItems", inprogressItems);

    ItemIterator submittedItemsIterator = Item.findBySubmitter(context, context.getCurrentUser());
    // Converting ItemIterator into something easier to digest
    List<Item> submittedItems = new LinkedList<Item>();
    try {
      while (submittedItemsIterator.hasNext()) {
        submittedItems.add(submittedItemsIterator.next());
      }
    } finally {
      if (submittedItemsIterator != null) {
        submittedItemsIterator.close();
      }
    }
    model.addAttribute("submittedItems", submittedItems);

    return "pages/submissions";
  }
  /**
   * Show a collection home page, or deal with button press on home page
   *
   * @param context Context object
   * @param request the HTTP request
   * @param response the HTTP response
   * @param community the community
   * @param collection the collection
   */
  private void collectionHome(
      Context context,
      HttpServletRequest request,
      HttpServletResponse response,
      Community community,
      Collection collection)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // Handle click on a browse or search button
    if (!handleButton(request, response, IdentifierService.getURL(community))) {
      // Will need to know whether to commit to DB
      boolean updated = false;

      // No search or browse button pressed, check for
      if (request.getParameter("submit_subscribe") != null) {
        // Subscribe button pressed.
        // Only registered can subscribe, so redirect unless logged in.
        if (context.getCurrentUser() == null
            && !Authenticate.startAuthentication(context, request, response)) return;
        else {
          SubscriptionManager.subscribe(context, context.getCurrentUser(), collection);
          updated = true;
        }
      } else if (request.getParameter("submit_unsubscribe") != null) {
        SubscriptionManager.unsubscribe(context, context.getCurrentUser(), collection);
        updated = true;
      }

      // display collection home page
      log.info(
          LogManager.getHeader(context, "view_collection", "collection_id=" + collection.getID()));

      // perform any necessary pre-processing
      preProcessCollectionHome(context, request, response, collection);

      // Is the user logged in/subscribed?
      EPerson e = context.getCurrentUser();
      boolean subscribed = false;

      if (e != null) {
        subscribed = SubscriptionManager.isSubscribed(context, e, collection);

        // is the user a COLLECTION_EDITOR?
        //                if (collection.canEditBoolean())
        if (AuthorizeManager.canEdit(collection, context)) {
          // set a variable to create an edit button
          request.setAttribute("editor_button", new Boolean(true));
        }

        // can they admin this collection?
        if (AuthorizeManager.authorizeActionBoolean(
            context, collection, Constants.COLLECTION_ADMIN)) {
          request.setAttribute("admin_button", new Boolean(true));

          // give them a button to manage submitter list
          // what group is the submitter?
          Group group = collection.getSubmitters();

          if (group != null) {
            request.setAttribute("submitters", group);
          }
        }

        // can they submit to this collection?
        if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.ADD)) {
          request.setAttribute("can_submit_button", new Boolean(true));

        } else {
          request.setAttribute("can_submit_button", new Boolean(false));
        }
      }

      // Forward to collection home page
      request.setAttribute("collection", collection);
      request.setAttribute("community", community);
      request.setAttribute("logged.in", new Boolean(e != null));
      request.setAttribute("subscribed", new Boolean(subscribed));
      JSPManager.showJSP(request, response, "/collection-home.jsp");

      if (updated) {
        context.complete();
      }
    }
  }
  /**
   * Show an item page
   *
   * @param context Context object
   * @param request the HTTP request
   * @param response the HTTP response
   * @param item the item
   * @param identifier a persistent identifier that belongs to the item
   */
  private void displayItem(
      Context context, HttpServletRequest request, HttpServletResponse response, Item item)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // Tombstone?
    if (item.isWithdrawn()) {
      JSPManager.showJSP(request, response, "/tombstone.jsp");

      return;
    }

    // Ensure the user has authorisation
    AuthorizeManager.authorizeAction(context, item, Constants.READ);

    log.info(
        LogManager.getHeader(
            context, "view_item", "uri=" + item.getIdentifier().getCanonicalForm()));

    // show edit link
    if (item.canEdit()) {
      // set a variable to create an edit button
      request.setAttribute("admin_button", new Boolean(true));
    }

    // Get the collections
    Collection[] collections = (Collection[]) item.getCollections().toArray();

    // For the breadcrumbs, get the first collection and the first community
    // that is in. FIXME: Not multiple-inclusion friendly--should be
    // smarter, context-sensitive
    request.setAttribute("dspace.collection", item.getOwningCollection());

    Collection collection = item.getOwningCollection();
    if (collection != null) {
      Community[] comms = (Community[]) collection.getCommunities().toArray();
      if (comms.length > 0) {
        request.setAttribute("dspace.community", comms[0]);

        /*
         * Find all the "parent" communities for the collection
         */
        request.setAttribute("dspace.communities", getParents(comms[0], true));
      }
    }

    // Full or simple display?
    boolean displayAll = false;
    String modeParam = request.getParameter("mode");

    if ((modeParam != null) && modeParam.equalsIgnoreCase("full")) {
      displayAll = true;
    }

    // Enable suggest link or not
    boolean suggestEnable = false;
    if (!ConfigurationManager.getBooleanProperty("webui.suggest.enable")) {
      // do nothing, the suggestLink is allready set to false
    } else {
      // it is in general enabled
      suggestEnable = true;

      // check for the enable only for logged in users option
      if (!ConfigurationManager.getBooleanProperty("webui.suggest.loggedinusers.only")) {
        // do nothing, the suggestLink stays as it is
      } else {
        // check whether there is a logged in user
        suggestEnable = (context.getCurrentUser() == null ? false : true);
      }
    }

    // Set attributes and display
    request.setAttribute("suggest.enable", new Boolean(suggestEnable));
    request.setAttribute("display.all", new Boolean(displayAll));
    request.setAttribute("item", item);
    request.setAttribute("collections", collections);
    JSPManager.showJSP(request, response, "/display-item.jsp");
  }
 @Override
 public List<Community> findAuthorizedGroupMapped(Context context, List<Integer> actions)
     throws SQLException {
   return communityDAO.findAuthorizedByGroup(context, context.getCurrentUser(), actions);
 }
Exemple #19
0
  /**
   * Checks that the context's current user can perform the given action on the given object. Throws
   * an exception if the user is not authorized, otherwise the method call does nothing.
   *
   * @param c context
   * @param o a DSpaceObject
   * @param useInheritance flag to say if ADMIN action on the current object or parent object can be
   *     used
   * @param action action to perform from <code>org.dspace.core.Constants</code>
   * @throws AuthorizeException if the user is denied
   */
  public static void authorizeAction(Context c, DSpaceObject o, int action, boolean useInheritance)
      throws AuthorizeException, SQLException {
    if (o == null) {
      // action can be -1 due to a null entry
      String actionText;

      if (action == -1) {
        actionText = "null";
      } else {
        actionText = Constants.actionText[action];
      }

      EPerson e = c.getCurrentUser();
      int userid;

      if (e == null) {
        userid = 0;
      } else {
        userid = e.getID();
      }

      throw new AuthorizeException(
          "Authorization attempted on null DSpace object " + actionText + " by user " + userid);
    }

    if (!authorize(c, o, action, c.getCurrentUser(), useInheritance)) {
      // denied, assemble and throw exception
      int otype = o.getType();
      int oid = o.getID();
      int userid;
      EPerson e = c.getCurrentUser();

      if (e == null) {
        userid = 0;
      } else {
        userid = e.getID();
      }

      //            AuthorizeException j = new AuthorizeException("Denied");
      //            j.printStackTrace();
      // action can be -1 due to a null entry
      String actionText;

      if (action == -1) {
        actionText = "null";
      } else {
        actionText = Constants.actionText[action];
      }

      throw new AuthorizeException(
          "Authorization denied for action "
              + actionText
              + " on "
              + Constants.typeText[otype]
              + ":"
              + oid
              + " by user "
              + userid,
          o,
          action);
    }
  }
  // returns true if archived
  protected boolean doState(
      Context context, BasicWorkflowItem workflowItem, int newstate, EPerson newowner)
      throws SQLException, IOException, AuthorizeException {
    Collection mycollection = workflowItem.getCollection();
    Group mygroup = null;
    boolean archived = false;

    // Gather our old data for launching the workflow event
    int oldState = workflowItem.getState();

    workflowItem.setState(newstate);

    switch (newstate) {
      case WFSTATE_STEP1POOL:

        // any reviewers?
        // if so, add them to the tasklist
        workflowItem.setOwner(null);

        // get reviewers (group 1 )
        mygroup = collectionService.getWorkflowGroup(mycollection, 1);

        if ((mygroup != null) && !(groupService.isEmpty(mygroup))) {
          // get a list of all epeople in group (or any subgroups)
          List<EPerson> epa = groupService.allMembers(context, mygroup);

          // there were reviewers, change the state
          //  and add them to the list
          createTasks(context, workflowItem, epa);
          workflowItemService.update(context, workflowItem);

          // email notification
          notifyGroupOfTask(context, workflowItem, mygroup, epa);
        } else {
          // no reviewers, skip ahead
          workflowItem.setState(WFSTATE_STEP1);
          archived = advance(context, workflowItem, null, true, false);
        }

        break;

      case WFSTATE_STEP1:

        // remove reviewers from tasklist
        // assign owner
        taskListItemService.deleteByWorkflowItem(context, workflowItem);
        workflowItem.setOwner(newowner);

        break;

      case WFSTATE_STEP2POOL:

        // clear owner
        // any approvers?
        // if so, add them to tasklist
        // if not, skip to next state
        workflowItem.setOwner(null);

        // get approvers (group 2)
        mygroup = collectionService.getWorkflowGroup(mycollection, 2);

        if ((mygroup != null) && !(groupService.isEmpty(mygroup))) {
          // get a list of all epeople in group (or any subgroups)
          List<EPerson> epa = groupService.allMembers(context, mygroup);

          // there were approvers, change the state
          //  timestamp, and add them to the list
          createTasks(context, workflowItem, epa);

          // email notification
          notifyGroupOfTask(context, workflowItem, mygroup, epa);
        } else {
          // no reviewers, skip ahead
          workflowItem.setState(WFSTATE_STEP2);
          archived = advance(context, workflowItem, null, true, false);
        }

        break;

      case WFSTATE_STEP2:

        // remove admins from tasklist
        // assign owner
        taskListItemService.deleteByWorkflowItem(context, workflowItem);
        workflowItem.setOwner(newowner);

        break;

      case WFSTATE_STEP3POOL:

        // any editors?
        // if so, add them to tasklist
        workflowItem.setOwner(null);
        mygroup = collectionService.getWorkflowGroup(mycollection, 3);

        if ((mygroup != null) && !(groupService.isEmpty(mygroup))) {
          // get a list of all epeople in group (or any subgroups)
          List<EPerson> epa = groupService.allMembers(context, mygroup);

          // there were editors, change the state
          //  timestamp, and add them to the list
          createTasks(context, workflowItem, epa);

          // email notification
          notifyGroupOfTask(context, workflowItem, mygroup, epa);
        } else {
          // no editors, skip ahead
          workflowItem.setState(WFSTATE_STEP3);
          archived = advance(context, workflowItem, null, true, false);
        }

        break;

      case WFSTATE_STEP3:

        // remove editors from tasklist
        // assign owner
        taskListItemService.deleteByWorkflowItem(context, workflowItem);
        workflowItem.setOwner(newowner);

        break;

      case WFSTATE_ARCHIVE:

        // put in archive in one transaction
        // remove workflow tasks
        taskListItemService.deleteByWorkflowItem(context, workflowItem);

        mycollection = workflowItem.getCollection();

        Item myitem = archive(context, workflowItem);

        // now email notification
        notifyOfArchive(context, myitem, mycollection);
        archived = true;

        break;
    }

    logWorkflowEvent(
        context,
        workflowItem.getItem(),
        workflowItem,
        context.getCurrentUser(),
        newstate,
        newowner,
        mycollection,
        oldState,
        mygroup);

    if (!archived) {
      workflowItemService.update(context, workflowItem);
    }

    return archived;
  }
Exemple #21
0
  /**
   * get Set of Integers all of the group memberships for an eperson
   *
   * @param c
   * @param e
   * @return Set of Integer groupIDs
   * @throws SQLException
   */
  public static Set<Integer> allMemberGroupIDs(Context c, EPerson e) throws SQLException {
    Set<Integer> groupIDs = new HashSet<Integer>();

    if (e != null) {
      // two queries - first to get groups eperson is a member of
      // second query gets parent groups for groups eperson is a member of

      TableRowIterator tri =
          DatabaseManager.queryTable(
              c,
              "epersongroup2eperson",
              "SELECT * FROM epersongroup2eperson WHERE eperson_id= ?",
              e.getID());

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

          int childID = row.getIntColumn("eperson_group_id");

          groupIDs.add(Integer.valueOf(childID));
        }
      } finally {
        // close the TableRowIterator to free up resources
        if (tri != null) {
          tri.close();
        }
      }
    }
    // Also need to get all "Special Groups" user is a member of!
    // Otherwise, you're ignoring the user's membership to these groups!
    // However, we only do this is we are looking up the special groups
    // of the current user, as we cannot look up the special groups
    // of a user who is not logged in.
    if ((c.getCurrentUser() == null)
        || (((c.getCurrentUser() != null) && (c.getCurrentUser().getID() == e.getID())))) {
      Group[] specialGroups = c.getSpecialGroups();
      for (Group special : specialGroups) {
        groupIDs.add(Integer.valueOf(special.getID()));
      }
    }

    // all the users are members of the anonymous group
    groupIDs.add(Integer.valueOf(0));

    // now we have all owning groups, also grab all parents of owning groups
    // yes, I know this could have been done as one big query and a union,
    // but doing the Oracle port taught me to keep to simple SQL!

    StringBuilder groupQuery = new StringBuilder();
    groupQuery.append("SELECT * FROM group2groupcache WHERE ");

    Iterator<Integer> i = groupIDs.iterator();

    // Build a list of query parameters
    Object[] parameters = new Object[groupIDs.size()];
    int idx = 0;
    while (i.hasNext()) {
      int groupID = (i.next()).intValue();

      parameters[idx++] = Integer.valueOf(groupID);

      groupQuery.append("child_id= ? ");
      if (i.hasNext()) {
        groupQuery.append(" OR ");
      }
    }

    // was member of at least one group
    // NOTE: even through the query is built dynamically, all data is
    // separated into the parameters array.
    TableRowIterator tri =
        DatabaseManager.queryTable(c, "group2groupcache", groupQuery.toString(), parameters);

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

        int parentID = row.getIntColumn("parent_id");

        groupIDs.add(Integer.valueOf(parentID));
      }
    } finally {
      // close the TableRowIterator to free up resources
      if (tri != null) {
        tri.close();
      }
    }

    return groupIDs;
  }
  @Override
  protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    Item item = null;
    Bitstream bitstream = null;

    // Get the ID from the URL
    String idString = request.getPathInfo();
    String handle = "";
    String sequenceText = "";
    String filename = null;
    int sequenceID;

    // Parse 'handle' and 'sequence' (bitstream seq. number) out
    // of remaining URL path, which is typically of the format:
    // {handle}/{sequence}/{bitstream-name}
    // But since the bitstream name MAY have any number of "/"s in
    // it, and the handle is guaranteed to have one slash, we
    // scan from the start to pick out handle and sequence:

    // Remove leading slash if any:
    if (idString.startsWith("/")) {
      idString = idString.substring(1);
    }

    // skip first slash within handle
    int slashIndex = idString.indexOf('/');
    if (slashIndex != -1) {
      slashIndex = idString.indexOf('/', slashIndex + 1);
      if (slashIndex != -1) {
        handle = idString.substring(0, slashIndex);
        int slash2 = idString.indexOf('/', slashIndex + 1);
        if (slash2 != -1) {
          sequenceText = idString.substring(slashIndex + 1, slash2);
          filename = idString.substring(slash2 + 1);
        }
      }
    }

    try {
      sequenceID = Integer.parseInt(sequenceText);
    } catch (NumberFormatException nfe) {
      sequenceID = -1;
    }

    // Now try and retrieve the item
    DSpaceObject dso = HandleManager.resolveToObject(context, handle);

    // Make sure we have valid item and sequence number
    if (dso != null && dso.getType() == Constants.ITEM && sequenceID >= 0) {
      item = (Item) dso;

      if (item.isWithdrawn()) {
        log.info(
            LogManager.getHeader(
                context, "view_bitstream", "handle=" + handle + ",withdrawn=true"));
        JSPManager.showJSP(request, response, "/tombstone.jsp");
        return;
      }

      boolean found = false;

      Bundle[] bundles = item.getBundles();

      for (int i = 0; (i < bundles.length) && !found; i++) {
        Bitstream[] bitstreams = bundles[i].getBitstreams();

        for (int k = 0; (k < bitstreams.length) && !found; k++) {
          if (sequenceID == bitstreams[k].getSequenceID()) {
            bitstream = bitstreams[k];
            found = true;
          }
        }
      }
    }

    if (bitstream == null || filename == null || !filename.equals(bitstream.getName())) {
      // No bitstream found or filename was wrong -- ID invalid
      log.info(LogManager.getHeader(context, "invalid_id", "path=" + idString));
      JSPManager.showInvalidIDError(request, response, idString, Constants.BITSTREAM);

      return;
    }

    log.info(LogManager.getHeader(context, "view_bitstream", "bitstream_id=" + bitstream.getID()));

    // Modification date
    // Only use last-modified if this is an anonymous access
    // - caching content that may be generated under authorisation
    //   is a security problem
    if (context.getCurrentUser() == null) {
      // TODO: Currently the date of the item, since we don't have dates
      // for files
      response.setDateHeader("Last-Modified", item.getLastModified().getTime());

      // Check for if-modified-since header
      long modSince = request.getDateHeader("If-Modified-Since");

      if (modSince != -1 && item.getLastModified().getTime() < modSince) {
        // Item has not been modified since requested date,
        // hence bitstream has not; return 304
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
      }
    }

    // Pipe the bits
    InputStream is = bitstream.retrieve();

    // Set the response MIME type
    response.setContentType(bitstream.getFormat().getMIMEType());

    // Response length
    response.setHeader("Content-Length", String.valueOf(bitstream.getSize()));

    if (threshold != -1 && bitstream.getSize() >= threshold) {
      setBitstreamDisposition(bitstream.getName(), request, response);
    }

    Utils.bufferedCopy(is, response.getOutputStream());
    is.close();
    response.getOutputStream().flush();
  }
  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;
  }
  protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    ExternalIdentifierDAO identifierDAO = ExternalIdentifierDAOFactory.getInstance(context);

    // Obtain information from request
    String uri = request.getParameter("uri");
    ExternalIdentifier identifier = identifierDAO.retrieve(uri);
    ObjectIdentifier oi = identifier.getObjectIdentifier();

    // Lookup Item title & collection
    Item item = null;
    String link = "";
    String title = null;
    String collName = null;
    if (identifier != null) {
      item = (Item) oi.getObject(context);
      link = item.getIdentifier().getURL().toString();
      request.setAttribute("link", link);

      if (item != null) {
        DCValue[] titleDC = item.getDC("title", null, Item.ANY);
        if (titleDC != null || titleDC.length > 0) {
          title = titleDC[0].value;
        }
        Collection[] colls = item.getCollections();
        collName = colls[0].getMetadata("name");
      }
    } else {
      String path = request.getPathInfo();
      log.info(LogManager.getHeader(context, "invalid_id", "path=" + path));
      JSPManager.showInvalidIDError(request, response, path, -1);
      return;
    }
    if (title == null) {
      title = "";
    }
    if (collName == null) {
      collName = "";
    }
    request.setAttribute("suggest.title", title);

    // User email from context
    EPerson currentUser = context.getCurrentUser();
    String authEmail = null;
    String userName = null;

    if (currentUser != null) {
      authEmail = currentUser.getEmail();
      userName = currentUser.getFullName();
    }

    if (request.getParameter("submit") != null) {
      String recipAddr = request.getParameter("recip_email");
      // the only required field is recipient email address
      if (recipAddr == null || recipAddr.equals("")) {
        log.info(LogManager.getHeader(context, "show_suggest_form", "problem=true"));
        request.setAttribute("suggest.problem", new Boolean(true));
        JSPManager.showJSP(request, response, "/suggest/suggest.jsp");
        return;
      }
      String recipName = request.getParameter("recip_name");
      if (recipName == null || "".equals(recipName)) {
        try {
          recipName =
              I18nUtil.getMessage("org.dspace.app.webui.servlet.SuggestServlet.recipient", context);
        } catch (MissingResourceException e) {
          log.warn(
              LogManager.getHeader(
                  context,
                  "show_suggest_form",
                  "Missing Resource: org.dspace.app.webui.servlet.SuggestServlet.sender"));
          recipName = "colleague";
        }
      }
      String senderName = request.getParameter("sender_name");
      if (senderName == null || "".equals(senderName)) {
        // use userName if available
        if (userName != null) {
          senderName = userName;
        } else {
          try {
            senderName =
                I18nUtil.getMessage("org.dspace.app.webui.servlet.SuggestServlet.sender", context);
          } catch (MissingResourceException e) {
            log.warn(
                LogManager.getHeader(
                    context,
                    "show_suggest_form",
                    "Missing Resource: org.dspace.app.webui.servlet.SuggestServlet.sender"));
            senderName = "A DSpace User";
          }
        }
      }
      String senderAddr = request.getParameter("sender_email");
      if (senderAddr == null || "".equals(senderAddr)) {
        // use authEmail if available
        if (authEmail != null) {
          senderAddr = authEmail;
        }
      }
      String itemUri = identifier.getURI().toString();
      String message = request.getParameter("message");
      String siteName = ConfigurationManager.getProperty("dspace.name");

      // All data is there, send the email
      try {
        Email email =
            ConfigurationManager.getEmail(
                I18nUtil.getEmailFilename(context.getCurrentLocale(), "suggest"));
        email.addRecipient(recipAddr); // recipient address
        email.addArgument(recipName); // 1st arg - recipient name
        email.addArgument(senderName); // 2nd arg - sender name
        email.addArgument(siteName); // 3rd arg - repository name
        email.addArgument(title); // 4th arg - item title
        email.addArgument(itemUri); // 5th arg - item identifier URI
        email.addArgument(link); // 6th arg - item local URL
        email.addArgument(collName); // 7th arg - collection name
        email.addArgument(message); // 8th arg - user comments

        // Set sender's address as 'reply-to' address if supplied
        if (senderAddr != null && !"".equals(senderAddr)) {
          email.setReplyTo(senderAddr);
        }

        // Only actually send the email if feature is enabled
        if (ConfigurationManager.getBooleanProperty("webui.suggest.enable", false)) {
          email.send();
        } else {
          throw new MessagingException(
              "Suggest item email not sent - webui.suggest.enable = false");
        }

        log.info(LogManager.getHeader(context, "sent_suggest", "from=" + senderAddr));

        JSPManager.showJSP(request, response, "/suggest/suggest_ok.jsp");
      } catch (MessagingException me) {
        log.warn(LogManager.getHeader(context, "error_mailing_suggest", ""), me);
        JSPManager.showInternalError(request, response);
      }
    } else {
      // Display suggest form
      log.info(LogManager.getHeader(context, "show_suggest_form", "problem=false"));
      request.setAttribute("authenticated.email", authEmail);
      request.setAttribute("eperson.name", userName);
      JSPManager.showJSP(request, response, "/suggest/suggest.jsp"); // asd
    }
  }
  /**
   * Authenticate the given username/password pair, in conjunction with the onBehalfOf user. The
   * rules are that the username/password pair must successfully authenticate the user, and the
   * onBehalfOf user must exist in the user database.
   *
   * @param context
   * @param auth
   * @return a SWORD context holding the various user information
   * @throws SwordAuthException
   * @throws SwordError
   * @throws DSpaceSwordException
   */
  private SwordContext authenticate(Context context, AuthCredentials auth)
      throws SwordAuthException, SwordError, DSpaceSwordException {
    String obo = auth.getOnBehalfOf();
    String un = auth.getUsername();
    String pw = auth.getPassword();

    // smooth out the OnBehalfOf request, so that empty strings are
    // treated as null
    if ("".equals(obo)) {
      obo = null;
    }

    // first find out if we support on-behalf-of deposit
    boolean mediated =
        ConfigurationManager.getBooleanProperty("swordv2-server", "on-behalf-of.enable");
    if (!mediated && obo != null) {
      // user is trying to do a mediated deposit on a repository which does not support it
      log.error("Attempted mediated deposit on service not configured to do so");
      throw new SwordError(
          UriRegistry.ERROR_MEDIATION_NOT_ALLOWED,
          "Mediated deposit to this service is not permitted");
    }

    log.info(
        LogManager.getHeader(
            context, "sword_authenticate", "username="******",on_behalf_of=" + obo));

    try {
      // attempt to authenticate the primary user
      SwordContext sc = new SwordContext();
      EPerson ep = null;
      boolean authenticated = false;
      if (this.authenticates(context, un, pw)) {
        // if authenticated, obtain the eperson object
        ep = context.getCurrentUser();

        if (ep != null) {
          authenticated = true;
          sc.setAuthenticated(ep);
          // Set any special groups - invoke the authentication mgr.
          int[] groupIDs = AuthenticationManager.getSpecialGroups(context, null);

          for (int i = 0; i < groupIDs.length; i++) {
            context.setSpecialGroup(groupIDs[i]);
            log.debug("Adding Special Group id=" + String.valueOf(groupIDs[i]));
          }

          sc.setAuthenticatorContext(context);
          sc.setContext(context);
        }

        // if there is an onBehalfOfuser, then find their eperson
        // record, and if it exists set it.  If not, then the
        // authentication process fails
        EPerson epObo = null;
        if (obo != null) {
          epObo = EPerson.findByEmail(context, obo);
          if (epObo == null) {
            epObo = EPerson.findByNetid(context, obo);
          }

          if (epObo != null) {
            sc.setOnBehalfOf(epObo);
            Context oboContext = this.constructContext();
            oboContext.setCurrentUser(epObo);
            // Set any special groups - invoke the authentication mgr.
            int[] groupIDs = AuthenticationManager.getSpecialGroups(oboContext, null);

            for (int i = 0; i < groupIDs.length; i++) {
              oboContext.setSpecialGroup(groupIDs[i]);
              log.debug("Adding Special Group id=" + String.valueOf(groupIDs[i]));
            }
            sc.setContext(oboContext);
          } else {
            authenticated = false;
            throw new SwordError(
                UriRegistry.ERROR_TARGET_OWNER_UNKNOWN,
                "unable to identify on-behalf-of user: "******"sword_unable_to_set_user", "username="******"Unable to authenticate with the supplied credentials");
        } else {
          // FIXME: this shouldn't ever happen now, but may as well leave it in just in case
          // there's a bug elsewhere
          log.info(
              LogManager.getHeader(
                  context,
                  "sword_unable_to_set_on_behalf_of",
                  "username="******",on_behalf_of=" + obo));
          throw new SwordAuthException("Unable to authenticate the onBehalfOf account");
        }
      }

      return sc;
    } catch (SQLException e) {
      log.error("caught exception: ", e);
      throw new DSpaceSwordException(
          "There was a problem accessing the repository user database", e);
    } catch (AuthorizeException e) {
      log.error("caught exception: ", e);
      throw new SwordAuthException("There was a problem authenticating or authorising the user", e);
    }
  }
 @Override
 public void authorizeAction(Context c, DSpaceObject o, int action, boolean useInheritance)
     throws AuthorizeException, SQLException {
   authorizeAction(c, c.getCurrentUser(), o, action, useInheritance);
 }
Exemple #27
0
  /**
   * Delete item in collection.
   *
   * @param collectionId Id of collection which will be deleted.
   * @param itemId Id of item in colletion.
   * @return It returns status code: OK(200). NOT_FOUND(404) if item or collection was not found,
   *     UNAUTHORIZED(401) if user is not allowed to delete item or permission to write into
   *     collection.
   * @throws WebApplicationException It can be thrown by: SQLException, when was problem with
   *     database reading or writting. AuthorizeException, when was problem with authorization to
   *     item or collection. IOException, when was problem with removing item. ContextException,
   *     when was problem with creating context of DSpace.
   */
  @DELETE
  @Path("/{collection_id}/items/{item_id}")
  @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response deleteCollectionItem(
      @PathParam("collection_id") Integer collectionId,
      @PathParam("item_id") Integer itemId,
      @QueryParam("userIP") String user_ip,
      @QueryParam("userAgent") String user_agent,
      @QueryParam("xforwarderfor") String xforwarderfor,
      @Context HttpHeaders headers,
      @Context HttpServletRequest request)
      throws WebApplicationException {

    log.info("Delete item(id=" + itemId + ") in collection(id=" + collectionId + ").");
    org.dspace.core.Context context = null;

    try {
      context = createContext(getUser(headers));
      org.dspace.content.Collection dspaceCollection =
          findCollection(context, collectionId, org.dspace.core.Constants.WRITE);

      org.dspace.content.Item item = null;
      org.dspace.content.ItemIterator dspaceItems = dspaceCollection.getItems();
      while (dspaceItems.hasNext()) {
        org.dspace.content.Item dspaceItem = dspaceItems.next();
        if (dspaceItem.getID() == itemId) {
          item = dspaceItem;
        }
      }

      if (item == null) {
        context.abort();
        log.warn("Item(id=" + itemId + ") was not found!");
        throw new WebApplicationException(Response.Status.NOT_FOUND);
      } else if (!AuthorizeManager.authorizeActionBoolean(
          context, item, org.dspace.core.Constants.REMOVE)) {
        context.abort();
        if (context.getCurrentUser() != null) {
          log.error(
              "User("
                  + context.getCurrentUser().getEmail()
                  + ") has not permission to delete item!");
        } else {
          log.error("User(anonymous) has not permission to delete item!");
        }
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
      }

      writeStats(
          dspaceCollection,
          UsageEvent.Action.UPDATE,
          user_ip,
          user_agent,
          xforwarderfor,
          headers,
          request,
          context);
      writeStats(
          item,
          UsageEvent.Action.REMOVE,
          user_ip,
          user_agent,
          xforwarderfor,
          headers,
          request,
          context);

      dspaceCollection.removeItem(item);

      context.complete();

    } catch (ContextException e) {
      processException(
          "Could not delete item(id="
              + itemId
              + ") in collection(id="
              + collectionId
              + "), ContextException. Message: "
              + e.getMessage(),
          context);
    } catch (SQLException e) {
      processException(
          "Could not delete item(id="
              + itemId
              + ") in collection(id="
              + collectionId
              + "), SQLException. Message: "
              + e,
          context);
    } catch (AuthorizeException e) {
      processException(
          "Could not delete item(id="
              + itemId
              + ") in collection(id="
              + collectionId
              + "), AuthorizeException. Message: "
              + e,
          context);
    } catch (IOException e) {
      processException(
          "Could not delete item(id="
              + itemId
              + ") in collection(id="
              + collectionId
              + "), IOException. Message: "
              + e,
          context);
    } finally {
      processFinally(context);
    }

    log.info(
        "Item(id=" + itemId + ") in collection(id=" + collectionId + ") was successfully deleted.");
    return Response.ok().build();
  }
  protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // Obtain information from request
    // The page where the user came from
    String fromPage = request.getHeader("Referer");

    // Prevent spammers and splogbots from poisoning the feedback page
    String host = ConfigurationManager.getProperty("dspace.hostname");

    String basicHost = "";
    if (host.equals("localhost")
        || host.equals("127.0.0.1")
        || host.equals(InetAddress.getLocalHost().getHostAddress())) basicHost = host;
    else {
      // cut off all but the hostname, to cover cases where more than one URL
      // arrives at the installation; e.g. presence or absence of "www"
      int lastDot = host.lastIndexOf(".");
      basicHost = host.substring(host.substring(0, lastDot).lastIndexOf("."));
    }

    if (fromPage == null || fromPage.indexOf(basicHost) == -1) {
      throw new AuthorizeException();
    }

    // The email address they provided
    String formEmail = request.getParameter("email");

    // Browser
    String userAgent = request.getHeader("User-Agent");

    // Session id
    String sessionID = request.getSession().getId();

    // User email from context
    EPerson currentUser = context.getCurrentUser();
    String authEmail = null;

    if (currentUser != null) {
      authEmail = currentUser.getEmail();
    }

    // Has the user just posted their feedback?
    if (request.getParameter("submit") != null) {
      EmailValidator ev = EmailValidator.getInstance();
      String feedback = request.getParameter("feedback");

      // Check all data is there
      if ((formEmail == null)
          || formEmail.equals("")
          || (feedback == null)
          || feedback.equals("")
          || !ev.isValid(formEmail)) {
        log.info(LogManager.getHeader(context, "show_feedback_form", "problem=true"));
        request.setAttribute("feedback.problem", new Boolean(true));
        JSPManager.showJSP(request, response, "/feedback/form.jsp");

        return;
      }

      // All data is there, send the email
      try {
        Email email =
            ConfigurationManager.getEmail(
                I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback"));
        email.addRecipient(ConfigurationManager.getProperty("feedback.recipient"));

        email.addArgument(new Date()); // Date
        email.addArgument(formEmail); // Email
        email.addArgument(authEmail); // Logged in as
        email.addArgument(fromPage); // Referring page
        email.addArgument(userAgent); // User agent
        email.addArgument(sessionID); // Session ID
        email.addArgument(feedback); // The feedback itself

        // Replying to feedback will reply to email on form
        email.setReplyTo(formEmail);

        email.send();

        log.info(LogManager.getHeader(context, "sent_feedback", "from=" + formEmail));

        JSPManager.showJSP(request, response, "/feedback/acknowledge.jsp");
      } catch (MessagingException me) {
        log.warn(LogManager.getHeader(context, "error_mailing_feedback", ""), me);

        JSPManager.showInternalError(request, response);
      }
    } else {
      // Display feedback form
      log.info(LogManager.getHeader(context, "show_feedback_form", "problem=false"));
      request.setAttribute("authenticated.email", authEmail);
      JSPManager.showJSP(request, response, "/feedback/form.jsp");
    }
  }