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

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

    InstallItem.installItem(c, wfi);

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

    return item;
  }
  /**
   * Get a workflow item from the database. The item, collection and submitter are loaded into
   * memory.
   *
   * @param context DSpace context object
   * @param id ID of the workspace item
   * @return the workflow item, or null if the ID is invalid.
   */
  public static WorkflowItem find(Context context, int id) throws SQLException {
    // First check the cache
    WorkflowItem fromCache = (WorkflowItem) context.fromCache(WorkflowItem.class, id);

    if (fromCache != null) {
      return fromCache;
    }

    TableRow row = DatabaseManager.find(context, "workflowitem", id);

    if (row == null) {
      if (log.isDebugEnabled()) {
        log.debug(
            LogManager.getHeader(context, "find_workflow_item", "not_found,workflow_id=" + id));
      }

      return null;
    } else {
      if (log.isDebugEnabled()) {
        log.debug(LogManager.getHeader(context, "find_workflow_item", "workflow_id=" + id));
      }

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

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

    installItemService.installItem(context, workflowItem);

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

    return item;
  }
Ejemplo n.º 4
0
  /**
   * Return the focus value.
   *
   * @return the focus value to use
   * @throws BrowseException
   */
  private String getJumpToValue() throws BrowseException {
    log.debug(LogManager.getHeader(context, "get_focus_value", ""));

    // if the focus is by value, just return it
    if (scope.hasJumpToValue()) {
      log.debug(
          LogManager.getHeader(
              context, "get_focus_value_return", "return=" + scope.getJumpToValue()));
      return scope.getJumpToValue();
    }

    // if the focus is to start with, then we need to return the value of the starts with
    if (scope.hasStartsWith()) {
      log.debug(
          LogManager.getHeader(
              context, "get_focus_value_return", "return=" + scope.getStartsWith()));
      return scope.getStartsWith();
    }

    // since the focus is not by value, we need to obtain it

    // get the id of the item to focus on
    int id = scope.getJumpToItem();

    // get the table name.  We don't really need to care about whether we are in a
    // community or collection at this point.  This is only for full or second
    // level browse, so there is no need to worry about distinct value browsing
    String tableName = browseIndex.getTableName();

    // we need to make sure that we select from the correct column.  If the sort option
    // is the 0th option then we use sort_value, but if it is one of the others we have
    // to select from that column instead.  Otherwise, we end up missing the focus value
    // to do comparisons in other columns.  The use of the focus value needs to be consistent
    // across the browse
    SortOption so = scope.getSortOption();
    if (so == null || so.getNumber() == 0) {
      if (browseIndex.getSortOption() != null) {
        so = browseIndex.getSortOption();
      }
    }

    String col = "sort_1";
    if (so.getNumber() > 0) {
      col = "sort_" + Integer.toString(so.getNumber());
    }

    // now get the DAO to do the query for us, returning the highest
    // string value in the given column in the given table for the
    // item (I think)
    String max = dao.doMaxQuery(col, tableName, id);

    log.debug(LogManager.getHeader(context, "get_focus_value_return", "return=" + max));

    return max;
  }
  /*
   * 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);
      }
    }
  }
  protected void notifyOfReject(
      Context context, BasicWorkflowItem workflowItem, EPerson e, String reason) {
    try {
      // Get the item title
      String title = getItemTitle(workflowItem);

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

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

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

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

      throw re;
    } catch (Exception ex) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + ex.getMessage()));
    }
  }
Ejemplo n.º 7
0
  /**
   * Get the position of the current start point of the browse in the field of total objects
   * relevant to this browse. This is integrally related to how results are presented in pages to
   * the User Interface. The argument tells us whether this is a distinct browse or not, as this has
   * an impact on how results are calculated
   *
   * @param distinct is this a distinct browse
   * @return the offset of the first result from the start of the set
   * @throws SQLException
   * @throws BrowseException
   */
  private int getPosition(boolean distinct) throws SQLException, BrowseException {
    log.debug(LogManager.getHeader(context, "get_position", "distinct=" + distinct));

    // if there isn't a focus then we are at the start
    if (dao.getJumpToValue() == null) {
      log.debug(LogManager.getHeader(context, "get_position_return", "return=0"));
      return 0;
    }

    // get the table name that we are going to be getting our data from
    String tableName =
        browseIndex.getTableName(distinct, scope.inCommunity(), scope.inCollection());

    // ensure that the select is set to "*"
    String[] select = {"*"};
    dao.setCountValues(select);

    // FIXME: it would be nice to have a good way of doing this in the DAO
    // now reset all of the fields that we don't want to have constraining
    // our count, storing them locally to reinstate later
    boolean isAscending = dao.isAscending();
    boolean useEquals = dao.useEqualsComparator();
    String orderField = dao.getOrderField();
    int limit = dao.getLimit();
    int offset = dao.getOffset();

    // reverse the direction of the query, and remove the equal comparator
    // (if it exists), as well as nullifying a few other unnecessary parameters
    dao.setAscending(!isAscending);
    dao.setEqualsComparator(false);
    dao.setOrderField(null);
    dao.setLimit(-1);
    dao.setOffset(-1);

    // perform the query and get the result
    int count = dao.doCountQuery();

    // now put back the values we removed for this method
    dao.setAscending(isAscending);
    dao.setEqualsComparator(useEquals);
    dao.setOrderField(orderField);
    dao.setLimit(limit);
    dao.setOffset(offset);

    log.debug(LogManager.getHeader(context, "get_position_return", "return=" + count));

    return count;
  }
  @Override
  public WorkspaceItem abort(Context context, BasicWorkflowItem workflowItem, EPerson e)
      throws SQLException, AuthorizeException, IOException {
    // authorize a DSpaceActions.ABORT
    if (!authorizeService.isAdmin(context)) {
      throw new AuthorizeException("You must be an admin to abort a workflow");
    }

    // stop workflow regardless of its state
    taskListItemService.deleteByWorkflowItem(context, workflowItem);

    log.info(
        LogManager.getHeader(
            context,
            "abort_workflow",
            "workflow_item_id="
                + workflowItem.getID()
                + "item_id="
                + workflowItem.getItem().getID()
                + "collection_id="
                + workflowItem.getCollection().getID()
                + "eperson_id="
                + e.getID()));

    // convert into personal workspace
    return returnToWorkspace(context, workflowItem);
  }
Ejemplo n.º 9
0
  @Override
  public void removeSubcommunity(
      Context context, Community parentCommunity, Community childCommunity)
      throws SQLException, AuthorizeException, IOException {
    // Check authorisation
    authorizeService.authorizeAction(context, parentCommunity, Constants.REMOVE);

    ArrayList<String> removedIdentifiers = getIdentifiers(context, childCommunity);
    String removedHandle = childCommunity.getHandle();
    UUID removedId = childCommunity.getID();

    parentCommunity.removeSubCommunity(childCommunity);
    childCommunity.getParentCommunities().remove(parentCommunity);
    if (CollectionUtils.isEmpty(childCommunity.getParentCommunities())) {
      rawDelete(context, childCommunity);
    }
    log.info(
        LogManager.getHeader(
            context,
            "remove_subcommunity",
            "parent_comm_id="
                + parentCommunity.getID()
                + ",child_comm_id="
                + childCommunity.getID()));

    context.addEvent(
        new Event(
            Event.REMOVE,
            Constants.COMMUNITY,
            parentCommunity.getID(),
            Constants.COMMUNITY,
            removedId,
            removedHandle,
            removedIdentifiers));
  }
  /* (non-Javadoc)
   * @see org.dspace.browse.BrowseDAO#doCountQuery()
   */
  public int doCountQuery() throws BrowseException {
    String query = getQuery();
    Object[] params = getQueryParams();

    if (log.isDebugEnabled()) {
      log.debug(LogManager.getHeader(context, "executing_count_query", "query=" + query));
    }

    TableRowIterator tri = null;

    try {
      // now run the query
      tri = DatabaseManager.query(context, query, params);

      if (tri.hasNext()) {
        TableRow row = tri.next();
        return (int) row.getLongColumn("num");
      } else {
        return 0;
      }
    } catch (SQLException e) {
      log.error("caught exception: ", e);
      throw new BrowseException(e);
    } finally {
      if (tri != null) {
        tri.close();
      }
    }
  }
  /**
   * show the workspace item home page
   *
   * @param context the context of the request
   * @param request the servlet request
   * @param response the servlet response
   */
  private void showMainPage(Context c, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // get the value from the request
    int wsItemID = UIUtil.getIntParameter(request, "workspace_id");

    // get the workspace item, item and collections from the request value
    WorkspaceItem wsItem = WorkspaceItem.find(c, wsItemID);
    Item item = wsItem.getItem();
    // Collection[] collections = item.getCollections();
    Collection[] collections = {wsItem.getCollection()};

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

    log.info(
        LogManager.getHeader(c, "View Workspace Item Metadata", "workspace_item_id=" + wsItemID));

    // Full or simple display?
    boolean displayAll = false;
    String button = UIUtil.getSubmitButton(request, "submit_simple");
    if (button.equalsIgnoreCase("submit_full")) {
      displayAll = true;
    }

    // FIXME: we need to synchronise with the handle servlet to use the
    // display item JSP for both handled and un-handled items
    // Set attributes and display
    // request.setAttribute("wsItem", wsItem);
    request.setAttribute("display.all", Boolean.valueOf(displayAll));
    request.setAttribute("item", item);
    request.setAttribute("collections", collections);
    request.setAttribute("workspace_id", Integer.valueOf(wsItem.getID()));

    JSPManager.showJSP(request, response, "/display-item.jsp");
  }
Ejemplo n.º 12
0
  /**
   * Creates a new metadata field.
   *
   * @param context DSpace context object
   * @throws IOException
   * @throws AuthorizeException
   * @throws SQLException
   * @throws NonUniqueMetadataException
   */
  public void create(Context context)
      throws IOException, AuthorizeException, SQLException, NonUniqueMetadataException {
    // Check authorisation: Only admins may create DC types
    if (!AuthorizeManager.isAdmin(context)) {
      throw new AuthorizeException("Only administrators may modify the metadata registry");
    }

    // Ensure the element and qualifier are unique within a given schema.
    if (!unique(context, schemaID, element, qualifier)) {
      throw new NonUniqueMetadataException(
          "Please make " + element + "." + qualifier + " unique within schema #" + schemaID);
    }

    // Create a table row and update it with the values
    row = DatabaseManager.row("MetadataFieldRegistry");
    row.setColumn("metadata_schema_id", schemaID);
    row.setColumn("element", element);
    row.setColumn("qualifier", qualifier);
    row.setColumn("scope_note", scopeNote);
    DatabaseManager.insert(context, row);
    decache();

    // Remember the new row number
    this.fieldID = row.getIntColumn("metadata_field_id");

    log.info(
        LogManager.getHeader(
            context,
            "create_metadata_field",
            "metadata_field_id=" + row.getIntColumn("metadata_field_id")));
  }
Ejemplo n.º 13
0
  /* (non-Javadoc)
   * @see org.dspace.browse.BrowseDAO#doValueQuery()
   */
  public List<String[]> doValueQuery() throws BrowseException {
    String query = getQuery();

    Object[] params = getQueryParams();
    log.debug(LogManager.getHeader(context, "executing_value_query", "query=" + query));

    TableRowIterator tri = null;

    try {
      // now run the query
      tri = DatabaseManager.query(context, query, params);

      // go over the query results and process
      List<String[]> results = new ArrayList<String[]>();
      while (tri.hasNext()) {
        TableRow row = tri.next();
        String valueResult = row.getStringColumn("value");
        String authorityResult = row.getStringColumn("authority");
        if (enableBrowseFrequencies) {
          long frequency = row.getLongColumn("num");
          results.add(new String[] {valueResult, authorityResult, String.valueOf(frequency)});
        } else results.add(new String[] {valueResult, authorityResult, ""});
      }

      return results;
    } catch (SQLException e) {
      log.error("caught exception: ", e);
      throw new BrowseException(e);
    } finally {
      if (tri != null) {
        tri.close();
      }
    }
  }
Ejemplo n.º 14
0
  @Override
  public WorkspaceItem abort(Context c, XmlWorkflowItem wi, EPerson e)
      throws AuthorizeException, SQLException, IOException {
    if (!authorizeService.isAdmin(c)) {
      throw new AuthorizeException("You must be an admin to abort a workflow");
    }

    c.turnOffAuthorisationSystem();
    // Restore permissions for the submitter
    // convert into personal workspace
    WorkspaceItem wsi = returnToWorkspace(c, wi);

    log.info(
        LogManager.getHeader(
            c,
            "abort_workflow",
            "workflow_item_id="
                + wi.getID()
                + "item_id="
                + wsi.getItem().getID()
                + "collection_id="
                + wi.getCollection().getID()
                + "eperson_id="
                + e.getID()));

    c.restoreAuthSystemState();
    return wsi;
  }
Ejemplo n.º 15
0
  @Override
  public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters)
      throws ProcessingException, SAXException, IOException {
    super.setup(resolver, objectModel, src, parameters);
    authorized = true;
    try {
      String stepID = parameters.getParameter("step_id");
      String beanID = parameters.getParameter("bean_id");
      int workspaceID = Integer.valueOf(parameters.getParameter("workspace_item_id").substring(1));
      WorkspaceService wi = WorkspaceService.find(context, workspaceID);
      SubmissionProcess process =
          SubmissionProcessFactory.getSubmissionProcess(context, wi.getCollection());
      SubmissionStep step = process.getStep(context, Integer.parseInt(stepID));
      xmluiActionUI =
          (AbstractXMLUIAction) SubmissionProcessXMLUIFactory.getActionInterface(beanID);
      // authorized = step.getActionConfig(beanID).getProcessingAction().isAuthorized(context,
      // ObjectModelHelper.getRequest(objectModel), wi);

      if (xmluiActionUI != null) xmluiActionUI.setup(resolver, objectModel, src, parameters);
      //            else
      //                throw new ProcessingException("SubmissionStep class is null!  We do not have
      // a valid AbstractStep in " + this.transformerClassName + ". ");
    } catch (Exception e) {
      log.error(
          LogManager.getHeader(context, "error while setting up SubmissionTransformer", ""), e);
      e.printStackTrace();
      throw new ProcessingException("Something went wrong while setting up the workflow");
    }
    // TODO: throw exception !
  }
  /* (non-Javadoc)
   * @see org.dspace.browse.BrowseDAO#doValueQuery()
   */
  public List doValueQuery() throws BrowseException {
    String query = getQuery();
    Object[] params = getQueryParams();
    log.debug(LogManager.getHeader(context, "executing_value_query", "query=" + query));

    TableRowIterator tri = null;

    try {
      // now run the query
      tri = DatabaseManager.query(context, query, params);

      // go over the query results and process
      List results = new ArrayList();
      while (tri.hasNext()) {
        TableRow row = tri.next();
        String stringResult = row.getStringColumn("value");
        results.add(stringResult);
      }

      return results;
    } catch (SQLException e) {
      log.error("caught exception: ", e);
      throw new BrowseException(e);
    } finally {
      if (tri != null) {
        tri.close();
      }
    }
  }
  /**
   * Return the workflow item to the workspace of the submitter. The workflow item is removed, and a
   * workspace item created.
   *
   * @param c Context
   * @param wfi WorkflowItem to be 'dismantled'
   * @return the workspace item
   */
  protected WorkspaceItem returnToWorkspace(Context c, BasicWorkflowItem wfi)
      throws SQLException, IOException, AuthorizeException {
    // FIXME: How should this interact with the workflow system?
    // FIXME: Remove license
    // FIXME: Provenance statement?
    // Create the new workspace item row
    WorkspaceItem workspaceItem = workspaceItemService.create(c, wfi);

    workspaceItem.setMultipleFiles(wfi.hasMultipleFiles());
    workspaceItem.setMultipleTitles(wfi.hasMultipleTitles());
    workspaceItem.setPublishedBefore(wfi.isPublishedBefore());
    workspaceItemService.update(c, workspaceItem);

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

    // Now remove the workflow object manually from the database
    workflowItemService.deleteWrapper(c, wfi);

    return workspaceItem;
  }
Ejemplo n.º 18
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;
  }
 /*
  * 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;
 }
    /** contact the ldap server and attempt to authenticate */
    protected boolean ldapAuthenticate(String netid, String password, Context context) {
      if (!password.equals("")) {

        LdapContext ctx = null;
        StartTlsResponse startTLSResponse = null;

        // Set up environment for creating initial context
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url);

        try {
          if (useTLS) {
            ctx = new InitialLdapContext(env, null);
            // start TLS
            startTLSResponse = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());

            startTLSResponse.negotiate();

            // perform simple client authentication
            ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, netid);
            ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, password);
            ctx.addToEnvironment(javax.naming.Context.AUTHORITATIVE, "true");
            ctx.addToEnvironment(javax.naming.Context.REFERRAL, "follow");
            // dummy operation to check if authentication has succeeded
            ctx.getAttributes("");
          } else if (!useTLS) {
            // Authenticate
            env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
            env.put(javax.naming.Context.SECURITY_PRINCIPAL, netid);
            env.put(javax.naming.Context.SECURITY_CREDENTIALS, password);
            env.put(javax.naming.Context.AUTHORITATIVE, "true");
            env.put(javax.naming.Context.REFERRAL, "follow");

            // Try to bind
            ctx = new InitialLdapContext(env, null);
          }
        } catch (NamingException | IOException e) {
          // something went wrong (like wrong password) so return false
          log.warn(LogManager.getHeader(context, "ldap_authentication", "type=failed_auth " + e));
          return false;
        } finally {
          // Close the context when we're done
          try {
            if (startTLSResponse != null) {
              startTLSResponse.close();
            }
            if (ctx != null) {
              ctx.close();
            }
          } catch (NamingException | IOException e) {
          }
        }
      } else {
        return false;
      }

      return true;
    }
Ejemplo n.º 21
0
  /* (non-Javadoc)
   * @see org.dspace.browse.BrowseDAO#doQuery()
   */
  public List<BrowseItem> doQuery() throws BrowseException {
    String query = getQuery();
    Object[] params = getQueryParams();

    if (log.isDebugEnabled()) {
      log.debug(LogManager.getHeader(context, "executing_full_query", "query=" + query));
    }

    TableRowIterator tri = null;
    try {
      // now run the query
      tri = DatabaseManager.query(context, query, params);

      // go over the query results and process
      List<BrowseItem> results = new ArrayList<BrowseItem>();
      while (tri.hasNext()) {
        TableRow row = tri.next();
        BrowseItem browseItem =
            new BrowseItem(context, row.getIntColumn("item_id"), itemsInArchive, itemsWithdrawn);
        results.add(browseItem);
      }

      return results;
    } catch (SQLException e) {
      log.error("caught exception: ", e);
      throw new BrowseException("problem with query: " + query, e);
    } finally {
      if (tri != null) {
        tri.close();
      }
    }
  }
Ejemplo n.º 22
0
  @Override
  public void removeCollection(Context context, Community community, Collection collection)
      throws SQLException, AuthorizeException, IOException {
    // Check authorisation
    authorizeService.authorizeAction(context, community, Constants.REMOVE);

    community.removeCollection(collection);
    ArrayList<String> removedIdentifiers = collectionService.getIdentifiers(context, collection);
    String removedHandle = collection.getHandle();
    UUID removedId = collection.getID();

    collection.removeCommunity(community);
    if (CollectionUtils.isEmpty(collection.getCommunities())) {
      collectionService.delete(context, collection);
    }

    log.info(
        LogManager.getHeader(
            context,
            "remove_collection",
            "community_id=" + community.getID() + ",collection_id=" + collection.getID()));

    // Remove any mappings
    context.addEvent(
        new Event(
            Event.REMOVE,
            Constants.COMMUNITY,
            community.getID(),
            Constants.COLLECTION,
            removedId,
            removedHandle,
            removedIdentifiers));
  }
Ejemplo n.º 23
0
  @Override
  public void addCollection(Context context, Community community, Collection collection)
      throws SQLException, AuthorizeException {
    // Check authorisation
    authorizeService.authorizeAction(context, community, Constants.ADD);

    log.info(
        LogManager.getHeader(
            context,
            "add_collection",
            "community_id=" + community.getID() + ",collection_id=" + collection.getID()));

    if (!community.getCollections().contains(collection)) {
      community.addCollection(collection);
      collection.addCommunity(community);
    }
    context.addEvent(
        new Event(
            Event.ADD,
            Constants.COMMUNITY,
            community.getID(),
            Constants.COLLECTION,
            collection.getID(),
            community.getHandle(),
            getIdentifiers(context, community)));
  }
Ejemplo n.º 24
0
  @Override
  public void addSubcommunity(Context context, Community parentCommunity, Community childCommunity)
      throws SQLException, AuthorizeException {
    // Check authorisation
    authorizeService.authorizeAction(context, parentCommunity, Constants.ADD);

    log.info(
        LogManager.getHeader(
            context,
            "add_subcommunity",
            "parent_comm_id="
                + parentCommunity.getID()
                + ",child_comm_id="
                + childCommunity.getID()));

    if (!parentCommunity.getSubcommunities().contains(childCommunity)) {
      parentCommunity.addSubCommunity(childCommunity);
      childCommunity.addParentCommunity(parentCommunity);
    }
    context.addEvent(
        new Event(
            Event.ADD,
            Constants.COMMUNITY,
            parentCommunity.getID(),
            Constants.COMMUNITY,
            childCommunity.getID(),
            parentCommunity.getHandle(),
            getIdentifiers(context, parentCommunity)));
  }
Ejemplo n.º 25
0
  @Override
  public void update(Context context, Community community) throws SQLException, AuthorizeException {
    // Check authorisation
    canEdit(context, community);

    log.info(
        LogManager.getHeader(context, "update_community", "community_id=" + community.getID()));

    communityDAO.save(context, community);
    if (community.isModified()) {
      context.addEvent(
          new Event(
              Event.MODIFY,
              Constants.COMMUNITY,
              community.getID(),
              null,
              getIdentifiers(context, community)));
      community.setModified();
    }
    if (community.isMetadataModified()) {
      context.addEvent(
          new Event(
              Event.MODIFY_METADATA,
              Constants.COMMUNITY,
              community.getID(),
              community.getDetails(),
              getIdentifiers(context, community)));
      community.clearModified();
    }
    community.clearDetails();
  }
Ejemplo n.º 26
0
  /**
   * Return the workflow item to the workspace of the submitter. The workflow item is removed, and a
   * workspace item created.
   *
   * @param c Context
   * @param wfi WorkflowItem to be 'dismantled'
   * @return the workspace item
   */
  private static WorkspaceItem returnToWorkspace(Context c, WorkflowItem wfi)
      throws SQLException, IOException, AuthorizeException {
    Item myitem = wfi.getItem();
    Collection mycollection = wfi.getCollection();

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

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

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

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

    return wi;
  }
Ejemplo n.º 27
0
  /**
   * abort() aborts a workflow, completely deleting it (administrator do this) (it will basically do
   * a reject from any state - the item ends up back in the user's PersonalWorkspace
   *
   * @param c Context
   * @param wi WorkflowItem to operate on
   * @param e EPerson doing the operation
   */
  public static void abort(Context c, WorkflowItem wi, EPerson e)
      throws SQLException, AuthorizeException, IOException {
    // authorize a DSpaceActions.ABORT
    if (!AuthorizeManager.isAdmin(c)) {
      throw new AuthorizeException("You must be an admin to abort a workflow");
    }

    // stop workflow regardless of its state
    deleteTasks(c, wi);

    log.info(
        LogManager.getHeader(
            c,
            "abort_workflow",
            "workflow_item_id="
                + wi.getID()
                + "item_id="
                + wi.getItem().getID()
                + "collection_id="
                + wi.getCollection().getID()
                + "eperson_id="
                + e.getID()));

    // convert into personal workspace
    WorkspaceItem wsi = returnToWorkspace(c, wi);
  }
Ejemplo n.º 28
0
  /** Update the group - writing out group object and EPerson list if necessary */
  public void update() throws SQLException, AuthorizeException {
    // FIXME: Check authorisation
    DatabaseManager.update(myContext, myRow);

    if (modifiedMetadata) {
      myContext.addEvent(new Event(Event.MODIFY_METADATA, Constants.GROUP, getID(), getDetails()));
      modifiedMetadata = false;
      clearDetails();
    }

    // Redo eperson mappings if they've changed
    if (epeopleChanged) {
      // Remove any existing mappings
      DatabaseManager.updateQuery(
          myContext, "delete from epersongroup2eperson where eperson_group_id= ? ", getID());

      // Add new mappings
      Iterator<EPerson> i = epeople.iterator();

      while (i.hasNext()) {
        EPerson e = i.next();

        TableRow mappingRow = DatabaseManager.row("epersongroup2eperson");
        mappingRow.setColumn("eperson_id", e.getID());
        mappingRow.setColumn("eperson_group_id", getID());
        DatabaseManager.insert(myContext, mappingRow);
      }

      epeopleChanged = false;
    }

    // Redo Group mappings if they've changed
    if (groupsChanged) {
      // Remove any existing mappings
      DatabaseManager.updateQuery(
          myContext, "delete from group2group where parent_id= ? ", getID());

      // Add new mappings
      Iterator<Group> i = groups.iterator();

      while (i.hasNext()) {
        Group g = i.next();

        TableRow mappingRow = DatabaseManager.row("group2group");
        mappingRow.setColumn("parent_id", getID());
        mappingRow.setColumn("child_id", g.getID());
        DatabaseManager.insert(myContext, mappingRow);
      }

      // groups changed, now change group cache
      rethinkGroupCache();

      groupsChanged = false;
    }

    log.info(LogManager.getHeader(myContext, "update_group", "group_id=" + getID()));
  }
Ejemplo n.º 29
0
  /** Update the workflow item, including the unarchived item. */
  public void update() throws SQLException, IOException, AuthorizeException {
    // FIXME check auth
    log.info(
        LogManager.getHeader(ourContext, "update_workflow_item", "workflow_item_id=" + getID()));

    // Update the item
    item.update();

    // Update ourselves
    DatabaseManager.update(ourContext, wfRow);
  }
  /**
   * Show error page if nothing has been <code>POST</code>ed to servlet
   *
   * @param context the context of the request
   * @param request the servlet request
   * @param response the servlet response
   */
  private void showErrorPage(
      Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    int wsItemID = UIUtil.getIntParameter(request, "workspace_id");

    log.error(
        LogManager.getHeader(
            context, "View Workspace Item Metadata Failed", "workspace_item_id=" + wsItemID));

    JSPManager.showJSP(request, response, "/workspace/wsv-error.jsp");
  }