/**
   * 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;
  }
  /**
   * Create item in collection. Item can be without filled metadata.
   *
   * @param collectionId Id of collection in which will be item created.
   * @param item Item filled only with metadata, other variables are ignored.
   * @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 status code with item. Return status (OK)200 if item was created. NOT_FOUND(404)
   *     if id of collection does not exists. UNAUTHORIZED(401) if user have not permission to write
   *     items in collection.
   * @throws WebApplicationException It is thrown when was problem with database reading or writing
   *     (SQLException) or problem with creating context(ContextException) or problem with
   *     authorization to collection or IOException or problem with index item into browse index. It
   *     is thrown by NOT_FOUND and UNATHORIZED status codes, too.
   */
  @POST
  @Path("/{collection_id}/items")
  @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Item addCollectionItem(
      @PathParam("collection_id") Integer collectionId,
      Item item,
      @QueryParam("userIP") String user_ip,
      @QueryParam("userAgent") String user_agent,
      @QueryParam("xforwarderfor") String xforwarderfor,
      @Context HttpHeaders headers,
      @Context HttpServletRequest request)
      throws WebApplicationException {

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

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

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

      log.trace("Creating item in collection(id=" + collectionId + ").");
      org.dspace.content.WorkspaceItem workspaceItem =
          org.dspace.content.WorkspaceItem.create(context, dspaceCollection, false);
      org.dspace.content.Item dspaceItem = workspaceItem.getItem();

      log.trace("Adding metadata to item(id=" + dspaceItem.getID() + ").");
      if (item.getMetadata() != null) {
        for (MetadataEntry entry : item.getMetadata()) {
          String data[] = mySplit(entry.getKey());
          dspaceItem.addMetadata(data[0], data[1], data[2], entry.getLanguage(), entry.getValue());
        }
      }
      workspaceItem.update();

      // Index item to browse.
      org.dspace.browse.IndexBrowse browse = new org.dspace.browse.IndexBrowse();
      browse.indexItem(dspaceItem);

      log.trace("Installing item to collection(id=" + collectionId + ").");
      dspaceItem = org.dspace.content.InstallItem.installItem(context, workspaceItem);

      returnItem = new Item(dspaceItem, "", context);

      context.complete();

    } catch (SQLException e) {
      processException(
          "Could not add item into collection(id="
              + collectionId
              + "), SQLException. Message: "
              + e,
          context);
    } catch (AuthorizeException e) {
      processException(
          "Could not add item into collection(id="
              + collectionId
              + "), AuthorizeException. Message: "
              + e,
          context);
    } catch (IOException e) {
      processException(
          "Could not add item into collection(id=" + collectionId + "), IOException. Message: " + e,
          context);
    } catch (BrowseException e) {
      processException(
          "Could not add item into browse index, BrowseException. Message: " + e, context);
    } catch (ContextException e) {
      processException(
          "Could not add item into collection(id="
              + collectionId
              + "), ContextException. Message: "
              + e.getMessage(),
          context);
    } finally {
      processFinally(context);
    }

    log.info(
        "Item successfully created in collection(id="
            + collectionId
            + "). Item handle="
            + returnItem.getHandle());
    return returnItem;
  }
  public static void main(String[] argv) throws Exception {
    Options options = new Options();
    options.addOption("c", "collection", true, "destination collection(s) Handle (repeatable)");
    options.addOption("e", "eperson", true, "email address of eperson doing importing");
    options.addOption(
        "w",
        "install",
        false,
        "disable workflow; install immediately without going through collection's workflow");
    options.addOption("t", "type", true, "package type or MIMEtype");
    options.addOption(
        "o", "option", true, "Packager option to pass to plugin, \"name=value\" (repeatable)");
    options.addOption(
        "d", "disseminate", false, "Disseminate package (output); default is to submit.");
    options.addOption("i", "item", true, "Handle of item to disseminate.");
    options.addOption("h", "help", false, "help");

    CommandLineParser parser = new PosixParser();
    CommandLine line = parser.parse(options, argv);

    String sourceFile = null;
    String eperson = null;
    String[] collections = null;
    boolean useWorkflow = true;
    String packageType = null;
    boolean submit = true;
    String itemHandle = null;
    PackageParameters pkgParams = new PackageParameters();

    if (line.hasOption('h')) {
      HelpFormatter myhelp = new HelpFormatter();
      myhelp.printHelp("Packager  [options]  package-file|-\n", options);
      System.out.println("\nAvailable Submission Package (SIP) types:");
      String pn[] = PluginManager.getAllPluginNames(PackageIngester.class);
      for (int i = 0; i < pn.length; ++i) System.out.println("  " + pn[i]);
      System.out.println("\nAvailable Dissemination Package (DIP) types:");
      pn = PluginManager.getAllPluginNames(PackageDisseminator.class);
      for (int i = 0; i < pn.length; ++i) System.out.println("  " + pn[i]);
      System.exit(0);
    }
    if (line.hasOption('w')) useWorkflow = false;
    if (line.hasOption('e')) eperson = line.getOptionValue('e');
    if (line.hasOption('c')) collections = line.getOptionValues('c');
    if (line.hasOption('t')) packageType = line.getOptionValue('t');
    if (line.hasOption('i')) itemHandle = line.getOptionValue('i');
    String files[] = line.getArgs();
    if (files.length > 0) sourceFile = files[0];
    if (line.hasOption('d')) submit = false;
    if (line.hasOption('o')) {
      String popt[] = line.getOptionValues('o');
      for (int i = 0; i < popt.length; ++i) {
        String pair[] = popt[i].split("\\=", 2);
        if (pair.length == 2) pkgParams.addProperty(pair[0].trim(), pair[1].trim());
        else if (pair.length == 1) pkgParams.addProperty(pair[0].trim(), "");
        else System.err.println("Warning: Illegal package option format: \"" + popt[i] + "\"");
      }
    }

    // Sanity checks on arg list: required args
    if (sourceFile == null
        || eperson == null
        || packageType == null
        || (submit && collections == null)) {
      System.err.println("Error - missing a REQUIRED argument or option.\n");
      HelpFormatter myhelp = new HelpFormatter();
      myhelp.printHelp("PackageManager  [options]  package-file|-\n", options);
      System.exit(0);
    }

    // find the EPerson, assign to context
    Context context = new Context();
    EPerson myEPerson = null;
    myEPerson = EPerson.findByEmail(context, eperson);
    if (myEPerson == null) usageError("Error, eperson cannot be found: " + eperson);
    context.setCurrentUser(myEPerson);

    if (submit) {
      // make sure we have an input file

      // GWaller 11/1/10 Disable piping of input in - we need to archive the package so it is
      // simpler to assume a file stream
      //                 rather than save the System.in bytes and re-read.

      if (sourceFile.equals("-")) {
        usageError(
            "Error, input piping not allowed. Specify a file name of a physical file to read");
      }

      InputStream source = new FileInputStream(sourceFile);

      PackageIngester sip =
          (PackageIngester) PluginManager.getNamedPlugin(PackageIngester.class, packageType);
      if (sip == null) usageError("Error, Unknown package type: " + packageType);

      // find collections
      Collection[] mycollections = null;

      System.out.println("Destination collections:");

      // validate each collection arg to see if it's a real collection
      mycollections = new Collection[collections.length];
      for (int i = 0; i < collections.length; i++) {
        // sanity check: did handle resolve, and to a collection?
        DSpaceObject dso = HandleManager.resolveToObject(context, collections[i]);
        if (dso == null)
          throw new IllegalArgumentException(
              "Bad collection list -- "
                  + "Cannot resolve collection handle \""
                  + collections[i]
                  + "\"");
        else if (dso.getType() != Constants.COLLECTION)
          throw new IllegalArgumentException(
              "Bad collection list -- "
                  + "Object at handle \""
                  + collections[i]
                  + "\" is not a collection!");
        mycollections[i] = (Collection) dso;
        System.out.println(
            (i == 0 ? "  Owning " : "  ") + " Collection: " + mycollections[i].getMetadata("name"));
      }

      try {
        // GWaller 26/08/09 Support array of collections
        WorkspaceItem wi = sip.ingest(context, mycollections, source, pkgParams, null);

        // GWaller 11/1/10 IssueID #157 Archive the package
        InputStream sourceCopy = new FileInputStream(sourceFile);
        Bundle archivedBundle =
            BundleUtils.getBundleByName(wi.getItem(), Constants.ARCHIVED_CONTENT_PACKAGE_BUNDLE);
        Bitstream bs = archivedBundle.createBitstream(sourceCopy);
        bs.setName(new File(sourceFile).getName());
        bs.update();
        archivedBundle.update();

        if (useWorkflow) {
          String handle = null;

          // Check if workflow completes immediately, and
          // return Handle if so.
          WorkflowItem wfi = WorkflowManager.startWithoutNotify(context, wi);

          if (wfi.getState() == WorkflowManager.WFSTATE_ARCHIVE) {
            Item ni = wfi.getItem();
            handle = HandleManager.findHandle(context, ni);
          }
          if (handle == null)
            System.out.println("Created Workflow item, ID=" + String.valueOf(wfi.getID()));
          else System.out.println("Created and installed item, handle=" + handle);
        } else {
          InstallItem.installItem(context, wi);
          System.out.println(
              "Created and installed item, handle="
                  + HandleManager.findHandle(context, wi.getItem()));
        }
        context.complete();
        System.exit(0);
      } catch (Exception e) {
        // abort all operations
        context.abort();
        e.printStackTrace();
        System.out.println(e);
        System.exit(1);
      }
    } else {
      OutputStream dest =
          (sourceFile.equals("-"))
              ? (OutputStream) System.out
              : (OutputStream) (new FileOutputStream(sourceFile));

      PackageDisseminator dip =
          (PackageDisseminator)
              PluginManager.getNamedPlugin(PackageDisseminator.class, packageType);
      if (dip == null) usageError("Error, Unknown package type: " + packageType);

      DSpaceObject dso = HandleManager.resolveToObject(context, itemHandle);
      if (dso == null)
        throw new IllegalArgumentException(
            "Bad Item handle -- " + "Cannot resolve handle \"" + itemHandle);
      dip.disseminate(context, dso, pkgParams, dest);
    }
  }
Exemple #4
0
  /**
   * item? try and add it to the archive.
   *
   * @param mycollections - add item to these Collections.
   * @param path - directory containing the item directories.
   * @param itemname handle - non-null means we have a pre-defined handle already
   * @param mapOut - mapfile we're writing
   */
  private Item addItem(
      Context c,
      Collection[] mycollections,
      String path,
      String itemname,
      PrintWriter mapOut,
      boolean template)
      throws Exception {
    String mapOutput = null;

    System.out.println("Adding item from directory " + itemname);

    // create workspace item
    Item myitem = null;
    WorkspaceItem wi = null;

    if (!isTest) {
      wi = WorkspaceItem.create(c, mycollections[0], template);
      myitem = wi.getItem();
    }

    // now fill out dublin core for item
    loadMetadata(c, myitem, path + File.separatorChar + itemname + File.separatorChar);

    // and the bitstreams from the contents file
    // process contents file, add bitstreams and bundles, return any
    // non-standard permissions
    List<String> options =
        processContentsFile(c, myitem, path + File.separatorChar + itemname, "contents");

    if (useWorkflow) {
      // don't process handle file
      // start up a workflow
      if (!isTest) {
        // Should we send a workflow alert email or not?
        if (ConfigurationManager.getProperty("workflow", "workflow.framework")
            .equals("xmlworkflow")) {
          if (useWorkflowSendEmail) {
            XmlWorkflowManager.start(c, wi);
          } else {
            XmlWorkflowManager.startWithoutNotify(c, wi);
          }
        } else {
          if (useWorkflowSendEmail) {
            WorkflowManager.start(c, wi);
          } else {
            WorkflowManager.startWithoutNotify(c, wi);
          }
        }

        // send ID to the mapfile
        mapOutput = itemname + " " + myitem.getID();
      }
    } else {
      // only process handle file if not using workflow system
      String myhandle =
          processHandleFile(c, myitem, path + File.separatorChar + itemname, "handle");

      // put item in system
      if (!isTest) {
        InstallItem.installItem(c, wi, myhandle);

        // find the handle, and output to map file
        myhandle = HandleManager.findHandle(c, myitem);

        mapOutput = itemname + " " + myhandle;
      }

      // set permissions if specified in contents file
      if (options.size() > 0) {
        System.out.println("Processing options");
        processOptions(c, myitem, options);
      }
    }

    // now add to multiple collections if requested
    if (mycollections.length > 1) {
      for (int i = 1; i < mycollections.length; i++) {
        if (!isTest) {
          mycollections[i].addItem(myitem);
        }
      }
    }

    // made it this far, everything is fine, commit transaction
    if (mapOut != null) {
      mapOut.println(mapOutput);
    }

    c.commit();

    return myitem;
  }