Package org.dspace.content

Examples of org.dspace.content.Bitstream


      File f = new File(dir, ce.filename);
     
        // get an input stream
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));

        Bitstream bs = null;
        String newBundleName = ce.bundlename;

        if (ce.bundlename == null// should be required but default convention established
        {
            if (ce.filename.equals("license.txt"))
            {
                newBundleName = "LICENSE";
            }
            else 
            {
                newBundleName = "ORIGINAL";
            }
        }
        ItemUpdate.pr("  Bitstream " + ce.filename + " to be added to bundle: " + newBundleName);
       
        if (!isTest)
        {
          // find the bundle
          Bundle[] bundles = item.getBundles(newBundleName);
          Bundle targetBundle = null;
 
          if (bundles.length < 1)
          {
              // not found, create a new one
              targetBundle = item.createBundle(newBundleName);
          }
          else
          {
          //verify bundle + name are not duplicates
            for (Bundle b : bundles)
            {
              Bitstream[] bitstreams = b.getBitstreams();
              for (Bitstream bsm : bitstreams)
              {
                if (bsm.getName().equals(ce.filename))
                {
                  throw new IllegalArgumentException("Duplicate bundle + filename cannot be added: "
                      + b.getName() + " + " + bsm.getName());
                }
              }
            }

              // select first bundle
              targetBundle = bundles[0];
          }
 
          bs = targetBundle.createBitstream(bis)
          bs.setName(ce.filename);
 
          // Identify the format
          // FIXME - guessing format guesses license.txt incorrectly as a text file format!
          BitstreamFormat fmt = FormatIdentifier.guessFormat(context, bs);
        bs.setFormat(fmt);
       
          if (ce.description != null)
          {
            bs.setDescription(ce.description);
          }
                   
          if ((ce.permissionsActionId != -1) && (ce.permissionsGroupName != null))
          {
        Group group = Group.findByName(context, ce.permissionsGroupName);
       
        if (group != null)
        {
              AuthorizeManager.removeAllPolicies(context, bs)// remove the default policy
              ResourcePolicy rp = ResourcePolicy.create(context);
              rp.setResource(bs);
              rp.setAction(ce.permissionsActionId);
              rp.setGroup(group);   
              rp.update();
        }
          }
         
          if (alterProvenance && !targetBundle.getName().equals("THUMBMNAIL")
              && !targetBundle.getName().equals("TEXT"))
          {
            DtoMetadata dtom = DtoMetadata.create("dc.description.provenance", "en", "");
           
            String append = "Bitstream added on " + DCDate.getCurrent() + " : "
                            + InstallItem.getBitstreamProvenanceMessage(item);
            MetadataUtilities.appendMetadata(item, dtom, false, append);
          }
         
          //update after all changes are applied, even metadata ones
          bs.update();
       
          if (!suppressUndo)
          {
            itarch.addUndoDeleteContents(bs.getID());
          }
        }
    }
View Full Code Here


           // The dso may be an item but it could still be an item's bitstream. So let's check for the parameter.
          if (request.getParameter("bitstreamId") != null)
          {
            String identifier = "unknown";
            try {
              Bitstream bit = Bitstream.find(context, new Integer(request.getParameter("bitstreamId")));
              if (bit != null) {
                identifier = bit.getName();
              }
            }
            catch(Exception e) {
              // just forget it - and display the restricted message.
            }
View Full Code Here

      {
        for (int id : list)
        {
          try
          {
              Bitstream bs = Bitstream.find(context, id);
              if (bs == null)
              {
                ItemUpdate.pr("Bitstream not found by id: " + id);
              }
              else
              {
                Bundle[] bundles = bs.getBundles();
                for (Bundle b : bundles)
                {
                  if (isTest)
                  {
                    ItemUpdate.pr("Delete bitstream with id = " + id);
                  }
                  else
                  {
                    b.removeBitstream(bs);
                    ItemUpdate.pr("Deleted bitstream with id = " + id);
                   
                  }
                } 
             
                    if (alterProvenance)
                    {
                      DtoMetadata dtom = DtoMetadata.create("dc.description.provenance", "en", "");
                     
                      String append = "Bitstream " + bs.getName() + " deleted on " + DCDate.getCurrent() + "; ";
                      Item item = bundles[0].getItems()[0];
                  ItemUpdate.pr("Append provenance with: " + append);
                 
                  if (!isTest)
                  {
View Full Code Here

    protected void doDSGet(Context context, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException,
            SQLException, AuthorizeException
    {
        Item item = null;
        Bitstream bitstream = null;

        String idString = request.getPathInfo();
        String filenameNoPath = null;
        String fullpath = null;
        String handle = null;

        // Parse URL
        if (idString != null)
        {
            // Remove leading slash
            if (idString.startsWith("/"))
            {
                idString = idString.substring(1);
            }

            // Get handle and full file path
            int slashIndex = idString.indexOf('/');
            if (slashIndex != -1)
            {
                slashIndex = idString.indexOf('/', slashIndex + 1);
                if (slashIndex != -1)
                {
                    handle = idString.substring(0, slashIndex);
                    fullpath = URLDecoder.decode(idString
                            .substring(slashIndex + 1),
                            Constants.DEFAULT_ENCODING);

                    // Get filename with no path
                    slashIndex = fullpath.indexOf('/');
                    if (slashIndex != -1)
                    {
                        String[] pathComponents = fullpath.split("/");
                        if (pathComponents.length <= maxDepthGuess + 1)
                        {
                            filenameNoPath = pathComponents[pathComponents.length - 1];
                        }
                    }
                }
            }
        }

        if (handle != null && fullpath != null)
        {
            // Find the item
            try
            {
                /*
                 * If the original item doesn't have a Handle yet (because it's
                 * in the workflow) what we actually have is a fake Handle in
                 * the form: db-id/1234 where 1234 is the database ID of the
                 * item.
                 */
                if (handle.startsWith("db-id"))
                {
                    String dbIDString = handle
                            .substring(handle.indexOf('/') + 1);
                    int dbID = Integer.parseInt(dbIDString);
                    item = Item.find(context, dbID);
                }
                else
                {
                    item = (Item) HandleManager
                            .resolveToObject(context, handle);
                }
            }
            catch (NumberFormatException nfe)
            {
                // Invalid ID - this will be dealt with below
            }
        }

        if (item != null)
        {
            // Try to find bitstream with exactly matching name + path
            bitstream = getItemBitstreamByName(item, fullpath);
           
            if (bitstream == null && filenameNoPath != null)
            {
                // No match with the full path, but we can try again with
                // only the filename
                bitstream = getItemBitstreamByName(item, filenameNoPath);
            }
        }

        // Did we get a bitstream?
        if (bitstream != null)
        {
            log.info(LogManager.getHeader(context, "view_html", "handle="
                    + handle + ",bitstream_id=" + bitstream.getID()));
           
            new DSpace().getEventService().fireEvent(
                new UsageEvent(
                    UsageEvent.Action.VIEW,
                    request,
                    context,
                    bitstream));
           
            //new UsageEvent().fire(request, context, AbstractUsageEvent.VIEW,
      //    Constants.BITSTREAM, bitstream.getID());

            // Set the response MIME type
            response.setContentType(bitstream.getFormat().getMIMEType());

            // Response length
            response.setHeader("Content-Length", String.valueOf(bitstream
                    .getSize()));

            // Pipe the bits
            InputStream is = bitstream.retrieve();

            Utils.bufferedCopy(is, response.getOutputStream());
            is.close();
            response.getOutputStream().flush();
        }
View Full Code Here

      if (parts.length != 2)
        throw new UIException("Unable to parse id into bundle and bitstream id: "+id);

      int bitstreamID = Integer.valueOf(parts[1]);

      Bitstream bitstream = Bitstream.find(context,bitstreamID);
      bitstreams.add(bitstream);

    }

    // DIVISION: bitstream-confirm-delete
    Division deleted = body.addInteractiveDivision("bitstreams-confirm-delete",contextPath+"/admin/item",Division.METHOD_POST,"primary administrative item");
    deleted.setHead(T_head1);
    deleted.addPara(T_para1);

    Table table = deleted.addTable("bitstreams-confirm-delete",bitstreams.size() + 1, 1);

    Row header = table.addRow(Row.ROLE_HEADER);
    header.addCellContent(T_column1);
    header.addCellContent(T_column2);
    header.addCellContent(T_column3);

    for (Bitstream bitstream : bitstreams)
    {
      String format = null;
      BitstreamFormat bitstreamFormat = bitstream.getFormat();
      if (bitstreamFormat != null)
        format = bitstreamFormat.getShortDescription();

      Row row = table.addRow();
      row.addCell().addContent(bitstream.getName());
      row.addCell().addContent(bitstream.getDescription());
      row.addCell().addContent(format);
    }
    Para buttons = deleted.addPara();
    buttons.addButton("submit_confirm").setValue(T_submit_delete);
    buttons.addButton("submit_cancel").setValue(T_submit_cancel);
View Full Code Here

  protected void doDSGet(Context context, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException,
            SQLException, AuthorizeException
    {
      Item item = null;
      Bitstream bitstream = null;

        // Get the ID from the URL
        String idString = request.getPathInfo();
        String handle = "";
        String sequenceText = "";
        String filename = null;
        int sequenceID;

        if (idString == null)
        {
            idString = "";
        }
       
        // Parse 'handle' and 'sequence' (bitstream seq. number) out
        // of remaining URL path, which is typically of the format:
        // {handle}/{sequence}/{bitstream-name}
        // But since the bitstream name MAY have any number of "/"s in
        // it, and the handle is guaranteed to have one slash, we
        // scan from the start to pick out handle and sequence:

        // Remove leading slash if any:
        if (idString.startsWith("/"))
        {
            idString = idString.substring(1);
        }

        // skip first slash within handle
        int slashIndex = idString.indexOf('/');
        if (slashIndex != -1)
        {
            slashIndex = idString.indexOf('/', slashIndex + 1);
            if (slashIndex != -1)
            {
                handle = idString.substring(0, slashIndex);
                int slash2 = idString.indexOf('/', slashIndex + 1);
                if (slash2 != -1)
                {
                    sequenceText = idString.substring(slashIndex+1,slash2);
                    filename = idString.substring(slash2+1);
                }
            }
        }

        try
        {
            sequenceID = Integer.parseInt(sequenceText);
        }
        catch (NumberFormatException nfe)
        {
            sequenceID = -1;
        }
       
        // Now try and retrieve the item
        DSpaceObject dso = HandleManager.resolveToObject(context, handle);
       
        // Make sure we have valid item and sequence number
        if (dso != null && dso.getType() == Constants.ITEM && sequenceID >= 0)
        {
            item = (Item) dso;
       
            if (item.isWithdrawn())
            {
                log.info(LogManager.getHeader(context, "view_bitstream",
                        "handle=" + handle + ",withdrawn=true"));
                JSPManager.showJSP(request, response, "/tombstone.jsp");
                return;
            }

            boolean found = false;

            Bundle[] bundles = item.getBundles();

            for (int i = 0; (i < bundles.length) && !found; i++)
            {
                Bitstream[] bitstreams = bundles[i].getBitstreams();

                for (int k = 0; (k < bitstreams.length) && !found; k++)
                {
                    if (sequenceID == bitstreams[k].getSequenceID())
                    {
                        bitstream = bitstreams[k];
                        found = true;
                    }
                }
            }
        }

        if (bitstream == null || filename == null
                || !filename.equals(bitstream.getName()))
        {
            // No bitstream found or filename was wrong -- ID invalid
            log.info(LogManager.getHeader(context, "invalid_id", "path="
                    + idString));
            JSPManager.showInvalidIDError(request, response, idString,
                    Constants.BITSTREAM);

            return;
        }

        log.info(LogManager.getHeader(context, "view_bitstream",
                "bitstream_id=" + bitstream.getID()));
       
        //new UsageEvent().fire(request, context, AbstractUsageEvent.VIEW,
    //    Constants.BITSTREAM, bitstream.getID());

        new DSpace().getEventService().fireEvent(
            new UsageEvent(
                UsageEvent.Action.VIEW,
                request,
                context,
                bitstream));
       
        // Modification date
        // Only use last-modified if this is an anonymous access
        // - caching content that may be generated under authorisation
        //   is a security problem
        if (context.getCurrentUser() == null)
        {
            // TODO: Currently the date of the item, since we don't have dates
            // for files
            response.setDateHeader("Last-Modified", item.getLastModified()
                    .getTime());

            // Check for if-modified-since header
            long modSince = request.getDateHeader("If-Modified-Since");

            if (modSince != -1 && item.getLastModified().getTime() < modSince)
            {
                // Item has not been modified since requested date,
                // hence bitstream has not; return 304
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
        }
       
        // Pipe the bits
        InputStream is = bitstream.retrieve();
    
    // Set the response MIME type
        response.setContentType(bitstream.getFormat().getMIMEType());

        // Response length
        response.setHeader("Content-Length", String
                .valueOf(bitstream.getSize()));

    if(threshold != -1 && bitstream.getSize() >= threshold)
    {
      setBitstreamDisposition(bitstream.getName(), request, response);
    }

        Utils.bufferedCopy(is, response.getOutputStream());
        is.close();
        response.getOutputStream().flush();
View Full Code Here

          }
          else
          {
            boolean html = false;
            String handle = item.getHandle();
            Bitstream primaryBitstream = null;

            Bundle[] bunds = item.getBundles("ORIGINAL");
            Bundle[] thumbs = item.getBundles("THUMBNAIL");

            // if item contains multiple bitstreams, display bitstream
            // description
            boolean multiFile = false;
            Bundle[] allBundles = item.getBundles();

            for (int i = 0, filecount = 0; (i < allBundles.length)
                      && !multiFile; i++)
            {
              filecount += allBundles[i].getBitstreams().length;
              multiFile = (filecount > 1);
            }

            // check if primary bitstream is html
            if (bunds[0] != null)
            {
              Bitstream[] bits = bunds[0].getBitstreams();

              for (int i = 0; (i < bits.length) && !html; i++)
              {
                if (bits[i].getID() == bunds[0].getPrimaryBitstreamID())
                {
                  html = bits[i].getFormat().getMIMEType().equals(
                      "text/html");
                  primaryBitstream = bits[i];
                }
              }
            }

            out
                    .println("<table cellpadding=\"6\"><tr><th id=\"t1\" class=\"standard\">"
                            + LocaleSupport.getLocalizedMessage(pageContext,
                                    "org.dspace.app.webui.jsptag.ItemTag.file")
                            + "</th>");

            if (multiFile)
            {

              out
                        .println("<th id=\"t2\" class=\"standard\">"
                                + LocaleSupport
                                        .getLocalizedMessage(pageContext,
                                                "org.dspace.app.webui.jsptag.ItemTag.description")
                                + "</th>");
            }

            out.println("<th id=\"t3\" class=\"standard\">"
                    + LocaleSupport.getLocalizedMessage(pageContext,
                            "org.dspace.app.webui.jsptag.ItemTag.filesize")
                    + "</th><th id=\"t4\" class=\"standard\">"
                    + LocaleSupport.getLocalizedMessage(pageContext,
                            "org.dspace.app.webui.jsptag.ItemTag.fileformat")
                    + "</th></tr>");

              // if primary bitstream is html, display a link for only that one to
              // HTMLServlet
              if (html)
              {
                // If no real Handle yet (e.g. because Item is in workflow)
                // we use the 'fake' Handle db-id/1234 where 1234 is the
                // database ID of the item.
                if (handle == null)
                {
                  handle = "db-id/" + item.getID();
                }

                out.print("<tr><td headers=\"t1\" class=\"standard\">");
                    out.print("<a target=\"_blank\" href=\"");
                    out.print(request.getContextPath());
                    out.print("/html/");
                    out.print(handle + "/");
                    out
                        .print(UIUtil.encodeBitstreamName(primaryBitstream
                                .getName(), Constants.DEFAULT_ENCODING));
                    out.print("\">");
                    out.print(primaryBitstream.getName());
                    out.print("</a>");
                   
                   
                if (multiFile)
                {
                  out.print("</td><td headers=\"t2\" class=\"standard\">");

                  String desc = primaryBitstream.getDescription();
                  out.print((desc != null) ? desc : "");
                }

                out.print("</td><td headers=\"t3\" class=\"standard\">");
                    out.print(UIUtil.formatFileSize(primaryBitstream.getSize()));
                    out.print("</td><td headers=\"t4\" class=\"standard\">");
                out.print(primaryBitstream.getFormatDescription());
                out
                        .print("</td><td class=\"standard\"><a target=\"_blank\" href=\"");
                out.print(request.getContextPath());
                out.print("/html/");
                out.print(handle + "/");
                out
                        .print(UIUtil.encodeBitstreamName(primaryBitstream
                                .getName(), Constants.DEFAULT_ENCODING));
                out.print("\">"
                        + LocaleSupport.getLocalizedMessage(pageContext,
                                "org.dspace.app.webui.jsptag.ItemTag.view")
                        + "</a></td></tr>");
             
              else
              {
                for (int i = 0; i < bundles.length; i++)
                {
                  Bitstream[] bitstreams = bundles[i].getBitstreams();

                  for (int k = 0; k < bitstreams.length; k++)
                  {
                    // Skip internal types
                    if (!bitstreams[k].getFormat().isInternal())
                    {

                                // Work out what the bitstream link should be
                                // (persistent
                                // ID if item has Handle)
                                String bsLink = "<a target=\"_blank\" href=\""
                                        + request.getContextPath();

                                if ((handle != null)
                                        && (bitstreams[k].getSequenceID() > 0))
                                {
                                    bsLink = bsLink + "/bitstream/"
                                            + item.getHandle() + "/"
                                            + bitstreams[k].getSequenceID() + "/";
                                }
                                else
                                {
                                    bsLink = bsLink + "/retrieve/"
                                            + bitstreams[k].getID() + "/";
                                }

                                bsLink = bsLink
                                        + UIUtil.encodeBitstreamName(bitstreams[k]
                                            .getName(),
                                            Constants.DEFAULT_ENCODING) + "\">";

                      out
                                    .print("<tr><td headers=\"t1\" class=\"standard\">");
                                out.print(bsLink);
                      out.print(bitstreams[k].getName());
                                out.print("</a>");
                               

                      if (multiFile)
                      {
                        out
                                        .print("</td><td headers=\"t2\" class=\"standard\">");

                        String desc = bitstreams[k].getDescription();
                        out.print((desc != null) ? desc : "");
                      }

                      out
                                    .print("</td><td headers=\"t3\" class=\"standard\">");
                                out.print(UIUtil.formatFileSize(bitstreams[k].getSize()));
                      out
                                .print("</td><td headers=\"t4\" class=\"standard\">");
                      out.print(bitstreams[k].getFormatDescription());
                      out
                                    .print("</td><td class=\"standard\" align=\"center\">");

                      // is there a thumbnail bundle?
                      if ((thumbs.length > 0) && showThumbs)
                      {
                        String tName = bitstreams[k].getName() + ".jpg";
                                    String tAltText = LocaleSupport.getLocalizedMessage(pageContext, "org.dspace.app.webui.jsptag.ItemTag.thumbnail");
                        Bitstream tb = thumbs[0]
                                        .  getBitstreamByName(tName);

                        if (tb != null)
                        {
                          String myPath = request.getContextPath()
                                              + "/retrieve/"
                                              + tb.getID()
                                              + "/"
                                              + UIUtil.encodeBitstreamName(tb
                                                  .getName(),
                                                  Constants.DEFAULT_ENCODING);

                          out.print(bsLink);
                          out.print("<img src=\"" + myPath + "\" ");
View Full Code Here

    {
      InputStream is = filePart.getInputStream();

      String bundleName = request.getParameter("bundle");
     
      Bitstream bitstream;
      Bundle[] bundles = item.getBundles(bundleName);
      if (bundles.length < 1)
      {
        // set bundle's name to ORIGINAL
        bitstream = item.createSingleBitstream(is, bundleName);
       
        // set the permission as defined in the owning collection
        Collection owningCollection = item.getOwningCollection();
        if (owningCollection != null)
        {
            Bundle bnd = bitstream.getBundles()[0];
            bnd.inheritCollectionDefaultPolicies(owningCollection);
        }
      }
      else
      {
        // we have a bundle already, just add bitstream
        bitstream = bundles[0].createBitstream(is);
      }

      // Strip all but the last filename. It would be nice
      // to know which OS the file came from.
      String name = filePart.getUploadName();

      while (name.indexOf('/') > -1)
      {
        name = name.substring(name.indexOf('/') + 1);
      }

      while (name.indexOf('\\') > -1)
      {
        name = name.substring(name.indexOf('\\') + 1);
      }

      bitstream.setName(name);
      bitstream.setSource(filePart.getUploadName());
      bitstream.setDescription(request.getParameter("description"));

      // Identify the format
      BitstreamFormat format = FormatIdentifier.guessFormat(context, bitstream);
      bitstream.setFormat(format);

      // Update to DB
      bitstream.update();
      item.update();
     
      context.commit();
     
      result.setContinue(true);
View Full Code Here

  public static FlowResult processEditBitstream(Context context, int itemID, int bitstreamID, String primary, String description, int formatID, String userFormat) throws SQLException, AuthorizeException
  {
    FlowResult result = new FlowResult();
    result.setContinue(false);
   
    Bitstream bitstream = Bitstream.find(context, bitstreamID);
    BitstreamFormat currentFormat = bitstream.getFormat();

    //Step 1:
    // Update the bitstream's description
    if (description != null)
    {
      bitstream.setDescription(description);
    }
   
    //Step 2:
    // Check if the primary bitstream status has changed
    Bundle[] bundles = bitstream.getBundles();
    if (bundles != null && bundles.length > 0)
    {
      if (bitstreamID == bundles[0].getPrimaryBitstreamID())
      {
        // currently the bitstream is primary
        if ("no".equals(primary))
        {
          // However the user has removed this bitstream as a primary bitstream.
          bundles[0].unsetPrimaryBitstreamID();
          bundles[0].update();
        }
      }
      else
      {
        // currently the bitstream is non-primary
        if ("yes".equals(primary))
        {
          // However the user has set this bitstream as primary.
          bundles[0].setPrimaryBitstreamID(bitstreamID);
          bundles[0].update();
        }
      }
    }
   
   
    //Step 2:
    // Update the bitstream's format
    if (formatID > 0)
    {
      if (currentFormat == null || currentFormat.getID() != formatID)
      {
        BitstreamFormat newFormat = BitstreamFormat.find(context, formatID);
        if (newFormat != null)
        {
          bitstream.setFormat(newFormat);
        }
      }
    }
    else
    {
      if (userFormat != null && userFormat.length() > 0)
      {
        bitstream.setUserFormatDescription(userFormat);
      }
    }
   
    //Step 3:
    // Save our changes
    bitstream.update();
    context.commit();
   
     result.setContinue(true);
       result.setOutcome(true);
       result.setMessage(T_bitstream_updated);
View Full Code Here

     
      int bundleID = Integer.valueOf(parts[0]);
      int bitstreamID = Integer.valueOf(parts[1]);
     
      Bundle bundle = Bundle.find(context, bundleID);
      Bitstream bitstream = Bitstream.find(context,bitstreamID);
     
      bundle.removeBitstream(bitstream);
     
      if (bundle.getBitstreams().length == 0)
      {
View Full Code Here

TOP

Related Classes of org.dspace.content.Bitstream

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.