/**
   * See which items are possible to get the backup file from cloud.
   *
   * @param context DSpace context
   * @param item iterator of items
   * @return integer set with all the IDs Items that are possible to get the backup file from cloud
   */
  public Set<Integer> checkPossibleItemsGet(Context context, ItemIterator items) {
    // This will contain all the Items IDs that backup files could be get from cloud
    Set<Integer> setInfo = new HashSet<Integer>();

    try {
      // if exist some item to evaluate make the connection and
      // get items backups files in cloud
      if (items.hasNext() == true) {
        this.makeConnection();
        this.filesInCloud.putAll(this.newCloudConnection.getInfoFilesIn(Constants.ITEM));
      }

      // do the operation for all items
      while (items.hasNext() == true) {
        Item objItem = items.next();
        // check if it is possible and necessary to get a backup file from cloud
        Boolean checkCorrect = this.couldGetFileFromCloud(context, objItem.getID(), Constants.ITEM);
        // add the ID collection to set if correct
        if (checkCorrect == true) setInfo.add(objItem.getID());
      }

      // close the connection to cloud
      this.closeConnection();

    } catch (SQLException ex) {
      Logger.getLogger(ActualContentManagement.class.getName()).log(Level.SEVERE, null, ex);
    }

    return setInfo;
  }
 /* (non-Javadoc)
  * @see org.dspace.app.dav.DAVResource#children()
  */
 @Override
 protected DAVResource[] children() throws SQLException {
   Vector result = new Vector();
   ItemIterator ii = this.collection.getItems();
   while (ii.hasNext()) {
     Item item = ii.next();
     result.add(new DAVItem(this.context, this.request, this.response, makeChildPath(item), item));
   }
   return (DAVResource[]) result.toArray(new DAVResource[result.size()]);
 }
  /**
   * Send a collection backup file and respective children to cloud to be preserved.
   *
   * @param context context DSpace
   * @param ref ID of the collection
   * @param establishConnection true if pretend establish connection to cloud
   * @return true if file correctly sent to cloud, or false if not
   */
  public Boolean sendCollectionAndChilds(
      Context context, Integer ref, Boolean establishConnection) {
    // if first, make connection and get collection and item files preserved in cloud
    if (establishConnection == true) {
      this.makeConnection();
      this.filesInCloud.putAll(this.newCloudConnection.getInfoFilesIn(Constants.COLLECTION));
      this.filesInCloud.putAll(this.newCloudConnection.getInfoFilesIn(Constants.ITEM));
    }

    // send to cloud atual collection
    sendCollection(context, ref, false);

    Collection obj;
    ItemIterator items;

    // get the items presents in the collection
    try {
      obj = Collection.find(context, ref);
      items = obj.getAllItems();
    } catch (Exception ex) {
      Logger.getLogger(ActualContentManagement.class.getName()).log(Level.SEVERE, null, ex);
      // it means it is the first father in the order, so close connection
      if (establishConnection == true) this.closeConnection();
      return false;
    }

    // send to cloud, one by one, each item
    try {
      if (items.hasNext()) {
        Item newObj = items.next();
        sendItem(context, newObj.getID(), false);
      }
    } catch (Exception ex) {
      Logger.getLogger(ActualContentManagement.class.getName()).log(Level.SEVERE, null, ex);
      // it means it is the first father in the order, so close connection
      if (establishConnection == true) this.closeConnection();
      return false;
    }

    // it means it is the first father in the order
    if (establishConnection == true) this.closeConnection();

    return true;
  }
  /**
   * @param args
   * @throws SQLException
   * @throws IOException
   * @throws AuthorizeException
   */
  public static void main(String[] args) throws SQLException, AuthorizeException, IOException {

    Context ctx = new Context();
    ctx.setIgnoreAuthorization(true);
    ItemIterator iter = Item.findAll(ctx);

    Properties props = new Properties();

    File processed = new File("license.processed");

    if (processed.exists()) props.load(new FileInputStream(processed));

    int i = 0;

    try {
      while (iter.hasNext()) {
        if (i == 100) {
          props.store(
              new FileOutputStream(processed),
              "processed license files, remove to restart processing from scratch");
          i = 0;
        }

        Item item = (Item) iter.next();
        log.info("checking: " + item.getID());
        if (!props.containsKey("I" + item.getID())) {
          handleItem(item);
          log.info("processed: " + item.getID());
        }

        item.decache();
        props.put("I" + item.getID(), "done");
        i++;
      }

    } finally {
      props.store(
          new FileOutputStream(processed),
          "processed license files, remove to restart processing from scratch");
    }
  }
  /**
   * 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";
  }
  /**
   * Purge the collection of all items, then run a fresh harvest cycle.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @param request the Cocoon request object
   * @return A process result's object.
   * @throws TransformerException
   * @throws SAXException
   * @throws ParserConfigurationException
   * @throws CrosswalkException
   * @throws BrowseException
   */
  public static FlowResult processReimportCollection(
      Context context, int collectionID, Request request)
      throws SQLException, IOException, AuthorizeException, CrosswalkException,
          ParserConfigurationException, SAXException, TransformerException, BrowseException {
    Collection collection = Collection.find(context, collectionID);
    HarvestedCollection hc = HarvestedCollection.find(context, collectionID);

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

    return processRunCollectionHarvest(context, collectionID, request);
  }
 public static void applyFiltersCollection(Context c, Collection collection) throws Exception {
   ItemIterator i = collection.getItems();
   while (i.hasNext() && processed < max2Process) {
     applyFiltersItem(c, i.next());
   }
 }
 public static void applyFiltersAllItems(Context c) throws Exception {
   ItemIterator i = Item.findAll(c);
   while (i.hasNext() && processed < max2Process) {
     applyFiltersItem(c, i.next());
   }
 }
  /**
   * Get a list of all the items that the current SWORD context will allow deposit onto in the given
   * DSpace context
   *
   * <p>IF: the authenticated user is an administrator AND: (the on-behalf-of user is an
   * administrator OR the on-behalf-of user is authorised to WRITE on the item and ADD on the
   * ORIGINAL bundle OR the on-behalf-of user is null) OR IF: the authenticated user is authorised
   * to WRITE on the item and ADD on the ORIGINAL bundle AND: (the on-behalf-of user is an
   * administrator OR the on-behalf-of user is authorised to WRITE on the item and ADD on the
   * ORIGINAL bundle OR the on-behalf-of user is null)
   *
   * @param swordContext
   * @return the array of allowed collections
   * @throws DSpaceSwordException
   */
  public List<Item> getAllowedItems(
      SwordContext swordContext, org.dspace.content.Collection collection)
      throws DSpaceSwordException {
    // an item is allowed if the following conditions are met
    //
    // - the authenticated user is an administrator
    // -- the on-behalf-of user is an administrator
    // -- the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
    // -- the on-behalf-of user is null
    // - the authenticated user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
    // -- the on-behalf-of user is an administrator
    // -- the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle
    // -- the on-behalf-of user is null

    try {
      List<Item> allowed = new ArrayList<Item>();
      ItemIterator ii = collection.getItems();

      while (ii.hasNext()) {
        Item item = ii.next();

        boolean authAllowed = false;
        boolean oboAllowed = false;

        // check for obo null
        if (swordContext.getOnBehalfOf() == null) {
          oboAllowed = true;
        }

        // get the "ORIGINAL" bundle(s)
        Bundle[] bundles = item.getBundles("ORIGINAL");

        // look up the READ policy on the community.  This will include determining if the user is
        // an administrator
        // so we do not need to check that separately
        if (!authAllowed) {
          boolean write =
              AuthorizeManager.authorizeActionBoolean(
                  swordContext.getAuthenticatorContext(), item, Constants.WRITE);

          boolean add = false;
          if (bundles.length == 0) {
            add =
                AuthorizeManager.authorizeActionBoolean(
                    swordContext.getAuthenticatorContext(), item, Constants.ADD);
          } else {
            for (int i = 0; i < bundles.length; i++) {
              add =
                  AuthorizeManager.authorizeActionBoolean(
                      swordContext.getAuthenticatorContext(), bundles[i], Constants.ADD);
              if (!add) {
                break;
              }
            }
          }

          authAllowed = write && add;
        }

        // if we have not already determined that the obo user is ok to submit, look up the READ
        // policy on the
        // community.  THis will include determining if the user is an administrator.
        if (!oboAllowed) {
          boolean write =
              AuthorizeManager.authorizeActionBoolean(
                  swordContext.getOnBehalfOfContext(), item, Constants.WRITE);

          boolean add = false;
          if (bundles.length == 0) {
            add =
                AuthorizeManager.authorizeActionBoolean(
                    swordContext.getAuthenticatorContext(), item, Constants.ADD);
          } else {
            for (int i = 0; i < bundles.length; i++) {
              add =
                  AuthorizeManager.authorizeActionBoolean(
                      swordContext.getAuthenticatorContext(), bundles[i], Constants.ADD);
              if (!add) {
                break;
              }
            }
          }

          oboAllowed = write && add;
        }

        // final check to see if we are allowed to READ
        if (authAllowed && oboAllowed) {
          allowed.add(item);
        }
      }

      return allowed;
    } catch (SQLException e) {
      throw new DSpaceSwordException(e);
    }
  }
Beispiel #10
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();
  }
Beispiel #11
0
  /**
   * Return array of items in collection. You can add more properties to items with expand
   * parameter.
   *
   * @param collectionId Id of collection in DSpace.
   * @param expand String which define, what additional properties will be in returned item. Options
   *     are separeted by commas and are: "all", "metadata", "parentCollection",
   *     "parentCollectionList", "parentCommunityList" and "bitstreams".
   * @param limit Limit value for items in array. Default value is 100.
   * @param offset Offset of start index in array of items of collection. Default value is 0.
   * @param headers If you want to access to collection under logged user into context. In headers
   *     must be set header "rest-dspace-token" with passed token from login method.
   * @return Return array of items, on which has logged user permission to read. It can also return
   *     status code NOT_FOUND(404) if id of collection is incorrect or status code UNATHORIZED(401)
   *     if user has no permission to read collection.
   * @throws WebApplicationException It is thrown when was problem with database reading
   *     (SQLException) or problem with creating context(ContextException). It is thrown by
   *     NOT_FOUND and UNATHORIZED status codes, too.
   */
  @GET
  @Path("/{collection_id}/items")
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public org.dspace.rest.common.Item[] getCollectionItems(
      @PathParam("collection_id") Integer collectionId,
      @QueryParam("expand") String expand,
      @QueryParam("limit") @DefaultValue("100") Integer limit,
      @QueryParam("offset") @DefaultValue("0") Integer offset,
      @QueryParam("userIP") String user_ip,
      @QueryParam("userAgent") String user_agent,
      @QueryParam("xforwarderfor") String xforwarderfor,
      @Context HttpHeaders headers,
      @Context HttpServletRequest request)
      throws WebApplicationException {

    log.info("Reading collection(id=" + collectionId + ") items.");
    org.dspace.core.Context context = null;
    List<Item> items = null;

    try {
      context = createContext(getUser(headers));

      org.dspace.content.Collection dspaceCollection =
          findCollection(context, collectionId, org.dspace.core.Constants.READ);
      writeStats(
          dspaceCollection,
          UsageEvent.Action.VIEW,
          user_ip,
          user_agent,
          xforwarderfor,
          headers,
          request,
          context);

      items = new ArrayList<Item>();
      org.dspace.content.ItemIterator dspaceItems = dspaceCollection.getItems();
      for (int i = 0; (dspaceItems.hasNext()) && (i < (limit + offset)); i++) {
        if (i >= offset) {
          org.dspace.content.Item dspaceItem = dspaceItems.next();
          if (AuthorizeManager.authorizeActionBoolean(
              context, dspaceItem, org.dspace.core.Constants.READ)) {
            items.add(new Item(dspaceItem, expand, context));
            writeStats(
                dspaceItem,
                UsageEvent.Action.VIEW,
                user_ip,
                user_agent,
                xforwarderfor,
                headers,
                request,
                context);
          }
        }
      }

      context.complete();
    } catch (SQLException e) {
      processException("Could not read collection items, SQLException. Message: " + e, context);
    } catch (ContextException e) {
      processException(
          "Could not read collection items, ContextException. Message: " + e.getMessage(), context);
    } finally {
      processFinally(context);
    }

    log.trace("All items in collection(id=" + collectionId + ") were successfully read.");
    return items.toArray(new Item[0]);
  }