Exemple #1
0
  protected void logSearch() {
    int countCommunities = 0;
    int countCollections = 0;
    int countItems = 0;

    for (Integer type : queryResults.getHitTypes()) {
      switch (type.intValue()) {
        case Constants.ITEM:
          countItems++;
          break;
        case Constants.COLLECTION:
          countCollections++;
          break;
        case Constants.COMMUNITY:
          countCommunities++;
          break;
      }
    }

    String logInfo = "";

    try {
      DSpaceObject dsoScope = getScope();

      if (dsoScope instanceof Collection) {
        logInfo = "collection_id=" + dsoScope.getID() + ",";
      } else if (dsoScope instanceof Community) {
        logInfo = "community_id=" + dsoScope.getID() + ",";
      }
    } catch (SQLException sqle) {
      // Ignore, as we are only trying to get the scope to add detail to the log message
    }

    log.info(
        LogManager.getHeader(
            context,
            "search",
            logInfo
                + "query=\""
                + queryArgs.getQuery()
                + "\",results=("
                + countCommunities
                + ","
                + countCollections
                + ","
                + countItems
                + ")"));
  }
  /**
   * Return a List of the policies for an object
   *
   * @param c current context
   * @param o object to retrieve policies for
   * @return List of <code>ResourcePolicy</code> objects
   */
  public static List<ResourcePolicy> getPolicies(Context c, DSpaceObject o) throws SQLException {
    TableRowIterator tri =
        DatabaseManager.queryTable(
            c,
            "resourcepolicy",
            "SELECT * FROM resourcepolicy WHERE resource_type_id= ? AND resource_id= ? ",
            o.getType(),
            o.getID());

    List<ResourcePolicy> policies = new ArrayList<ResourcePolicy>();

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

        // first check the cache (FIXME: is this right?)
        ResourcePolicy cachepolicy =
            (ResourcePolicy) c.fromCache(ResourcePolicy.class, row.getIntColumn("policy_id"));

        if (cachepolicy != null) {
          policies.add(cachepolicy);
        } else {
          policies.add(new ResourcePolicy(c, row));
        }
      }
    } finally {
      if (tri != null) {
        tri.close();
      }
    }

    return policies;
  }
 /**
  * removes ALL policies for an object. FIXME doesn't check authorization
  *
  * @param c DSpace context
  * @param o object to remove policies for
  * @throws SQLException if there's a database problem
  */
 public static void removeAllPolicies(Context c, DSpaceObject o) throws SQLException {
   // FIXME: authorization check?
   DatabaseManager.updateQuery(
       c,
       "DELETE FROM resourcepolicy WHERE " + "resource_type_id= ? AND resource_id= ? ",
       o.getType(),
       o.getID());
 }
 /**
  * Removes all policies from a group for a particular object that belong to a Group. FIXME doesn't
  * check authorization
  *
  * @param c current context
  * @param o the object
  * @param g the group
  * @throws SQLException if there's a database problem
  */
 public static void removeGroupPolicies(Context c, DSpaceObject o, Group g) throws SQLException {
   DatabaseManager.updateQuery(
       c,
       "DELETE FROM resourcepolicy WHERE "
           + "resource_type_id= ? AND resource_id= ? AND epersongroup_id= ? ",
       o.getType(),
       o.getID(),
       g.getID());
 }
  /**
   * Return the metadata URL of the supplied object, assuming it's a DSpace item, community or
   * collection.
   */
  public String getObjectURL(Object object) throws WingException {
    if (object instanceof DSpaceObject) {
      DSpaceObject dso = (DSpaceObject) object;
      String handle = dso.getHandle();

      // If the object has a handle then refrence it by it's handle.
      if (handle != null) {
        return "/metadata/handle/" + handle + "/mets.xml";
      } else {
        // No handle then refrence it by an internal ID.
        if (dso instanceof Item || dso instanceof BrowseItem) {
          return "/metadata/internal/item/" + dso.getID() + "/mets.xml";
        } else if (object instanceof Collection) {
          return "/metadata/internal/collection/" + dso.getID() + "/mets.xml";
        } else if (object instanceof Community) {
          return "/metadata/internal/community/" + dso.getID() + "/mets.xml";
        }
      }
    }

    return null;
  }
  /**
   * Returns all groups authorized to perform an action on an object. Returns empty array if no
   * matches.
   *
   * @param c current context
   * @param o object
   * @param actionID ID of action frm <code>org.dspace.core.Constants</code>
   * @return array of <code>Group</code>s that can perform the specified action on the specified
   *     object
   * @throws java.sql.SQLException if there's a database problem
   */
  public static Group[] getAuthorizedGroups(Context c, DSpaceObject o, int actionID)
      throws java.sql.SQLException {
    // do query matching groups, actions, and objects
    TableRowIterator tri =
        DatabaseManager.queryTable(
            c,
            "resourcepolicy",
            "SELECT * FROM resourcepolicy WHERE resource_type_id= ? "
                + "AND resource_id= ? AND action_id= ? ",
            o.getType(),
            o.getID(),
            actionID);

    List<Group> groups = new ArrayList<Group>();
    try {

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

        // first check the cache (FIXME: is this right?)
        ResourcePolicy cachepolicy =
            (ResourcePolicy) c.fromCache(ResourcePolicy.class, row.getIntColumn("policy_id"));

        ResourcePolicy myPolicy = null;

        if (cachepolicy != null) {
          myPolicy = cachepolicy;
        } else {
          myPolicy = new ResourcePolicy(c, row);
        }

        // now do we have a group?
        Group myGroup = myPolicy.getGroup();

        if (myGroup != null) {
          groups.add(myGroup);
        }
      }
    } finally {
      if (tri != null) {
        tri.close();
      }
    }

    Group[] groupArray = new Group[groups.size()];
    groupArray = groups.toArray(groupArray);

    return groupArray;
  }
 /**
  * Remove all policies from an object that match a given action. FIXME doesn't check authorization
  *
  * @param context current context
  * @param dso object to remove policies from
  * @param actionID ID of action to match from <code>org.dspace.core.Constants</code>, or -1=all
  * @throws SQLException if there's a database problem
  */
 public static void removePoliciesActionFilter(Context context, DSpaceObject dso, int actionID)
     throws SQLException {
   if (actionID == -1) {
     // remove all policies from object
     removeAllPolicies(context, dso);
   } else {
     DatabaseManager.updateQuery(
         context,
         "DELETE FROM resourcepolicy WHERE resource_type_id= ? AND "
             + "resource_id= ? AND action_id= ? ",
         dso.getType(),
         dso.getID(),
         actionID);
   }
 }
  private static String formatMessage(DSpaceObject object) {
    try {
      String objText = Constants.typeText[object.getType()].toLowerCase();
      String handle = object.getHandle();

      /* Emulate Item logger */
      if (handle != null && object instanceof Item) {
        return "handle=" + object.getHandle();
      } else {
        return objText + "_id=" + object.getID();
      }

    } catch (Exception e) {

    }
    return "";
  }
Exemple #9
0
  /**
   * Process sets of objects to add, update, and delete in index. Correct for interactions between
   * the sets -- e.g. objects which were deleted do not need to be added or updated, new objects
   * don't also need an update, etc.
   */
  public void end(Context ctx) throws Exception {

    if (objectsToUpdate != null && handlesToDelete != null) {

      // update the changed Items not deleted because they were on create list
      for (DSpaceObject iu : objectsToUpdate) {
        /* we let all types through here and
         * allow the search DSIndexer to make
         * decisions on indexing and/or removal
         */
        String hdl = iu.getHandle();
        if (hdl != null && !handlesToDelete.contains(hdl)) {
          try {
            DSIndexer.indexContent(ctx, iu, true);
            log.debug(
                "Indexed "
                    + Constants.typeText[iu.getType()]
                    + ", id="
                    + String.valueOf(iu.getID())
                    + ", handle="
                    + hdl);
          } catch (Exception e) {
            log.error("Failed while indexing object: ", e);
          }
        }
      }

      for (String hdl : handlesToDelete) {
        try {
          DSIndexer.unIndexContent(ctx, hdl);
          if (log.isDebugEnabled()) {
            log.debug("UN-Indexed Item, handle=" + hdl);
          }
        } catch (Exception e) {
          log.error("Failed while UN-indexing object: " + hdl, e);
        }
      }
    }

    // "free" the resources
    objectsToUpdate = null;
    handlesToDelete = null;
  }
Exemple #10
0
 protected void markProcessed(DSpaceObject dso) {
   this.processed.add(dso.getID());
 }
Exemple #11
0
  /**
   * Utility method for obtaining a string representation of the browse. This is useful only for
   * debug
   */
  public String toString() {
    try {
      StringBuffer sb = new StringBuffer();

      // calculate the range for display
      String from = Integer.toString(overallPosition + 1);
      String to = Integer.toString(overallPosition + results.size());
      String of = Integer.toString(total);

      // report on the positional information of the browse
      sb.append("BrowseInfo String Representation: ");
      sb.append("Browsing " + from + " to " + to + " of " + of + " ");

      // insert the information about which index
      sb.append(
          "in index: "
              + browseIndex.getName()
              + " (data type: "
              + browseIndex.getDataType()
              + ", display type: "
              + browseIndex.getDisplayType()
              + ") ");

      sb.append("||");

      // report on the browse scope container
      String container = "all of DSpace";
      DSpaceObject theContainer = null;
      if (inCollection()) {
        container = "collection";
        theContainer = this.collection;
      } else if (inCommunity()) {
        container = "community";
        theContainer = this.community;
      }

      String containerID = "no id available/necessary";
      if (theContainer != null) {
        containerID =
            Integer.toString(theContainer.getID()) + " (" + theContainer.getHandle() + ")";
      }

      sb.append("Browsing in " + container + ": " + containerID);
      sb.append("||");

      // load the item list display configuration
      ItemListConfig config = new ItemListConfig();

      // some information about the columns to be displayed
      if (browseIndex.isItemIndex()) {
        sb.append("Listing over " + Integer.toString(config.numCols()) + " columns: ");
        for (int k = 1; k <= config.numCols(); k++) {
          if (k > 1) {
            sb.append(",");
          }
          String[] meta = config.getMetadata(k);
          sb.append(meta[0] + "." + meta[1] + "." + meta[2]);
        }

        if (value != null) {
          sb.append(" on value: ").append(value);
        }

        if (isStartsWith()) {
          sb.append(" sort column starting with: ").append(focus);
        } else if (hasFocus()) {
          sb.append(" sort column focus: ").append(focus);
        }
      } else if (browseIndex.isMetadataIndex()) {
        sb.append("Listing single column: ").append(browseIndex.getMetadata());
        if (isStartsWith()) {
          sb.append(" sort column starting with: ").append(focus);
        } else if (hasFocus()) {
          sb.append(" sort column focus: ").append(focus);
        }
      }

      sb.append("||");

      // some information about how the data is sorted
      String direction = (ascending ? "ASC" : "DESC");
      sb.append(
          "Sorting by: "
              + sortOption.getMetadata()
              + " "
              + direction
              + " (option "
              + Integer.toString(sortOption.getNumber())
              + ")");
      sb.append("||");

      // output the results
      if (browseIndex.isMetadataIndex() && !isSecondLevel()) {
        sb.append(valueListingString());
      } else if (browseIndex.isItemIndex() || isSecondLevel()) {
        sb.append(fullListingString(config));
      }

      sb.append("||");

      // tell us what the next and previous values are going to be
      sb.append("Top of next page: ");
      if (hasNextPage()) {
        sb.append("offset: ").append(Integer.toString(this.nextOffset));
      } else {
        sb.append("n/a");
      }
      sb.append(";");

      sb.append("Top of previous page: ");
      if (hasPrevPage()) {
        sb.append("offset: ").append(Integer.toString(this.prevOffset));
      } else {
        sb.append("n/a");
      }

      sb.append("||");

      return sb.toString();
    } catch (SQLException e) {
      return e.getMessage();
    } catch (BrowseException e) {
      return e.getMessage();
    }
  }
  @Override
  public List<Item> getItems(
      DSpaceObject scope,
      String startDate,
      String endDate,
      int offset,
      int limit,
      boolean items,
      boolean collections,
      boolean withdrawn)
      throws ParseException {
    try {
      // Put together our query. Note there is no need for an
      // "in_archive=true" condition, we are using the existence of a
      // persistent identifier as our 'existence criterion'.
      String query =
          "SELECT p.value, p.type_id, p.resource_id as item_id, "
              + "i.withdrawn, i.last_modified "
              + "FROM externalidentifier p, item i";

      // We are building a complex query that may contain a variable
      // about of input data points. To accomidate this while still
      // providing type safty we build a list of parameters to be
      // plugged into the query at the database level.
      List parameters = new ArrayList();

      if (scope != null) {
        if (scope.getType() == Constants.COLLECTION) {
          query += ", collection2item cl2i";
        } else if (scope.getType() == Constants.COMMUNITY) {
          query += ", communities2item cm2i";
        }
      }

      query += " WHERE p.resource_type_id=" + Constants.ITEM + " AND p.resource_id = i.item_id ";

      if (scope != null) {
        if (scope.getType() == Constants.COLLECTION) {
          query += " AND cl2i.collection_id= ? " + " AND cl2i.item_id = p.resource_id ";
          parameters.add(scope.getID());
        } else if (scope.getType() == Constants.COMMUNITY) {
          query += " AND cm2i.community_id= ? " + " AND cm2i.item_id = p.resource_id";
          parameters.add(scope.getID());
        }
      }

      if (startDate != null) {
        query = query + " AND i.last_modified >= ? ";
        parameters.add(toTimestamp(startDate, false));
      }

      if (endDate != null) {
        /*
         * If the end date has seconds precision, e.g.:
         *
         * 2004-04-29T13:45:43Z
         *
         * we need to add 999 milliseconds to this. This is because SQL
         * TIMESTAMPs have millisecond precision, and so might have a value:
         *
         * 2004-04-29T13:45:43.952Z
         *
         * and so <= '2004-04-29T13:45:43Z' would not pick this up. Reading
         * things out of the database, TIMESTAMPs are rounded down, so the
         * above value would be read as '2004-04-29T13:45:43Z', and
         * therefore a caller would expect <= '2004-04-29T13:45:43Z' to
         * include that value.
         *
         * Got that? ;-)
         */
        boolean selfGenerated = false;
        if (endDate.length() == 20) {
          endDate = endDate.substring(0, 19) + ".999Z";
          selfGenerated = true;
        }

        query += " AND i.last_modified <= ? ";
        parameters.add(toTimestamp(endDate, selfGenerated));
      }

      if (!withdrawn) {
        // Exclude withdrawn items
        if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) {
          query += " AND withdrawn=0 ";
        } else {
          // postgres uses booleans
          query += " AND withdrawn=false ";
        }
      }

      // Order by item ID, so that for a given harvest the order will be
      // consistent. This is so that big harvests can be broken up into
      // several smaller operations (e.g. for OAI resumption tokens.)
      query += " ORDER BY p.resource_id";

      // Execute
      Object[] parametersArray = parameters.toArray();
      TableRowIterator tri = DatabaseManager.query(context, query, parametersArray);

      return returnAsList(tri);
    } catch (SQLException sqle) {
      throw new RuntimeException(sqle);
    }
  }
Exemple #13
0
  protected void dspaceDFS(DSpaceObject dso, Callback callback, boolean check, boolean reset)
      throws SQLException {
    if (dso.getType() != Constants.SITE
        && dso.getType() != Constants.COMMUNITY
        && dso.getType() != Constants.COLLECTION
        && dso.getType() != Constants.ITEM) {
      throw new IllegalArgumentException(
          contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
              + " is currently not supported as independent entity.");
    }

    if (reset) {
      this.processed.clear();
    }

    if (isProcessed(dso)) {
      log.debug(
          "Skipping processing of "
              + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
              + " "
              + dso.getID()
              + " (handle "
              + dso.getHandle()
              + "), already processed.");
      return;
    }
    markProcessed(dso);
    // this is useful to debug depth first search, but it is really noisy.
    // log.debug("Procesing " + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso) +
    // " " + dso.getID() + ":" + dso.getHandle() + ".");

    // if this method is used for conversion we should check if we have the
    // permissions to read a DSO before converting all of it decendents
    // (e.g. check read permission on a community before converting all of
    // its subcommunties and collections).
    // just skip items with missing permissions and report them.
    if (check) {
      try {
        RDFUtil.isPublic(context, dso);
      } catch (ItemNotArchivedException ex) {
        if (!(dso instanceof Item)) throw new IllegalStateException(ex.getMessage(), ex);
        report(
            "Skipping processing of Item "
                + dso.getID()
                + " (handle "
                + dso.getHandle()
                + "): Item is not "
                + "archived.");
        return;
      } catch (ItemWithdrawnException ex) {
        if (!(dso instanceof Item)) throw new IllegalStateException(ex.getMessage(), ex);
        report(
            "Skipping processing of Item "
                + dso.getID()
                + " (handle "
                + dso.getHandle()
                + "): Item is "
                + "withdrawn.");
        return;
      } catch (ItemNotDiscoverableException ex) {
        if (!(dso instanceof Item)) throw new IllegalStateException(ex.getMessage(), ex);
        report(
            "Skipping processing of Item "
                + dso.getID()
                + " (handle "
                + dso.getHandle()
                + "): Item is not "
                + "discoverable.");
        return;
      } catch (AuthorizeException ex) {
        report(
            "Skipping processing of "
                + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
                + " "
                + dso.getID()
                + " (handle "
                + dso.getHandle()
                + ")"
                + ", not authorized: "
                + ex.getMessage());
        return;
      }
    }

    if (dso instanceof Site) {
      List<Community> communities = communityService.findAllTop(context);
      for (Community community : communities) {
        this.dspaceDFS(community, callback, check, false);
      }
    }

    if (dso instanceof Community) {
      List<Community> subcommunities = ((Community) dso).getSubcommunities();
      for (Community sub : subcommunities) {
        this.dspaceDFS(sub, callback, check, false);
      }
      List<Collection> collections = ((Community) dso).getCollections();
      for (Collection collection : collections) {
        this.dspaceDFS(collection, callback, check, false);
      }
    }

    if (dso instanceof Collection) {
      Iterator<Item> items = itemService.findAllByCollection(context, (Collection) dso);
      while (items.hasNext()) {
        Item item = items.next();
        this.dspaceDFS(item, callback, check, false);
      }
    }

    //        Currently Bundles and Bitsreams aren't supported as independent entities.
    //        They should be converted as part of an item. So we do not need to make
    //        the recursive call for them. An item itself will be converted as part
    //        of the callback call below.
    //        The following code is left here for the day, we decide to also convert
    //        bundles and/or bitstreams.
    //
    //        if (dso instanceof Item)
    //        {
    //            Bundle[] bundles = ((Item) dso).getBundles();
    //            for (Bundle bundle : bundles)
    //            {
    //                this.dspaceDFS(bundle, callback, check, false);
    //            }
    //        }
    //
    //        if (dso instanceof Bundle)
    //        {
    //            Bitstream[] bistreams = ((Bundle) dso).getBitstreams();
    //            for (Bitstream bitstream : bistreams)
    //            {
    //                this.dspaceDFS(bitstream, callback, check, false);
    //            }
    //        }

    callback.callback(dso);
    report(
        "Processed "
            + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
            + " "
            + dso.getID()
            + " (handle "
            + dso.getHandle()
            + ").");
  }
  protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // dispense with simple service document requests
    String scope = request.getParameter("scope");
    if (scope != null && "".equals(scope)) {
      scope = null;
    }
    String path = request.getPathInfo();
    if (path != null && path.endsWith("description.xml")) {
      String svcDescrip = OpenSearch.getDescription(scope);
      response.setContentType(OpenSearch.getContentType("opensearchdescription"));
      response.setContentLength(svcDescrip.length());
      response.getWriter().write(svcDescrip);
      return;
    }

    // get enough request parameters to decide on action to take
    String format = request.getParameter("format");
    if (format == null || "".equals(format)) {
      // default to atom
      format = "atom";
    }

    // do some sanity checking
    if (!OpenSearch.getFormats().contains(format)) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    // then the rest - we are processing the query
    String query = request.getParameter("query");
    int start = Util.getIntParameter(request, "start");
    int rpp = Util.getIntParameter(request, "rpp");
    int sort = Util.getIntParameter(request, "sort_by");
    String order = request.getParameter("order");
    String sortOrder =
        (order == null || order.length() == 0 || order.toLowerCase().startsWith("asc"))
            ? SortOption.ASCENDING
            : SortOption.DESCENDING;

    QueryArgs qArgs = new QueryArgs();
    // can't start earlier than 0 in the results!
    if (start < 0) {
      start = 0;
    }
    qArgs.setStart(start);

    if (rpp > 0) {
      qArgs.setPageSize(rpp);
    }
    qArgs.setSortOrder(sortOrder);

    if (sort > 0) {
      try {
        qArgs.setSortOption(SortOption.getSortOption(sort));
      } catch (Exception e) {
        // invalid sort id - do nothing
      }
    }
    qArgs.setSortOrder(sortOrder);

    // Ensure the query is non-null
    if (query == null) {
      query = "";
    }

    // If there is a scope parameter, attempt to dereference it
    // failure will only result in its being ignored
    DSpaceObject container = (scope != null) ? HandleManager.resolveToObject(context, scope) : null;

    // Build log information
    String logInfo = "";

    // get the start of the query results page
    qArgs.setQuery(query);

    // Perform the search
    QueryResults qResults = null;
    if (container == null) {
      qResults = DSQuery.doQuery(context, qArgs);
    } else if (container instanceof Collection) {
      logInfo = "collection_id=" + container.getID() + ",";
      qResults = DSQuery.doQuery(context, qArgs, (Collection) container);
    } else if (container instanceof Community) {
      logInfo = "community_id=" + container.getID() + ",";
      qResults = DSQuery.doQuery(context, qArgs, (Community) container);
    }

    // now instantiate the results
    DSpaceObject[] results = new DSpaceObject[qResults.getHitHandles().size()];
    for (int i = 0; i < qResults.getHitHandles().size(); i++) {
      String myHandle = (String) qResults.getHitHandles().get(i);
      DSpaceObject dso = HandleManager.resolveToObject(context, myHandle);
      if (dso == null) {
        throw new SQLException("Query \"" + query + "\" returned unresolvable handle: " + myHandle);
      }
      results[i] = dso;
    }

    // Log
    log.info(
        LogManager.getHeader(
            context,
            "search",
            logInfo + "query=\"" + query + "\",results=(" + results.length + ")"));

    // format and return results
    Map<String, String> labelMap = getLabels(request);
    Document resultsDoc =
        OpenSearch.getResultsDoc(format, query, qResults, container, results, labelMap);
    try {
      Transformer xf = TransformerFactory.newInstance().newTransformer();
      response.setContentType(OpenSearch.getContentType(format));
      xf.transform(new DOMSource(resultsDoc), new StreamResult(response.getWriter()));
    } catch (TransformerException e) {
      log.error(e);
      throw new ServletException(e.toString());
    }
  }
Exemple #15
0
 protected boolean isProcessed(DSpaceObject dso) {
   return this.processed.contains(dso.getID());
 }
  @Override
  public void authorizeAction(
      Context c, EPerson e, 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];
      }

      UUID userid;

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

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

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

      if (e == null) {
        userid = null;
      } 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);
    }
  }
Exemple #17
0
  protected void runCLI(String[] args) {
    // prepare CLI and parse arguments
    Options options = createOptions();
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    try {
      line = parser.parse(options, args);
    } catch (ParseException ex) {
      usage(options);
      System.err.println();
      System.err.println(ex.getMessage());
      log.fatal(ex);
      System.exit(1);
    }

    String[] remainingArgs = line.getArgs();
    if (remainingArgs.length > 0) {
      this.usage(options);
      System.err.println();
      StringBuilder builder = new StringBuilder(100);
      for (String argument : remainingArgs) {
        if (builder.length() > 0) builder.append(", ");
        builder.append(argument);
      }
      String argumentsLine = builder.toString().trim();
      System.err.print("Cannot recognize the following argument");
      if (remainingArgs.length >= 2) System.err.print("s");
      System.err.println(": " + argumentsLine + ".");
      System.exit(1);
    }

    // set member variables depending on CLI arguments.
    if (line.hasOption("verbose")) {
      setVerbose(true);
    }

    if (line.hasOption("dry-run")) {
      setDryrun(true);
    }

    if (line.hasOption("stdout")) {
      setStdout(true);
    }

    // check mutual exclusive arguments
    if (line.hasOption("delete") && line.hasOption("delete-all")) {
      usage(options);
      System.err.println(
          "\n\nYou cannot use the options --delete <handle> " + "and --delete-all together.");
      System.exit(1);
    }

    if (line.hasOption("convert-all")
        && (line.hasOption("delete") || line.hasOption("delete-all"))) {
      usage(options);
      System.err.println(
          "\n\nYou cannot use the option --convert-all "
              + "together with --delete or --delete-all.");
      System.exit(1);
    }
    if (line.hasOption("identifiers")
        && (line.hasOption("delete") || line.hasOption("delete-all"))) {
      usage(options);
      System.err.println(
          "\n\nYou cannot use the option --identifiers <handle> "
              + "together with --delete or --delete-all.");
      System.exit(1);
    }
    if (line.hasOption("stdout") && (line.hasOption("delete") || line.hasOption("delete-all"))) {
      usage(options);
      System.err.println(
          "\n\nYou cannot use the option --stdout together " + "with --delete or --deleta-all.");
      System.exit(1);
    }

    // Run commands depending on CLI arguments.
    // process help first to prevent further evaluation of given options.
    if (line.hasOption('h')) {
      usage(options);
      System.exit(0);
    }

    if (line.hasOption("delete")) {
      String[] identifiers = line.getOptionValues("delete");
      for (String identifier : identifiers) {
        if (!StringUtils.startsWithIgnoreCase(identifier, "hdl:")) {
          if (!this.dryrun) {
            storage.delete(identifier);
          }
          if (this.verbose) {
            System.err.println("Deleted " + identifier + ".");
          }
          continue;
        }
        String handle = identifier.substring(4);

        log.debug("Trying to resolve identifier " + handle + ".");

        DSpaceObject dso = resolveHandle(handle);
        if (dso == null) {
          // resolveHandle reports problems and return null in case
          // of an error or an unresolvable handle.
          // Don't report it a second time, just continue...
          continue;
        }

        log.debug(
            "Resolved identifier "
                + handle
                + " as "
                + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
                + " "
                + dso.getID());

        try {
          this.delete(dso, true);
        } catch (SQLException ex) {
          log.error(ex);
          System.err.println(
              "A problem with the database connection " + "occurred. Canceled pending actions.");
          System.err.println(ex.getMessage());
          ex.printStackTrace(System.err);
          System.exit(1);
        }
      }
      System.exit(0);
    }

    if (line.hasOption("delete-all")) {
      this.deleteAll();
      System.exit(0);
    }

    if (line.hasOption("identifiers")) {
      String[] identifiers = line.getOptionValues("identifiers");
      report("Starting conversion of specified DSpaceObjects...");

      this.processed.clear();
      for (String handle : identifiers) {
        log.debug("Trying to resolve identifier " + handle + ".");

        DSpaceObject dso = resolveHandle(handle);
        if (dso == null) {
          // resolveHandle reports problems and return null in case
          // of an error or an unresolvable handle.
          // Don't report it a second time, just continue...
          continue;
        }

        try {
          this.convert(dso, false);
        } catch (SQLException ex) {
          log.error(ex);
          System.err.println(
              "A problem with the database connection " + "occurred. Canceled pending actions.");
          System.err.println(ex.getMessage());
          ex.printStackTrace(System.err);
          System.exit(1);
        }
      }
      report("Conversion ended.");
      System.exit(0);
    }

    if (line.hasOption("convert-all")) {
      try {
        this.convertAll();
      } catch (SQLException ex) {
        log.error(ex);
        System.err.println(
            "A problem with the database connection " + "occurred. Canceled pending actions.");
        System.err.println(ex.getMessage());
        ex.printStackTrace(System.err);
        System.exit(1);
      }
      System.exit(0);
    }

    this.usage(options);
    System.exit(0);
  }