Package org.dspace.content

Examples of org.dspace.content.Bitstream


        if (temp != null)
        {
            // Read the temp file as logo
            InputStream is = new BufferedInputStream(new FileInputStream(temp));
            Bitstream logoBS = collection.setLogo(is);

            // Strip all but the last filename. It would be nice
            // to know which OS the file came from.
            String noPath = wrapper.getFilesystemName("file");

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

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

            logoBS.setName(noPath);
            logoBS.setSource(wrapper.getFilesystemName("file"));

            // Identify the format
            BitstreamFormat bf = FormatIdentifier.guessFormat(context, logoBS);
            logoBS.setFormat(bf);
            AuthorizeManager.addPolicy(context, logoBS, Constants.WRITE, context
                    .getCurrentUser());
            logoBS.update();

            // Remove temp file
            temp.delete();
        }
View Full Code Here


        }

        String fn = swordService.getFilename(context, deposit, true);

        FileInputStream fis = new FileInputStream(tempFile);
        Bitstream bitstream = swordBundle.createBitstream(fis);
        bitstream.setName(fn);
        bitstream.setDescription("SWORD deposit package");

        BitstreamFormat bf = BitstreamFormat.findByMIMEType(context, deposit.getContentType());
        if (bf != null)
        {
          bitstream.setFormat(bf);
        }

        bitstream.update();
        swordBundle.update();
        item.update();

        swordService.message("Original package stored as " + fn + ", in item bundle " + swordBundle);
View Full Code Here

    {
        // we only understand how to crosswalk PREMIS to a Bitstream.
        if (dso.getType() != Constants.BITSTREAM)
            throw new CrosswalkObjectNotSupported("Wrong target object type, PREMISCrosswalk can only crosswalk to a Bitstream.");

        Bitstream bitstream = (Bitstream)dso;
        String MIMEType = null;
        String bsName = null;
        Iterator mi = ml.iterator();
        while (mi.hasNext())
        {
            Element me = (Element)mi.next();

            // if we're fed a <premis> wrapper object, recurse on its guts:
            if (me.getName().equals("premis"))
                ingest(context, dso, me.getChildren());

            // "object" section:
            else if (me.getName().equals("object"))
            {
                // originalName becomes new bitstream source and (default) name
                Element on = me.getChild("originalName", PREMIS_NS);
                if (on != null)
                    bsName = on.getTextTrim();

                // Reconcile technical metadata with bitstream content;
                // check that length and message digest (checksum) match.
                // XXX FIXME: wait for Checksum Checker code to add better test.
                Element oc = me.getChild("objectCharacteristics", PREMIS_NS);
                if (oc != null)
                {
                    String ssize = oc.getChildTextTrim("size", PREMIS_NS);
                    if (ssize != null)
                    {
                        try
                        {
                            int size = Integer.parseInt(ssize);
                            if (bitstream.getSize() != size)
                                throw new MetadataValidationException(
                                 "Bitstream size ("+String.valueOf(bitstream.getSize())+
                                 ") does not match size in PREMIS ("+ssize+"), rejecting it.");
                        }
                        catch (NumberFormatException ne)
                        {
                            throw new MetadataValidationException("Bad number value in PREMIS object/objectCharacteristics/size: "+ssize, ne);
                        }
                    }
                    Element fixity = oc.getChild("fixity", PREMIS_NS);
                    if (fixity != null)
                    {
                        String alg = fixity.getChildTextTrim("messageDigestAlgorithm", PREMIS_NS);
                        String md = fixity.getChildTextTrim("messageDigest", PREMIS_NS);
                        String b_alg = bitstream.getChecksumAlgorithm();
                        String b_md = bitstream.getChecksum();
                        if (alg != null && md != null &&
                            b_alg != null && b_md != null &&
                            alg.equals(b_alg))
                        {
                            if (md.equals(b_md))
                                log.debug("Bitstream checksum agrees with PREMIS: "+bitstream.getName());
                            else
                                throw new MetadataValidationException("Bitstream "+alg+" Checksum does not match value in PREMIS ("+b_md+" != "+md+"), for bitstream: "+bitstream.getName());
                        }
                        else
                            log.warn("Cannot test checksum on bitstream="+bitstream.getName()+
                                     ", algorithm in PREMIS is different: "+alg);
                    }

                    // Look for formatDesignation/formatName, which is
                    // MIME Type.  Match with DSpace bitstream format.
                    Element format = oc.getChild("format", PREMIS_NS);
                    if (format != null)
                    {
                        Element fd = format.getChild("formatDesignation", PREMIS_NS);
                        if (fd != null)
                            MIMEType = fd.getChildTextTrim("formatName", PREMIS_NS);
                    }
                }

                // Apply new bitstream name if we found it.
                if (bsName != null)
                {
                    bitstream.setName(bsName);
                    log.debug("Changing bitstream id="+String.valueOf(bitstream.getID())+"name and source to: "+bsName);
                }

                // reconcile bitstream format; if there's a MIMEtype,
                // get it from that, otherwise try to divine from file extension
                // (guessFormat() looks at bitstream Name, which we just set)
                BitstreamFormat bf = (MIMEType == null) ? null :
                        BitstreamFormat.findByMIMEType(context, MIMEType);
                if (bf == null)
                    bf = FormatIdentifier.guessFormat(context, bitstream);
                if (bf != null)
                    bitstream.setFormat(bf);
            }
            else
                log.debug("Skipping element: "+me.toString());
        }
        bitstream.update();
    }
View Full Code Here

        throws CrosswalkException,
               IOException, SQLException, AuthorizeException
    {
        if (dso.getType() != Constants.BITSTREAM)
            throw new CrosswalkObjectNotSupported("PREMISCrosswalk can only crosswalk a Bitstream.");
        Bitstream bitstream = (Bitstream)dso;

        Element premis = new Element("premis", PREMIS_NS);
        Element object = new Element("object", PREMIS_NS);
        premis.addContent(object);

        // objectIdentifier is required
        Element oid = new Element("objectIdentifier", PREMIS_NS);
        Element oit = new Element("objectIdentifierType", PREMIS_NS);
        oit.setText("URL");
        oid.addContent(oit);
        Element oiv = new Element("objectIdentifierValue", PREMIS_NS);

        // objectIdentifier value: by preference, if available:
        //  a. DSpace "persistent" URL to bitstream, if components available.
        //  b. name of bitstream, if any
        //  c. made-up name based on sequence ID and extension.
        String sid = String.valueOf(bitstream.getSequenceID());
        String baseUrl = ConfigurationManager.getProperty("dspace.url");
        String handle = null;
        // get handle of parent Item of this bitstream, if there is one:
        Bundle[] bn = bitstream.getBundles();
        if (bn.length > 0)
        {
            Item bi[] = bn[0].getItems();
            if (bi.length > 0)
                handle = bi[0].getHandle();
        }
        // get or make up name for bitstream:
        String bsName = bitstream.getName();
        if (bsName == null)
        {
            String ext[] = bitstream.getFormat().getExtensions();
            bsName = "bitstream_"+sid+ (ext.length > 0 ? ext[0] : "");
        }
        if (handle != null && baseUrl != null)
            oiv.setText(baseUrl
                    + "/bitstream/"
                    + URLEncoder.encode(handle, "UTF-8")
                    + "/"
                    + sid
                    + "/"
                    + URLEncoder.encode(bsName, "UTF-8"));
        else
            oiv.setText(URLEncoder.encode(bsName, "UTF-8"));

        oid.addContent(oiv);
        object.addContent(oid);

        // objectCategory is fixed value, "File".
        Element oc = new Element("objectCategory", PREMIS_NS);
        oc.setText("File");
        object.addContent(oc);

        Element ochar = new Element("objectCharacteristics", PREMIS_NS);
        object.addContent(ochar);

        // checksum if available
        String cks = bitstream.getChecksum();
        String cka = bitstream.getChecksumAlgorithm();
        if (cks != null && cka != null)
        {
            Element fixity = new Element("fixity", PREMIS_NS);
            Element mda = new Element("messageDigestAlgorithm", PREMIS_NS);
            mda.setText(cka);
            fixity.addContent(mda);
            Element md = new Element("messageDigest", PREMIS_NS);
            md.setText(cks);
            fixity.addContent(md);
            ochar.addContent(fixity);
        }

        // size
        Element size = new Element("size", PREMIS_NS);
        size.setText(String.valueOf(bitstream.getSize()));
        ochar.addContent(size);

        //  Punt and set formatName to the MIME type; the best we can
        //  do for now in the absence of any usable global format registries.
        // objectCharacteristics/format/formatDesignation/
        //                                       formatName <- MIME Type
        //
        Element format = new Element("format", PREMIS_NS);
        Element formatDes = new Element("formatDesignation", PREMIS_NS);
        Element formatName = new Element("formatName", PREMIS_NS);
        formatName.setText(bitstream.getFormat().getMIMEType());
        formatDes.addContent(formatName);
        format.addContent(formatDes);
        ochar.addContent(format);

        // originalName <- name (or source if none)
        String oname = bitstream.getName();
        if (oname == null)
            oname = bitstream.getSource();
        if (oname != null)
        {
            Element on = new Element("originalName", PREMIS_NS);
            on.setText(oname);
            object.addContent(on);
View Full Code Here

        }
        else {
            bs_format = BitstreamFormat.findByShortDescription(context, "License");
        }

        Bitstream bs = bundle.createBitstream(licenseStm);
        bs.setSource(CC_BS_SOURCE);
        bs.setName((mimeType != null &&
                    (mimeType.equalsIgnoreCase("text/xml") ||
                     mimeType.equalsIgnoreCase("text/rdf"))) ?
                   BSN_LICENSE_RDF : BSN_LICENSE_TEXT);
        bs.setFormat(bs_format);
        bs.update();
    }
View Full Code Here

    private static void setBitstreamFromBytes(Item item, Bundle bundle,
            String bitstream_name, BitstreamFormat format, byte[] bytes)
            throws SQLException, IOException, AuthorizeException
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        Bitstream bs = bundle.createBitstream(bais);

        bs.setName(bitstream_name);
        bs.setSource(CC_BS_SOURCE);

        bs.setFormat(format);

        // commit everything
        bs.update();
    }
View Full Code Here

    }

    private static byte[] getBytesFromBitstream(Item item, String bitstream_name)
            throws SQLException, IOException, AuthorizeException
    {
        Bitstream bs = getBitstream(item, bitstream_name);

        // no such bitstream
        if (bs == null)
        {
            return null;
        }

        // create a ByteArrayOutputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(bs.retrieve(), baos);

        return baos.toByteArray();
    }
View Full Code Here

            ZipEntry ze;
            while ((ze = zip.getNextEntry()) != null)
            {
                if (ze.isDirectory())
                    continue;
                Bitstream bs = null;
                String fname = ze.getName();
                if (fname.equals(MANIFEST_FILE))
                {
                    if (preserveManifest)
                    {
                        mdBundle = item.createBundle(Constants.METADATA_BUNDLE_NAME);
                        bs = mdBundle.createBitstream(new PackageUtils.UnclosableInputStream(zip));
                        bs.setName(fname);
                        bs.setSource(fname);

                        // Get magic bitstream format to identify manifest.
                        BitstreamFormat manifestFormat = null;
                        manifestFormat = PackageUtils.findOrCreateBitstreamFormat(context,
                             MANIFEST_BITSTREAM_FORMAT, "application/xml",
                             MANIFEST_BITSTREAM_FORMAT+" package manifest");
                        bs.setFormat(manifestFormat);

                        manifest = METSManifest.create(bs.retrieve(), validate);
                    }
                    else
                    {
                        manifest = METSManifest.create(new PackageUtils.UnclosableInputStream(zip), validate);
                        continue;
                    }
                }
                else
                {
                  // we need to create the bundle only the first time
                  if (contentBundle == null)
                  {
                    contentBundle = item.createBundle(Constants.CONTENT_BUNDLE_NAME);
                  }
                    bs = contentBundle.createBitstream(new PackageUtils.UnclosableInputStream(zip));
                    bs.setSource(fname);
                    bs.setName(fname);
                }
                packageFiles.add(fname);
                bs.setSource(fname);
                bs.update();
            }
            zip.close();

            if (manifest == null)
                throw new PackageValidationException("No METS Manifest found (filename="+MANIFEST_FILE+").  Package is unacceptable.");

            // initial sanity checks on manifest (in subclass)
            checkManifest(manifest);

            /* 2. Grovel a file list out of METS Manifest and compare
             *  it to the files in package, as an integrity test.
             */
            List manifestContentFiles = manifest.getContentFiles();

            // Compare manifest files with the ones found in package:
            //  a. Start with content files (mentioned in <fileGrp>s)
            HashSet missingFiles = new HashSet();
            for (Iterator mi = manifestContentFiles.iterator(); mi.hasNext(); )
            {
                // First locate corresponding Bitstream and make
                // map of Bitstream to <file> ID.
                Element mfile = (Element)mi.next();
                String mfileId = mfile.getAttributeValue("ID");
                if (mfileId == null)
                    throw new PackageValidationException("Invalid METS Manifest: file element without ID attribute.");
                String path = METSManifest.getFileName(mfile);
                Bitstream bs = contentBundle.getBitstreamByName(path);
                if (bs == null)
                {
                    log.warn("Cannot find bitstream for filename=\""+path+
                             "\", skipping it..may cause problems later.");
                    missingFiles.add(path);
                }
                else
                {
                    fileIdToBitstream.put(mfileId, bs);

                    // Now that we're done using Name to match to <file>,
                    // set default bitstream Name to last path element;
                    // Zip entries all have '/' pathname separators
                    // NOTE: set default here, hopefully crosswalk of
                    // a bitstream techMD section will override it.
                    String fname = bs.getName();
                    int lastSlash = fname.lastIndexOf('/');
                    if (lastSlash >= && lastSlash+1 < fname.length())
                        bs.setName(fname.substring(lastSlash+1));

                    // Set Default bitstream format:
                    //  1. attempt to guess from MIME type
                    //  2. if that fails, guess from "name" extension.
                    String mimeType = mfile.getAttributeValue("MIMETYPE");
                    BitstreamFormat bf = (mimeType == null) ? null :
                            BitstreamFormat.findByMIMEType(context, mimeType);
                    if (bf == null)
                        bf = FormatIdentifier.guessFormat(context, bs);
                    bs.setFormat(bf);

                    // if this bitstream belongs in another Bundle, move it:
                    String bundleName = manifest.getBundleName(mfile);
                    if (!bundleName.equals(Constants.CONTENT_BUNDLE_NAME))
                    {
                        Bundle bn;
                        Bundle bns[] = item.getBundles(bundleName);
                        if (bns != null && bns.length > 0)
                            bn = bns[0];
                        else
                            bn = item.createBundle(bundleName);
                        bn.addBitstream(bs);
                        contentBundle.removeBitstream(bs);
                    }

                    // finally, build compare lists by deleting matches.
                    if (packageFiles.contains(path))
                        packageFiles.remove(path);
                    else
                        missingFiles.add(path);
                }
            }

            //  b. Process files mentioned in <mdRef>s - check and move
            //     to METADATA bundle.
            for (Iterator mi = manifest.getMdFiles().iterator(); mi.hasNext(); )
            {
                Element mdref = (Element)mi.next();
                String path = METSManifest.getFileName(mdref);

                // finally, build compare lists by deleting matches.
                if (packageFiles.contains(path))
                    packageFiles.remove(path);
                else
                    missingFiles.add(path);

                // if there is a bitstream with that name in Content, move
                // it to the Metadata bundle:
                Bitstream mdbs = contentBundle.getBitstreamByName(path);
                if (mdbs != null)
                {
                    if (mdBundle == null)
                        mdBundle = item.createBundle(Constants.METADATA_BUNDLE_NAME);
                    mdBundle.addBitstream(mdbs);
                    contentBundle.removeBitstream(mdbs);
                }
            }

            // KLUDGE: make sure Manifest file doesn't get flagged as missing
            // or extra, since it won't be mentioned in the manifest.
            if (packageFiles.contains(MANIFEST_FILE))
                packageFiles.remove(MANIFEST_FILE);

            // Give subclass a chance to refine the lists of in-package
            // and missing files, delete extraneous files, etc.
            checkPackageFiles(packageFiles, missingFiles, manifest);

            // Any discrepency in file lists is a fatal error:
            if (!(packageFiles.isEmpty() && missingFiles.isEmpty()))
            {
                StringBuffer msg = new StringBuffer("Package is unacceptable: contents do not match manifest.");
                if (!missingFiles.isEmpty())
                {
                    msg.append("\nPackage is missing these files listed in Manifest:");
                    for (Iterator mi = missingFiles.iterator(); mi.hasNext(); )
                        msg.append("\n\t"+(String)mi.next());
                }
                if (!packageFiles.isEmpty())
                {
                    msg.append("\nPackage contains extra files NOT in manifest:");
                    for (Iterator mi = packageFiles.iterator(); mi.hasNext(); )
                        msg.append("\n\t"+(String)mi.next());
                }
                throw new PackageValidationException(msg.toString());
            }

            /* 3. crosswalk the metadata
             */
            // get mdref'd streams from "callback" object.
            MdrefManager callback = new MdrefManager(mdBundle);

            chooseItemDmd(context, item, manifest, callback, manifest.getItemDmds(), params);

            // crosswalk content bitstreams too.
            for (Iterator ei = fileIdToBitstream.entrySet().iterator();
                 ei.hasNext();)
            {
                Map.Entry ee = (Map.Entry)ei.next();
                manifest.crosswalkBitstream(context, (Bitstream)ee.getValue(),
                                        (String)ee.getKey(), callback);
            }

            // Take a second pass over files to correct names of derived files
            // (e.g. thumbnails, extracted text) to what DSpace expects:
            for (Iterator mi = manifestContentFiles.iterator(); mi.hasNext(); )
            {
                Element mfile = (Element)mi.next();
                String bundleName = manifest.getBundleName(mfile);
                if (!bundleName.equals(Constants.CONTENT_BUNDLE_NAME))
                {
                    Element origFile = manifest.getOriginalFile(mfile);
                    if (origFile != null)
                    {
                        String ofileId = origFile.getAttributeValue("ID");
                        Bitstream obs = (Bitstream)fileIdToBitstream.get(ofileId);
                        String newName = makeDerivedFilename(bundleName, obs.getName());
                        if (newName != null)
                        {
                            String mfileId = mfile.getAttributeValue("ID");
                            Bitstream bs = (Bitstream)fileIdToBitstream.get(mfileId);
                            bs.setName(newName);
                            bs.update();
                        }
                    }
                }
            }

            // Sanity-check the resulting metadata on the Item:
            PackageUtils.checkMetadata(item);

            /* 4. Set primary bitstream; same Bundle
             */
            Element pbsFile = manifest.getPrimaryBitstream();
            if (pbsFile != null)
            {
                Bitstream pbs = (Bitstream)fileIdToBitstream.get(pbsFile.getAttributeValue("ID"));
                if (pbs == null)
                    log.error("Got Primary Bitstream file ID="+pbsFile.getAttributeValue("ID")+
                             ", but found no corresponding bitstream.");
                else
                {
                    Bundle bn[] = pbs.getBundles();
                    if (bn.length > 0)
                        bn[0].setPrimaryBitstreamID(pbs.getID());
                    else
                        log.error("Sanity check, got primary bitstream without any parent bundle.");
                }
            }

View Full Code Here

         * @return the input stream of its content.
         */
        public InputStream getInputStream(Element mdref)
            throws MetadataValidationException, IOException, SQLException, AuthorizeException
        {
            Bitstream mdbs = getBitstreamForMdRef(mdref);
            if (mdbs == null)
                throw new MetadataValidationException("Failed dereferencing bitstream for mdRef element="+mdref.toString());
            return mdbs.retrieve();
        }
View Full Code Here

                return STATUS_EDIT_COMPLETE;
            }
            else
            {
                // load info for bitstream we are editing
                Bitstream b = Bitstream.find(context, Integer.parseInt(request
                        .getParameter("bitstream_id")));

                // save bitstream to submission info
                subInfo.setBitstream(b);
            }
        }
        else if (buttonPressed.startsWith("submit_edit_"))
        {
            // get ID of bitstream that was requested for editing
            String bitstreamID = buttonPressed.substring("submit_edit_"
                    .length());

            Bitstream b = Bitstream
                    .find(context, Integer.parseInt(bitstreamID));

            // save bitstream to submission info
            subInfo.setBitstream(b);
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.