/**
   * 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;
  }
  /**
   * 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;
  }
  // Create workflow start provenance message
  protected void recordStart(Context context, Item myitem)
      throws SQLException, IOException, AuthorizeException {
    // get date
    DCDate now = DCDate.getCurrent();

    // Create provenance description
    String provmessage;

    if (myitem.getSubmitter() != null) {
      provmessage =
          "Submitted by "
              + myitem.getSubmitter().getFullName()
              + " ("
              + myitem.getSubmitter().getEmail()
              + ") on "
              + now.toString()
              + "\n";
    } else
    // null submitter
    {
      provmessage = "Submitted by unknown (probably automated) on" + now.toString() + "\n";
    }

    // add sizes and checksums of bitstreams
    provmessage += installItemService.getBitstreamProvenanceMessage(context, myitem);

    // Add message to the DC
    itemService.addMetadata(
        context, myitem, MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provmessage);
    itemService.update(context, myitem);
  }
  /**
   * Perform a database query to obtain the string array of values corresponding to the passed
   * parameters. This is only really called from <code>
   * getMetadata(schema, element, qualifier, lang);
   * </code> which will obtain the value from cache if available first.
   *
   * @param schema
   * @param element
   * @param qualifier
   * @param lang
   */
  @Override
  public List<DCValue> getMetadata(
      Item item, String schema, String element, String qualifier, String lang) {
    List<DCValue> metadata = new ArrayList<DCValue>();
    try {
      TableRowIterator tri;

      if (qualifier == null) {
        Object[] params = {item.getID(), element, schema};
        tri = DatabaseManager.query(context, getByMetadataElement, params);
      } else if (Item.ANY.equals(qualifier)) {
        Object[] params = {item.getID(), element, schema};
        tri = DatabaseManager.query(context, getByMetadataAnyQualifier, params);
      } else {
        Object[] params = {item.getID(), element, qualifier, schema};
        tri = DatabaseManager.query(context, getByMetadata, params);
      }

      while (tri.hasNext()) {
        TableRow tr = tri.next();
        DCValue dcv = new DCValue();
        dcv.schema = schema;
        dcv.element = element;
        dcv.qualifier = qualifier;
        dcv.language = lang;
        dcv.value = tr.getStringColumn("text_value");
        metadata.add(dcv);
      }
    } catch (SQLException sqle) {
      throw new RuntimeException(sqle);
    }
    return metadata;
  }
  /**
   * 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;
  }
Example #6
0
  protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    Integer itemID = UIUtil.getIntParameter(request, "itemID");
    Item item = Item.find(context, itemID);
    String submit = UIUtil.getSubmitButton(request, "submit");
    if (submit != null && submit.equals("submit")) {
      request.setAttribute("itemID", itemID);
      JSPManager.showJSP(request, response, "/tools/version-summary.jsp");
      return;
    }

    String summary = request.getParameter("summary");
    if (submit != null && submit.equals("submit_version")) {
      Integer wsid = VersionUtil.processCreateNewVersion(context, itemID, summary);
      response.sendRedirect(request.getContextPath() + "/submit?resume=" + wsid);
      context.complete();
      return;
    } else if (submit != null && submit.equals("submit_update_version")) {
      String versionID = request.getParameter("versionID");
      request.setAttribute("itemID", itemID);
      request.setAttribute("versionID", versionID);
      JSPManager.showJSP(request, response, "/tools/version-update-summary.jsp");
      return;
    }

    // Send us back to the item page if we cancel !
    response.sendRedirect(request.getContextPath() + "/handle/" + item.getHandle());
    context.complete();
  }
  /**
   * 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;
  }
Example #8
0
  /**
   * Remove a file from an item
   *
   * @param context current DSpace context
   * @param item Item where file should be removed from
   * @param bitstreamID The id of bitstream representing the file to remove
   * @return Status or error flag which will be processed by UI-related code! (if STATUS_COMPLETE or
   *     0 is returned, no errors occurred!)
   */
  protected int processRemoveFile(Context context, Item item, int bitstreamID)
      throws IOException, SQLException, AuthorizeException {
    Bitstream bitstream;

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

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

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

    bundles[0].removeBitstream(bitstream);

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

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

    // no errors occurred
    return STATUS_COMPLETE;
  }
  private List disseminateListInternal(DSpaceObject dso, boolean addSchema)
      throws CrosswalkException, IOException, SQLException, AuthorizeException {
    if (dso.getType() != Constants.ITEM)
      throw new CrosswalkObjectNotSupported(
          "MODSDisseminationCrosswalk can only crosswalk an Item.");
    Item item = (Item) dso;
    initMap();

    MetadataValue[] dc = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
    List result = new ArrayList(dc.length);
    for (int i = 0; i < dc.length; i++) {
      // Compose qualified DC name - schema.element[.qualifier]
      // e.g. "dc.title", "dc.subject.lcc", "lom.Classification.Keyword"
      String qdc =
          dc[i].getMetadataField().getSchema()
              + "."
              + ((dc[i].getMetadataField().getQualifier() == null)
                  ? dc[i].getMetadataField().getElement()
                  : (dc[i].getMetadataField().getElement()
                      + "."
                      + dc[i].getMetadataField().getQualifier()));

      modsTriple trip = (modsTriple) modsMap.get(qdc);
      if (trip == null)
        log.warn("WARNING: " + getPluginInstanceName() + ": No MODS mapping for \"" + qdc + "\"");
      else {
        try {
          Element me = (Element) trip.xml.clone();
          if (addSchema) me.setAttribute("schemaLocation", schemaLocation, XSI_NS);
          Iterator ni = trip.xpath.selectNodes(me).iterator();
          if (!ni.hasNext())
            log.warn(
                "XPath \""
                    + trip.xpath.getXPath()
                    + "\" found no elements in \""
                    + outputUgly.outputString(me)
                    + "\", qdc="
                    + qdc);
          while (ni.hasNext()) {
            Object what = ni.next();
            if (what instanceof Element) ((Element) what).setText(dc[i].getValue());
            else if (what instanceof Attribute) ((Attribute) what).setValue(dc[i].getValue());
            else if (what instanceof Text) ((Text) what).setText(dc[i].getValue());
            else log.warn("Got unknown object from XPath, class=" + what.getClass().getName());
          }
          result.add(me);
        } catch (JDOMException je) {
          log.error(
              "Error following XPath in modsTriple: context="
                  + outputUgly.outputString(trip.xml)
                  + ", xpath="
                  + trip.xpath.getXPath()
                  + ", exception="
                  + je.toString());
        }
      }
    }
    return result;
  }
Example #10
0
 /**
  * Return pathname element to this Item. Use db-id format if no handle, otherwise the DSpace
  * object format.
  *
  * @param item the item
  * @return the path elt
  */
 protected static String getPathElt(Item item) {
   String handle = item.getHandle();
   if (handle == null) {
     return getPathElt(item.getID());
   } else {
     return DAVDSpaceObject.getPathElt(item);
   }
 }
Example #11
0
  /**
   * each entry represents a bitstream....
   *
   * @param c
   * @param i
   * @param path
   * @param fileName
   * @param bundleName
   * @throws SQLException
   * @throws IOException
   * @throws AuthorizeException
   */
  private void processContentFileEntry(
      Context c, Item i, String path, String fileName, String bundleName, boolean primary)
      throws SQLException, IOException, AuthorizeException {
    String fullpath = path + File.separatorChar + fileName;

    // get an input stream
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fullpath));

    Bitstream bs = null;
    String newBundleName = bundleName;

    if (bundleName == null) {
      // is it license.txt?
      if ("license.txt".equals(fileName)) {
        newBundleName = "LICENSE";
      } else {
        // call it ORIGINAL
        newBundleName = "ORIGINAL";
      }
    }

    if (!isTest) {
      // find the bundle
      Bundle[] bundles = i.getBundles(newBundleName);
      Bundle targetBundle = null;

      if (bundles.length < 1) {
        // not found, create a new one
        targetBundle = i.createBundle(newBundleName);
      } else {
        // put bitstreams into first bundle
        targetBundle = bundles[0];
      }

      // now add the bitstream
      bs = targetBundle.createBitstream(bis);

      bs.setName(fileName);

      // Identify the format
      // FIXME - guessing format guesses license.txt incorrectly as a text
      // file format!
      BitstreamFormat bf = FormatIdentifier.guessFormat(c, bs);
      bs.setFormat(bf);

      // Is this a the primary bitstream?
      if (primary) {
        targetBundle.setPrimaryBitstreamID(bs.getID());
        targetBundle.update();
      }

      bs.update();
    }

    bis.close();
  }
  /**
   * get the title of the item in this workflow
   *
   * @param wi the workflow item object
   */
  public static String getItemTitle(WorkflowItem wi) throws SQLException {
    Item myitem = wi.getItem();
    DCValue[] titles = myitem.getDC("title", null, Item.ANY);

    // only return the first element, or "Untitled"
    if (titles.length > 0) {
      return titles[0].value;
    } else {
      return I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled ");
    }
  }
  @Override
  public String getItemTitle(BasicWorkflowItem wi) throws SQLException {
    Item myitem = wi.getItem();
    String title = myitem.getName();

    // only return the first element, or "Untitled"
    if (StringUtils.isNotBlank(title)) {
      return title;
    } else {
      return I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled ");
    }
  }
Example #14
0
  @Override
  public int perform(DSpaceObject dso) throws IOException {
    status = Curator.CURATE_SKIP;
    logDebugMessage("The target dso is " + dso.getName());
    if (dso instanceof Item) {
      status = Curator.CURATE_SUCCESS;
      Item item = (Item) dso;
      try {
        openSession();
      } catch (IOException ioE) {
        // no point going further - set result and error out
        closeSession();
        setResult(CONNECT_FAIL_MESSAGE);
        return Curator.CURATE_ERROR;
      }

      try {
        Bundle bundle = item.getBundles("ORIGINAL")[0];
        results = new ArrayList<String>();
        for (Bitstream bitstream : bundle.getBitstreams()) {
          InputStream inputstream = bitstream.retrieve();
          logDebugMessage("Scanning " + bitstream.getName() + " . . . ");
          int bstatus = scan(bitstream, inputstream, getItemHandle(item));
          inputstream.close();
          if (bstatus == Curator.CURATE_ERROR) {
            // no point going further - set result and error out
            setResult(SCAN_FAIL_MESSAGE);
            status = bstatus;
            break;
          }
          if (failfast && bstatus == Curator.CURATE_FAIL) {
            status = bstatus;
            break;
          } else if (bstatus == Curator.CURATE_FAIL && status == Curator.CURATE_SUCCESS) {
            status = bstatus;
          }
        }
      } catch (AuthorizeException authE) {
        throw new IOException(authE.getMessage(), authE);
      } catch (SQLException sqlE) {
        throw new IOException(sqlE.getMessage(), sqlE);
      } finally {
        closeSession();
      }

      if (status != Curator.CURATE_ERROR) {
        formatResults(item);
      }
    }
    return status;
  }
Example #15
0
  private static List<Integer> GetIds(
      Context context, int dateId, Type type, String param, String beginY, String endY)
      throws SQLException {
    String subQuery = null;
    int typeId = Item.returnId(context, "type", "");
    String begin = "";
    String end = "";
    begin += beginY + "-01-01";
    end += endY + "-12-31";

    // Different subqueries for different types
    if (type == Type.COLLECTION) {
      subQuery = "(SELECT item_id FROM collection2item WHERE collection_id = ?) a";
    } else if (type == Type.AUTHOR) {
      subQuery =
          "(SELECT item_id FROM metadatavalue WHERE metadata_field_id = ? AND text_value = ?) a";
    }

    // Main query
    String query =
        "SELECT item.item_id FROM item,handle, "
            + "(SELECT metadata_value_id ,metadatavalue.item_id,metadatavalue.text_value FROM metadatavalue WHERE metadatavalue.text_value >= ? AND metadatavalue.text_value <= ? AND metadata_field_id = ? "
            + "ORDER BY metadatavalue.text_value DESC) e, (SELECT item_id, metadatavalue.text_value FROM metadatavalue WHERE metadata_field_id = ?) g, "
            + subQuery
            + " WHERE g.item_id = item.item_id AND a.item_id = item.item_id AND item.item_id = e.item_id AND item.item_id = handle.resource_id AND "
            + "handle.resource_type_id = 2 AND in_archive AND NOT withdrawn ORDER BY e.text_value DESC, g.text_value";
    List<Integer> ids = new ArrayList<Integer>();

    PreparedStatement statement = context.getDBConnection().prepareStatement(query);
    statement.setString(1, begin); // fill in boundries
    statement.setString(2, end);
    statement.setInt(3, dateId); // fill in dateId
    statement.setInt(4, typeId); // fill in type id

    // Fill in the given parameters depending on type, add custom types here incase needed!
    if (type == Type.COLLECTION) {
      int col = Integer.parseInt(param);
      statement.setInt(5, col);
    } else if (type == Type.AUTHOR) {
      int id = Item.returnId(context, "contributor", "author");
      statement.setInt(5, id);
      statement.setString(6, param);
    }
    ResultSet rs = statement.executeQuery();

    int i = 0;
    while (rs.next()) {
      ids.add(rs.getInt("item_id"));
    }
    return ids;
  }
Example #16
0
  /**
   * Do the work of "copy" method; this code is shared with e.g. DAVInProgressSubmission.
   *
   * @param context the context
   * @param item the item
   * @param destination the destination
   * @param overwrite the overwrite
   * @return HTTP status code.
   * @throws DAVStatusException the DAV status exception
   * @throws SQLException the SQL exception
   * @throws AuthorizeException the authorize exception
   * @throws IOException Signals that an I/O exception has occurred.
   */
  protected static int addItemToCollection(
      Context context, Item item, DAVResource destination, boolean overwrite)
      throws DAVStatusException, SQLException, AuthorizeException, IOException {
    // sanity checks
    if (!(destination instanceof DAVCollection)) {
      throw new DAVStatusException(
          HttpServletResponse.SC_METHOD_NOT_ALLOWED,
          "COPY of Item is only allowed when destination is a DSpace Collection.");
    }

    // access check
    AuthorizeManager.authorizeAction(context, item, Constants.READ);

    // make sure item doesn't belong to this collection
    Collection destColl = ((DAVCollection) destination).getCollection();

    log.debug(
        "COPY from="
            + item.toString()
            + " ("
            + item.getHandle()
            + "), to="
            + destColl.toString()
            + " ("
            + destColl.getHandle()
            + ")");

    // check if it's already a member
    Collection refs[] = item.getCollections();
    for (Collection element : refs) {
      if (destColl.equals(element)) {
        log.debug(
            "COPY - item @ "
                + item.getHandle()
                + " is already a member of collection @ "
                + destColl.getHandle());
        if (overwrite) {
          return DAV.SC_NO_CONTENT;
        } else {
          throw new DAVStatusException(
              DAV.SC_CONFLICT,
              "This Item is already a member of collection handle=" + destColl.getHandle());
        }
      }
    }

    destColl.addItem(item);
    return DAV.SC_NO_CONTENT;
  }
  /**
   * Add the current date to the item metadata. This looks up the field in which to store this
   * metadata in the configuration sword.updated.field
   *
   * @param item
   * @throws DSpaceSwordException
   */
  protected void setUpdatedDate(Item item, VerboseDescription verboseDescription)
      throws DSpaceSwordException {
    String field = ConfigurationManager.getProperty("swordv2-server", "updated.field");
    if (field == null || "".equals(field)) {
      throw new DSpaceSwordException(
          "No configuration, or configuration is invalid for: sword.updated.field");
    }

    MDValue dc = this.configToDC(field, null);
    item.clearMetadata(dc.getSchema(), dc.getElement(), dc.getQualifier(), MDValue.ANY);
    item.addMetadata(
        dc.getSchema(), dc.getElement(), dc.getQualifier(), null, Utils.asISO8601(new Date()));

    verboseDescription.append("Updated date added to response from item metadata where available");
  }
Example #18
0
  public void addListPolicies(List parent, DSpaceObject dso, Collection owningCollection)
      throws WingException, SQLException {
    if (!isAdvancedFormEnabled) {
      return;
    }
    parent.addLabel(T_head_policies_table);

    java.util.List<ResourcePolicy> resourcePolicies =
        authorizeService.findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM);
    if (resourcePolicies.isEmpty()) {
      parent.addItem(T_no_policies);
      return;
    }

    for (ResourcePolicy rp : resourcePolicies) {
      int id = rp.getID();

      String name = "";
      if (rp.getRpName() != null) name = rp.getRpName();

      String action = resourcePolicyService.getActionText(rp);

      // if it is the default policy for the Submitter don't show it.
      if (dso instanceof org.dspace.content.Item) {
        org.dspace.content.Item item = (org.dspace.content.Item) dso;
        if (rp.getEPerson() != null) {
          if (item.getSubmitter().equals(rp.getEPerson())) continue;
        }
      }

      String group = "";
      if (rp.getGroup() != null) group = rp.getGroup().getName();

      // start
      String startDate = "";
      if (rp.getStartDate() != null) {
        startDate = DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd");
      }

      // endDate
      String endDate = "";
      if (rp.getEndDate() != null) {
        endDate = DateFormatUtils.format(rp.getEndDate(), "yyyy-MM-dd");
      }

      parent.addItem(T_policy.parameterize(name, action, group, startDate, endDate));
    }
  }
  private boolean isEmbargoed(Context context, Item item) throws Exception {
    // if an embargo field isn't configured, then the item can't be embargoed
    String liftDateField = ConfigurationManager.getProperty("embargo.field.lift");
    if (liftDateField == null) {
      return false;
    }

    // if there is no embargo value, the item isn't embargoed
    DCValue[] embargoes = item.getMetadata(liftDateField);
    if (embargoes.length == 0) {
      return false;
    }

    // if the embargo date is in the past, then the item isn't embargoed
    try {
      DCDate embargoDate = EmbargoManager.getEmbargoTermsAsDate(context, item);
      if ((new Date()).getTime() > embargoDate.toDate().getTime()) {
        return false;
      }
    } catch (SQLException e) {
      throw new Exception(e);
    } catch (AuthorizeException e) {
      throw new Exception(e);
    } catch (IOException e) {
      throw new Exception(e);
    }

    return true;
  }
Example #20
0
  @Override
  public void setEmbargo(Context context, Item item) throws SQLException, AuthorizeException {
    // if lift is null, we might be restoring an item from an AIP
    DCDate myLift = getEmbargoTermsAsDate(context, item);
    if (myLift == null) {
      if ((myLift = recoverEmbargoDate(item)) == null) {
        return;
      }
    }
    String slift = myLift.toString();
    boolean ignoreAuth = context.ignoreAuthorization();
    try {
      context.setIgnoreAuthorization(true);
      itemService.clearMetadata(context, item, lift_schema, lift_element, lift_qualifier, Item.ANY);
      itemService.addMetadata(
          context, item, lift_schema, lift_element, lift_qualifier, null, slift);
      log.info("Set embargo on Item " + item.getHandle() + ", expires on: " + slift);

      setter.setEmbargo(context, item);

      itemService.update(context, item);
    } finally {
      context.setIgnoreAuthorization(ignoreAuth);
    }
  }
  /**
   * Attempt to filter a bitstream
   *
   * <p>An exception will be thrown if the media filter class cannot be instantiated, exceptions
   * from filtering will be logged to STDOUT and swallowed.
   *
   * @return true if bitstream processed, false if no applicable filter or already processed
   */
  public static boolean filterBitstream(Context c, Item myItem, Bitstream myBitstream)
      throws Exception {
    boolean filtered = false;

    // iterate through filter classes. A single format may be actioned
    // by more than one filter
    for (int i = 0; i < filterClasses.length; i++) {
      List fmts = (List) filterFormats.get(filterClasses[i].getClass().getName());
      if (fmts.contains(myBitstream.getFormat().getShortDescription())) {
        try {
          // only update item if bitstream not skipped
          if (filterClasses[i].processBitstream(c, myItem, myBitstream)) {
            myItem.update(); // Make sure new bitstream has a sequence
            // number
            filtered = true;
          }
        } catch (Exception e) {
          System.out.println(
              "ERROR filtering, skipping bitstream #" + myBitstream.getID() + " " + e);
          e.printStackTrace();
        }
      }
    }
    return filtered;
  }
Example #22
0
  private void deleteItems(Context c, String mapFile) throws Exception {
    System.out.println("Deleting items listed in mapfile: " + mapFile);

    // read in the mapfile
    Map<String, String> myhash = readMapFile(mapFile);

    // now delete everything that appeared in the mapFile
    Iterator<String> i = myhash.keySet().iterator();

    while (i.hasNext()) {
      String itemID = myhash.get(i.next());

      if (itemID.indexOf('/') != -1) {
        String myhandle = itemID;
        System.out.println("Deleting item " + myhandle);
        deleteItem(c, myhandle);
      } else {
        // it's an ID
        Item myitem = Item.find(c, Integer.parseInt(itemID));
        System.out.println("Deleting item " + itemID);
        deleteItem(c, myitem);
      }
      c.clearCache();
    }
  }
  /**
   * For a bitstream that's a thumbnail or extracted text, find the corresponding bitstream it was
   * derived from, in the ORIGINAL bundle.
   *
   * @param item the item we're dealing with
   * @param derived the derived bitstream
   * @return the corresponding original bitstream (or null)
   */
  protected static Bitstream findOriginalBitstream(Item item, Bitstream derived)
      throws SQLException {
    Bundle[] bundles = item.getBundles();

    // Filename of original will be filename of the derived bitstream
    // minus the extension (last 4 chars - .jpg or .txt)
    String originalFilename = derived.getName().substring(0, derived.getName().length() - 4);

    // First find "original" bundle
    for (int i = 0; i < bundles.length; i++) {
      if ((bundles[i].getName() != null) && bundles[i].getName().equals("ORIGINAL")) {
        // Now find the corresponding bitstream
        Bitstream[] bitstreams = bundles[i].getBitstreams();

        for (int bsnum = 0; bsnum < bitstreams.length; bsnum++) {
          if (bitstreams[bsnum].getName().equals(originalFilename)) {
            return bitstreams[bsnum];
          }
        }
      }
    }

    // Didn't find it
    return null;
  }
  public InputStream disseminate(Context context, Item item)
      throws DSpaceSwordException, SwordError, SwordServerException {
    try {
      Abdera abdera = new Abdera();
      Feed feed = abdera.newFeed();

      this.addMetadata(feed, item);

      Bundle[] originals = item.getBundles("ORIGINAL");
      for (Bundle original : originals) {
        Bitstream[] bss = original.getBitstreams();
        for (Bitstream bitstream : bss) {
          Entry entry = feed.addEntry();
          this.populateEntry(context, entry, bitstream);
        }
      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      feed.writeTo(baos);
      ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
      return bais;
    } catch (SQLException e) {
      throw new DSpaceSwordException(e);
    } catch (IOException e) {
      throw new DSpaceSwordException(e);
    }
  }
Example #25
0
  /**
   * Look up the id of the template item for a given collection.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @return The id of the template item.
   * @throws IOException
   */
  public static int getTemplateItemID(Context context, int collectionID)
      throws SQLException, AuthorizeException, IOException {
    Collection collection = Collection.find(context, collectionID);
    Item template = collection.getTemplateItem();

    if (template == null) {
      collection.createTemplateItem();
      template = collection.getTemplateItem();

      collection.update();
      template.update();
      context.commit();
    }

    return template.getID();
  }
Example #26
0
  /**
   * Register the bitstream file into DSpace
   *
   * @param c
   * @param i
   * @param assetstore
   * @param bitstreamPath the full filepath expressed in the contents file
   * @param bundleName
   * @throws SQLException
   * @throws IOException
   * @throws AuthorizeException
   */
  private void registerBitstream(
      Context c, Item i, int assetstore, String bitstreamPath, String bundleName)
      throws SQLException, IOException, AuthorizeException {
    // TODO validate assetstore number
    // TODO make sure the bitstream is there

    Bitstream bs = null;
    String newBundleName = bundleName;

    if (bundleName == null) {
      // is it license.txt?
      if (bitstreamPath.endsWith("license.txt")) {
        newBundleName = "LICENSE";
      } else {
        // call it ORIGINAL
        newBundleName = "ORIGINAL";
      }
    }

    if (!isTest) {
      // find the bundle
      Bundle[] bundles = i.getBundles(newBundleName);
      Bundle targetBundle = null;

      if (bundles.length < 1) {
        // not found, create a new one
        targetBundle = i.createBundle(newBundleName);
      } else {
        // put bitstreams into first bundle
        targetBundle = bundles[0];
      }

      // now add the bitstream
      bs = targetBundle.registerBitstream(assetstore, bitstreamPath);

      // set the name to just the filename
      int iLastSlash = bitstreamPath.lastIndexOf('/');
      bs.setName(bitstreamPath.substring(iLastSlash + 1));

      // Identify the format
      // FIXME - guessing format guesses license.txt incorrectly as a text file format!
      BitstreamFormat bf = FormatIdentifier.guessFormat(c, bs);
      bs.setFormat(bf);

      bs.update();
    }
  }
  private void populateTableRowFromCollection(Collection collection, TableRow row) {
    int id = collection.getID();
    Bitstream logo = collection.getLogo();
    Item templateItem = collection.getTemplateItem();
    Group admins = collection.getAdministrators();
    Group[] workflowGroups = collection.getWorkflowGroups();

    if (logo == null) {
      row.setColumnNull("logo_bitstream_id");
    } else {
      row.setColumn("logo_bitstream_id", logo.getID());
    }

    if (templateItem == null) {
      row.setColumnNull("template_item_id");
    } else {
      row.setColumn("template_item_id", templateItem.getID());
    }

    if (admins == null) {
      row.setColumnNull("admin");
    } else {
      row.setColumn("admin", admins.getID());
    }

    for (int i = 1; i <= workflowGroups.length; i++) {
      Group g = workflowGroups[i - 1];
      if (g == null) {
        row.setColumnNull("workflow_step_" + i);
      } else {
        row.setColumn("workflow_step_" + i, g.getID());
      }
    }

    // Now loop over all allowed metadata fields and set the value into the
    // TableRow.
    for (CollectionMetadataField field : CollectionMetadataField.values()) {
      String value = collection.getMetadata(field.toString());
      if (value == null) {
        row.setColumnNull(field.toString());
      } else {
        row.setColumn(field.toString(), value);
      }
    }

    row.setColumn("uuid", collection.getIdentifier().getUUID().toString());
  }
  private Item retrieve(TableRow row) {
    if (row == null) {
      return null;
    }

    int id = row.getIntColumn("item_id");
    Item item = new ItemProxy(context, id);
    populateItemFromTableRow(item, row);

    // FIXME: I'd like to bump the rest of this up into the superclass
    // so we don't have to do it for every implementation, but I can't
    // figure out a clean way of doing this yet.
    List<ExternalIdentifier> identifiers = identifierDAO.getExternalIdentifiers(item);
    item.setExternalIdentifiers(identifiers);

    return item;
  }
Example #29
0
  private void replaceItems(
      Context c, Collection[] mycollections, String sourceDir, String mapFile, boolean template)
      throws Exception {
    // verify the source directory
    File d = new java.io.File(sourceDir);

    if (d == null || !d.isDirectory()) {
      System.out.println("Error, cannot open source directory " + sourceDir);
      System.exit(1);
    }

    // read in HashMap first, to get list of handles & source dirs
    Map<String, String> myHash = readMapFile(mapFile);

    // for each handle, re-import the item, discard the new handle
    // and re-assign the old handle
    for (Map.Entry<String, String> mapEntry : myHash.entrySet()) {
      // get the old handle
      String newItemName = mapEntry.getKey();
      String oldHandle = mapEntry.getValue();

      Item oldItem = null;

      if (oldHandle.indexOf('/') != -1) {
        System.out.println("\tReplacing:  " + oldHandle);

        // add new item, locate old one
        oldItem = (Item) HandleManager.resolveToObject(c, oldHandle);
      } else {
        oldItem = Item.find(c, Integer.parseInt(oldHandle));
      }

      /* Rather than exposing public item methods to change handles --
       * two handles can't exist at the same time due to key constraints
       * so would require temp handle being stored, old being copied to new and
       * new being copied to old, all a bit messy -- a handle file is written to
       * the import directory containing the old handle, the existing item is
       * deleted and then the import runs as though it were loading an item which
       * had already been assigned a handle (so a new handle is not even assigned).
       * As a commit does not occur until after a successful add, it is safe to
       * do a delete as any error results in an aborted transaction without harming
       * the original item */
      File handleFile =
          new File(sourceDir + File.separatorChar + newItemName + File.separatorChar + "handle");
      PrintWriter handleOut = new PrintWriter(new FileWriter(handleFile, true));

      if (handleOut == null) {
        throw new Exception("can't open handle file: " + handleFile.getCanonicalPath());
      }

      handleOut.println(oldHandle);
      handleOut.close();

      deleteItem(c, oldItem);
      addItem(c, mycollections, sourceDir, newItemName, null, template);
      c.clearCache();
    }
  }
  /**
   * rejects an item - rejection means undoing a submit - WorkspaceItem is created, and the
   * WorkflowItem is removed, user is emailed rejection_message.
   *
   * @param c Context
   * @param wi WorkflowItem to operate on
   * @param e EPerson doing the operation
   * @param rejection_message message to email to user
   */
  public static WorkspaceItem reject(
      Context c, WorkflowItem wi, EPerson e, String rejection_message)
      throws SQLException, AuthorizeException, IOException {
    // authorize a DSpaceActions.REJECT
    // stop workflow
    deleteTasks(c, wi);

    // rejection provenance
    Item myitem = wi.getItem();

    // Get current date
    String now = DCDate.getCurrent().toString();

    // Get user's name + email address
    String usersName = getEPersonName(e);

    // Here's what happened
    String provDescription =
        "Rejected by " + usersName + ", reason: " + rejection_message + " on " + now + " (GMT) ";

    // Add to item as a DC field
    myitem.addDC("description", "provenance", "en", provDescription);
    myitem.update();

    // convert into personal workspace
    WorkspaceItem wsi = returnToWorkspace(c, wi);

    // notify that it's been rejected
    notifyOfReject(c, wi, e, rejection_message);

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

    return wsi;
  }