Package edu.harvard.hul.ois.mets

Examples of edu.harvard.hul.ois.mets.Mets


        try
        {
            init(context);

            // Create the METS file
            Mets mets = new Mets();

            // Top-level stuff
            mets.setOBJID("hdl:" + item.getHandle());
            mets.setLABEL("DSpace Item");
            mets.setSchema("mods", "http://www.loc.gov/mods/v3",
                    "http://www.loc.gov/standards/mods/v3/mods-3-0.xsd");

            // MetsHdr
            MetsHdr metsHdr = new MetsHdr();
            metsHdr.setCREATEDATE(new Date()); // FIXME: CREATEDATE is now:
                                               // maybe should be item create
                                               // date?

            // Agent
            Agent agent = new Agent();
            agent.setROLE(Role.CUSTODIAN);
            agent.setTYPE(Type.ORGANIZATION);

            Name name = new Name();
            name.getContent()
                    .add(
                            new PCData(ConfigurationManager
                                    .getProperty("dspace.name")));
            agent.getContent().add(name);

            metsHdr.getContent().add(agent);

            mets.getContent().add(metsHdr);

            DmdSec dmdSec = new DmdSec();
            dmdSec.setID("DMD_hdl_" + item.getHandle());

            MdWrap mdWrap = new MdWrap();
            mdWrap.setMDTYPE(Mdtype.MODS);

            XmlData xmlData = new XmlData();
            createMODS(item, xmlData);

            mdWrap.getContent().add(xmlData);
            dmdSec.getContent().add(mdWrap);
            mets.getContent().add(dmdSec);

            // amdSec
            AmdSec amdSec = new AmdSec();
            amdSec.setID("TMD_hdl_" + item.getHandle());

            // FIXME: techMD here
            // License as <rightsMD><mdWrap><binData>base64encoded</binData>...
            InputStream licenseStream = findLicense(context, item);

            if (licenseStream != null)
            {
                RightsMD rightsMD = new RightsMD();
                MdWrap rightsMDWrap = new MdWrap();
                rightsMDWrap.setMIMETYPE("text/plain");
                rightsMDWrap.setMDTYPE(Mdtype.OTHER);
                rightsMDWrap.setOTHERMDTYPE("TEXT");

                BinData binData = new BinData();
                Base64 base64 = new Base64(licenseStream);

                binData.getContent().add(base64);
                rightsMDWrap.getContent().add(binData);
                rightsMD.getContent().add(rightsMDWrap);
                amdSec.getContent().add(rightsMD);
            }

            // FIXME: History data???? Nooooo!!!!
            mets.getContent().add(amdSec);

            // fileSec
            FileSec fileSec = new FileSec();
            boolean fileSecEmpty = true;

            Bundle[] bundles = item.getBundles();

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

                // Unusual condition, but if no bitstreams, skip this bundle
                if (bitstreams.length == 0)
                {
                    continue;
                }
                       
                // First: we skip the license bundle, since it's included
                // elsewhere
                if (bitstreams[0].getFormat().getID() == licenseFormat)
                {
                    continue;
                }

                // Create a fileGrp
                FileGrp fileGrp = new FileGrp();

                // Bundle name for USE attribute
                if ((bundles[i].getName() != null)
                        && !bundles[i].getName().equals(""))
                {
                    fileGrp.setUSE(bundles[i].getName());
                }

                for (int bits = 0; bits < bitstreams.length; bits++)
                {
                    // What's the persistent(-ish) ID?
                    String bitstreamPID = ConfigurationManager
                            .getProperty("dspace.url")
                            + "/bitstream/"
                            + item.getHandle()
                            + "/"
                            + bitstreams[bits].getSequenceID()
                            + "/"
                            + Util.encodeBitstreamName(bitstreams[bits].getName(),
                                    "UTF-8");

                    edu.harvard.hul.ois.mets.File file = new edu.harvard.hul.ois.mets.File();

                    /*
                     * ID: we use the unique part of the persistent ID, i.e. the
                     * Handle + sequence number, but with _'s instead of /'s so
                     * it's a legal xsd:ID.
                     */
                    String xmlIDstart = item.getHandle().replaceAll("/", "_")
                            + "_";

                    file.setID(xmlIDstart + bitstreams[bits].getSequenceID());

                    String groupID = "GROUP_" + xmlIDstart
                            + bitstreams[bits].getSequenceID();

                    /*
                     * If we're in THUMBNAIL or TEXT bundles, the bitstream is
                     * extracted text or a thumbnail, so we use the name to work
                     * out which bitstream to be in the same group as
                     */
                    if ((bundles[i].getName() != null)
                            && (bundles[i].getName().equals("THUMBNAIL") || bundles[i]
                                    .getName().equals("TEXT")))
                    {
                        // Try and find the original bitstream, and chuck the
                        // derived
                        // bitstream in the same group
                        Bitstream original = findOriginalBitstream(item,
                                bitstreams[bits]);

                        if (original != null)
                        {
                            groupID = "GROUP_" + xmlIDstart
                                    + original.getSequenceID();
                        }
                    }

                    file.setGROUPID(groupID);
                    file.setOWNERID(bitstreamPID);

                    // FIXME: ADMID should point to appropriate TechMD section
                    // above
                    file
                            .setMIMETYPE(bitstreams[bits].getFormat()
                                    .getMIMEType());

                    // FIXME: CREATED: no date
                    file.setSIZE(bitstreams[bits].getSize());
                    file.setCHECKSUM(bitstreams[bits].getChecksum());
                    file.setCHECKSUMTYPE(Checksumtype.MD5);

                    // FLocat: filename is as in records, or full URL
                    // FIXME: Duplicate filenames and characters illegal to
                    // local OS may cause problems
                    FLocat flocat = new FLocat();
                    flocat.setLOCTYPE(Loctype.URL);
                    if (fullURL)
                    {
                        flocat.setXlinkHref(bitstreamPID);
                    }
                    else
                    {
                        flocat.setXlinkHref(bitstreams[bits].getName());
                    }

                    // Add FLocat to File, and File to FileGrp
                    file.getContent().add(flocat);
                    fileGrp.getContent().add(file);
                }

                // Add fileGrp to fileSec
                fileSec.getContent().add(fileGrp);
                fileSecEmpty = false;
            }

            // Add fileSec to document
            if (!fileSecEmpty)
            {
                mets.getContent().add(fileSec);
            }
           
            // FIXME: Add Structmap here, but it is empty and we won't use it now.
            StructMap structMap = new StructMap();
            Div div = new Div();
            structMap.getContent().add(div);
            mets.getContent().add(structMap);

           
            mets.validate(new MetsValidator());

            mets.write(new MetsWriter(os));
        }
        catch (MetsException e)
        {
            // We don't pass up a MetsException, so callers don't need to
            // know the details of the METS toolkit
View Full Code Here


    {
        try
        {
            // Create the METS file
            Mets mets = new Mets();
        
            // Top-level stuff
            mets.setID(gensym("mets"));
            mets.setOBJID("hdl:" + item.getHandle());
            mets.setLABEL("DSpace Item");
            mets.setPROFILE(getProfile());
        
            // MetsHdr
            MetsHdr metsHdr = new MetsHdr();
            metsHdr.setCREATEDATE(new Date()); // FIXME: CREATEDATE is now:
                                               // maybe should be item create
            // date?

            // Agent
            Agent agent = new Agent();
            agent.setROLE(Role.CUSTODIAN);
            agent.setTYPE(Type.ORGANIZATION);
            Name name = new Name();
            name.getContent()
                    .add(new PCData(ConfigurationManager
                                    .getProperty("dspace.name")));
            agent.getContent().add(name);
            metsHdr.getContent().add(agent);
            mets.getContent().add(metsHdr);
        
            // add DMD sections
            // Each type element MAY be either just a MODS-and-crosswalk name, OR
            // a combination "MODS-name:crosswalk-name" (e.g. "DC:qDC").
            String dmdTypes[] = getDmdTypes(params);

            // record of ID of each dmdsec to make DMDID in structmap.
            String dmdGroup = gensym("dmd_group");
            String dmdId[] = new String[dmdTypes.length];
            for (int i = 0; i < dmdTypes.length; ++i)
            {
                dmdId[i] = gensym("dmd");
                XmlData xmlData = new XmlData();
                String xwalkName, metsName;
                String parts[] = dmdTypes[i].split(":", 2);
                if (parts.length > 1)
                {
                    metsName = parts[0];
                    xwalkName = parts[1];
                }
                else
                    xwalkName = metsName = dmdTypes[i];

                DisseminationCrosswalk xwalk = (DisseminationCrosswalk)
                  PluginManager.getNamedPlugin(DisseminationCrosswalk.class, xwalkName);
                if (xwalk == null)
                    throw new PackageValidationException("Cannot find "+dmdTypes[i]+" crosswalk plugin!");
                else
                    crosswalkToMets(xwalk, item, xmlData);

                DmdSec dmdSec = new DmdSec();
                dmdSec.setID(dmdId[i]);
                dmdSec.setGROUPID(dmdGroup);
                MdWrap mdWrap = new MdWrap();
                setMdType(mdWrap, metsName);
                mdWrap.getContent().add(xmlData);
                dmdSec.getContent().add(mdWrap);
                mets.getContent().add(dmdSec);
            }
        
            // Only add license AMD section if there are any licenses.
            // Catch authorization failures accessing license bitstreams
            // only if we are skipping unauthorized bitstreams.
            String licenseID = null;
            try
            {
            AmdSec amdSec = new AmdSec();
            addRightsMd(context, item, amdSec);
            if (amdSec.getContent().size() > 0)
            {
                licenseID = gensym("license");
                amdSec.setID(licenseID);
                mets.getContent().add(amdSec);
            }
            }
            catch (AuthorizeException e)
            {
                String unauth = (params == null) ? null : params.getProperty("unauthorized");
                if (!(unauth != null && unauth.equalsIgnoreCase("skip")))
                    throw e;
                else
                    log.warn("Skipping license metadata because of access failure: "+e.toString());
            }

            // FIXME: History data???? Nooooo!!!!

            // fileSec - all non-metadata bundles go into fileGrp,
            // and each bitstream therein into a file.
            // Create the bitstream-level techMd and div's for structmap
            // at the same time so we can connec the IDREFs to IDs.
            FileSec fileSec = new FileSec();
        
            String techMdType = getTechMdType(params);
            String parts[] = techMdType.split(":", 2);
            String xwalkName, metsName;
            if (parts.length > 1)
            {
                metsName = parts[0];
                xwalkName = parts[1];
            }
            else
                xwalkName = metsName = techMdType;

            DisseminationCrosswalk xwalk = (DisseminationCrosswalk)
              PluginManager.getNamedPlugin(DisseminationCrosswalk.class, xwalkName);
            if (xwalk == null)
                throw new PackageValidationException("Cannot find "+xwalkName+" crosswalk plugin!");

            // log the primary bitstream for structmap
            String primaryBitstreamFileID = null;

            // accumulate content DIV items to put in structMap later.
            List contentDivs = new ArrayList();

            // how to handle unauthorized bundle/bitstream:
            String unauth = (params == null) ? null : params.getProperty("unauthorized");

            Bundle[] bundles = item.getBundles();
            for (int i = 0; i < bundles.length; i++)
            {
                if (PackageUtils.isMetaInfoBundle(bundles[i]))
                    continue;

                // unauthorized bundle?
                // NOTE: This must match the logic in disseminate()
                if (!AuthorizeManager.authorizeActionBoolean(context,
                            bundles[i], Constants.READ))
                {
                    if (unauth != null &&
                        (unauth.equalsIgnoreCase("skip")))
                        continue;
                    else
                        throw new AuthorizeException("Not authorized to read Bundle named \""+bundles[i].getName()+"\"");
                }

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

                // Create a fileGrp
                FileGrp fileGrp = new FileGrp();
        
                // Bundle name for USE attribute
                String bName = bundles[i].getName();
                if ((bName != null) && !bName.equals(""))
                    fileGrp.setUSE(bundleToFileGrp(bName));
        
                // watch for primary bitstream
                int primaryBitstreamID = -1;
                boolean isContentBundle = false;
                if ((bName != null) && bName.equals("ORIGINAL"))
                {
                    isContentBundle = true;
                    primaryBitstreamID = bundles[i].getPrimaryBitstreamID();
                }

                for (int bits = 0; bits < bitstreams.length; bits++)
                {
                    // Check for authorization.  Handle unauthorized
                    // bitstreams to match the logic in disseminate(),
                    // i.e. "unauth=zero" means include a 0-length bitstream,
                    // "unauth=skip" means to ignore it (and exclude from
                    // manifest).
                    boolean auth = AuthorizeManager.authorizeActionBoolean(context,
                            bitstreams[bits], Constants.READ);
                    if (!auth)
                    {
                        if (unauth != null && unauth.equalsIgnoreCase("skip"))
                            continue;
                        else if (!(unauth != null && unauth.equalsIgnoreCase("zero")))
                            throw new AuthorizeException("Not authorized to read Bitstream, SID="+String.valueOf(bitstreams[bits].getSequenceID()));
                    }

                    String sid = String.valueOf(bitstreams[bits].getSequenceID());
        
                    edu.harvard.hul.ois.mets.File file = new edu.harvard.hul.ois.mets.File();
        
                    String xmlIDstart = "bitstream_";
                    String fileID = xmlIDstart + sid;

                    file.setID(fileID);

                    // log primary bitstream for later (structMap)
                    if (bitstreams[bits].getID() == primaryBitstreamID)
                        primaryBitstreamFileID = fileID;

                    // if this is content, add to structmap too:
                    if (isContentBundle)
                    {
                        Div div = new Div();
                        div.setID(gensym("div"));
                        div.setTYPE("DSpace Content Bitstream");
                        Fptr fptr = new Fptr();
                        fptr.setFILEID(fileID);
                        div.getContent().add(fptr);
                        contentDivs.add(div);
                    }

                    file.setSEQ(bitstreams[bits].getSequenceID());
        
                    String groupID = "GROUP_" + xmlIDstart + sid;
        
                    /*
                     * If we're in THUMBNAIL or TEXT bundles, the bitstream is
                     * extracted text or a thumbnail, so we use the name to work
                     * out which bitstream to be in the same group as
                     */
                    if ((bundles[i].getName() != null)
                            && (bundles[i].getName().equals("THUMBNAIL") ||
                                bundles[i].getName().startsWith("TEXT")))
                    {
                        // Try and find the original bitstream, and chuck the
                        // derived bitstream in the same group
                        Bitstream original = findOriginalBitstream(item,
                                bitstreams[bits]);
        
                        if (original != null)
                        {
                            groupID = "GROUP_" + xmlIDstart
                                    + original.getSequenceID();
                        }
                    }
        
                    file.setGROUPID(groupID);
                    file.setMIMETYPE(bitstreams[bits].getFormat().getMIMEType());
        
                    // FIXME: CREATED: no date

                    file.setSIZE(auth ? bitstreams[bits].getSize() : 0);

                    // translate checksum and type to METS, if available.
                    String csType = bitstreams[bits].getChecksumAlgorithm();
                    String cs = bitstreams[bits].getChecksum();
                    if (auth && cs != null && csType != null)
                    {
                        try
                        {
                            file.setCHECKSUMTYPE(Checksumtype.parse(csType));
                            file.setCHECKSUM(cs);
                        }
                        catch (MetsException e)
                        {
                            log.warn("Cannot set bitstream checksum type="+csType+" in METS.");
                        }
                    }
        
                    // FLocat: filename is MD5 checksum
                    FLocat flocat = new FLocat();
                    flocat.setLOCTYPE(Loctype.URL);
                    flocat.setXlinkHref(makeBitstreamName(bitstreams[bits]));

                    // Make bitstream techMD metadata, add to file.
                    String techID = "techMd_for_bitstream_"+bitstreams[bits].getSequenceID();
                    AmdSec fAmdSec = new AmdSec();
                    fAmdSec.setID(techID);
                    TechMD techMd = new TechMD();
                    techMd.setID(gensym("tech"));
                    MdWrap mdWrap = new MdWrap();
                    setMdType(mdWrap, metsName);
                    XmlData xmlData = new XmlData();
                    mdWrap.getContent().add(xmlData);
                    techMd.getContent().add(mdWrap);
                    fAmdSec.getContent().add(techMd);
                    mets.getContent().add(fAmdSec);
                    crosswalkToMets(xwalk, bitstreams[bits], xmlData);
                    file.setADMID(techID);

                    // Add FLocat to File, and File to FileGrp
                    file.getContent().add(flocat);
                    fileGrp.getContent().add(file);
                }
        
                // Add fileGrp to fileSec
                fileSec.getContent().add(fileGrp);
            }
        
            // Add fileSec to document
            mets.getContent().add(fileSec);
        
            // Create simple structMap: initial div represents the Item,
            // and user-visible content bitstreams are in its child divs.
            StringBuffer dmdIds = new StringBuffer();
            for (int i = 0; i < dmdId.length; ++i)
                dmdIds.append(" "+dmdId[i]);
            StructMap structMap = new StructMap();
            structMap.setID(gensym("struct"));
            structMap.setTYPE("LOGICAL");
            structMap.setLABEL("DSpace");
            Div div0 = new Div();
            div0.setID(gensym("div"));
            div0.setTYPE("DSpace Item");
            div0.setDMDID(dmdIds.substring(1));
            if (licenseID != null)
                div0.setADMID(licenseID);

            // if there is a primary bitstream, add FPTR to it.
            if (primaryBitstreamFileID != null)
            {
                Fptr fptr = new Fptr();
                fptr.setFILEID(primaryBitstreamFileID);
                div0.getContent().add(fptr);
            }

            // add DIV for each content bitstream
            div0.getContent().addAll(contentDivs);

            structMap.getContent().add(div0);

            // Does subclass have something to add to structMap?
            addStructMap(context, item, params, mets);

            mets.getContent().add(structMap);

            mets.validate(new MetsValidator());
        
            mets.write(new MetsWriter(out));
        }
        catch (MetsException e)
        {
            // We don't pass up a MetsException, so callers don't need to
            // know the details of the METS toolkit
View Full Code Here

            outStream = new FileOutputStream(pkgFile);

            // Generate a true manifest-only "package", no external files/data & no need to zip up
            if (params != null && params.getBooleanProperty("manifestOnly", false))
            {
                Mets manifest = makeManifest(context, dso, params, null);
                //only validate METS if specified (default = true)
                if(params.getBooleanProperty("validate", true))
                {
                    manifest.validate(new MetsValidator());
                }
                manifest.write(new MetsWriter(outStream));
            }
            else
            {
                // make a Zip-based package
                writeZipPackage(context, dso, params, outStream);
View Full Code Here

        // map of extra streams to put in Zip (these are located during makeManifest())
        MdStreamCache extraStreams = new MdStreamCache();
        ZipOutputStream zip = new ZipOutputStream(pkg);
        zip.setComment("METS archive created by DSpace " + Util.getSourceVersion());
        Mets manifest = makeManifest(context, dso, params, extraStreams);

        // copy extra (metadata, license, etc) bitstreams into zip, update manifest
        if (extraStreams != null)
        {
            for (Map.Entry<MdRef, InputStream> ment : extraStreams.getMap().entrySet())
            {
                MdRef ref = ment.getKey();

                // Both Deposit Licenses & CC Licenses which are referenced as "extra streams" may already be
                // included in our Package (if their bundles are already included in the <filSec> section of manifest).
                // So, do a special check to see if we need to link up extra License <mdRef> entries to the bitstream in the <fileSec>.
                // (this ensures that we don't accidentally add the same License file to our package twice)
                linkLicenseRefsToBitstreams(context, params, dso, ref);

                //If this 'mdRef' is NOT already linked up to a file in the package,
                // then its file must be missing.  So, we are going to add a new
                // file to the Zip package.
                if(ref.getXlinkHref()==null || ref.getXlinkHref().isEmpty())
                {
                    InputStream is = ment.getValue();

                    // create a hopefully unique filename within the Zip
                    String fname = gensym("metadata");
                    // link up this 'mdRef' to point to that file
                    ref.setXlinkHref(fname);
                    if (log.isDebugEnabled())
                    {
                        log.debug("Writing EXTRA stream to Zip: " + fname);
                    }
                    //actually add the file to the Zip package
                    ZipEntry ze = new ZipEntry(fname);
                    if (lmTime != 0)
                    {
                        ze.setTime(lmTime);
                    }
                    else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
                    {
                        ze.setTime(DEFAULT_MODIFIED_DATE);
                    }
                    zip.putNextEntry(ze);
                    Utils.copy(is, zip);
                    zip.closeEntry();

                    is.close();
                }
            }
        }

        // write manifest after metadata.
        ZipEntry me = new ZipEntry(METSManifest.MANIFEST_FILE);
        if (lmTime != 0)
        {
            me.setTime(lmTime);
        }
        else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
        {
            me.setTime(DEFAULT_MODIFIED_DATE);
        }

        zip.putNextEntry(me);

        // can only validate now after fixing up extraStreams
        // note: only validate METS if specified (default = true)
        if(params.getBooleanProperty("validate", true))
        {
            manifest.validate(new MetsValidator());
        }
        manifest.write(new MetsWriter(zip));
        zip.closeEntry();

        //write any bitstreams associated with DSpace object to zip package
        addBitstreamsToZip(context, dso, params, zip);
View Full Code Here

                              MdStreamCache extraStreams)
        throws MetsException, PackageValidationException, CrosswalkException, AuthorizeException, SQLException, IOException

    {
        // Create the METS manifest in memory
        Mets mets = new Mets();
       
        String identifier = "DB-ID-" + dso.getID();
        if(dso.getHandle()!=null)
        {
            identifier = dso.getHandle().replace('/', '-');
        }
       
        // this ID should be globally unique (format: DSpace_[objType]_[handle with slash replaced with a dash])
        mets.setID("DSpace_" + Constants.typeText[dso.getType()] + "_" + identifier);

        // identifies the object described by this document
        mets.setOBJID(makePersistentID(dso));
        mets.setTYPE(getObjectTypeString(dso));

        // this is the signature by which the ingester will recognize
        // a document it can expect to interpret.
        mets.setPROFILE(getProfile());

        MetsHdr metsHdr = makeMetsHdr(context, dso, params);
        if (metsHdr != null)
        {
            mets.getContent().add(metsHdr);
        }

        // add DMD sections
        // Each type element MAY be either just a MODS-and-crosswalk name, OR
        // a combination "MODS-name:crosswalk-name" (e.g. "DC:qDC").
        String dmdTypes[] = getDmdTypes(context, dso, params);

        // record of ID of each dmdsec to make DMDID in structmap.
        String dmdId[] = new String[dmdTypes.length];
        for (int i = 0; i < dmdTypes.length; ++i)
        {
            MdSec dmdSec = makeMdSec(context, dso, DmdSec.class, dmdTypes[i], params, extraStreams);
            if (dmdSec != null)
            {
                mets.getContent().add(dmdSec);
                dmdId[i] = dmdSec.getID();
            }
        }

        // add object-wide technical/source MD segments, get ID string:
        // Put that ID in ADMID of first div in structmap.
        String objectAMDID = addAmdSec(context, dso, params, mets, extraStreams);

        // Create simple structMap: initial div represents the Object's
        // contents, its children are e.g. Item bitstreams (content only),
        // Collection's members, or Community's members.
        StructMap structMap = new StructMap();
        structMap.setID(gensym("struct"));
        structMap.setTYPE("LOGICAL");
        structMap.setLABEL("DSpace Object");
        Div div0 = new Div();
        div0.setID(gensym("div"));
        div0.setTYPE("DSpace Object Contents");
        structMap.getContent().add(div0);

        // fileSec is optional, let object type create it if needed.
        FileSec fileSec = null;

        // Item-specific manifest - license, bitstreams as Files, etc.
        if (dso.getType() == Constants.ITEM)
        {
            // this tags file ID and group identifiers for bitstreams.
            String bitstreamIDstart = "bitstream_";
            Item item = (Item)dso;

            // how to handle unauthorized bundle/bitstream:
            String unauth = (params == null) ? null : params.getProperty("unauthorized");

            // fileSec - all non-metadata bundles go into fileGrp,
            // and each bitstream therein into a file.
            // Create the bitstream-level techMd and div's for structmap
            // at the same time so we can connect the IDREFs to IDs.
            fileSec = new FileSec();
            Bundle[] bundles = item.getBundles();
            for (int i = 0; i < bundles.length; i++)
            {
                if (!includeBundle(bundles[i]))
                {
                    continue;
                }

                // unauthorized bundle?
                // NOTE: This must match the logic in disseminate()
                if (!AuthorizeManager.authorizeActionBoolean(context,
                            bundles[i], Constants.READ))
                {
                    if (unauth != null &&
                        (unauth.equalsIgnoreCase("skip")))
                    {
                        continue;
                    }
                    else
                    {
                        throw new AuthorizeException("Not authorized to read Bundle named \"" + bundles[i].getName() + "\"");
                    }
                }

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

                // Create a fileGrp, USE = permuted Bundle name
                FileGrp fileGrp = new FileGrp();
                String bName = bundles[i].getName();
                if ((bName != null) && !bName.equals(""))
                {
                    fileGrp.setUSE(bundleToFileGrp(bName));
                }

                // add technical metadata for a bundle
                String techBundID = addAmdSec(context, bundles[i], params, mets, extraStreams);
                if (techBundID != null)
                {
                    fileGrp.setADMID(techBundID);
                }

                // watch for primary bitstream
                int primaryBitstreamID = -1;
                boolean isContentBundle = false;
                if ((bName != null) && bName.equals("ORIGINAL"))
                {
                    isContentBundle = true;
                    primaryBitstreamID = bundles[i].getPrimaryBitstreamID();
                }

                // For each bitstream, add to METS manifest
                for (int bits = 0; bits < bitstreams.length; bits++)
                {
                    // Check for authorization.  Handle unauthorized
                    // bitstreams to match the logic in disseminate(),
                    // i.e. "unauth=zero" means include a 0-length bitstream,
                    // "unauth=skip" means to ignore it (and exclude from
                    // manifest).
                    boolean auth = AuthorizeManager.authorizeActionBoolean(context,
                            bitstreams[bits], Constants.READ);
                    if (!auth)
                    {
                        if (unauth != null && unauth.equalsIgnoreCase("skip"))
                        {
                            continue;
                        }
                        else if (!(unauth != null && unauth.equalsIgnoreCase("zero")))
                        {
                            throw new AuthorizeException("Not authorized to read Bitstream, SID=" + String.valueOf(bitstreams[bits].getSequenceID()));
                        }
                    }

                    String sid = String.valueOf(bitstreams[bits].getSequenceID());
                    String fileID = bitstreamIDstart + sid;
                    edu.harvard.hul.ois.mets.File file = new edu.harvard.hul.ois.mets.File();
                    file.setID(fileID);
                    file.setSEQ(bitstreams[bits].getSequenceID());
                    fileGrp.getContent().add(file);

                    // set primary bitstream in structMap
                    if (bitstreams[bits].getID() == primaryBitstreamID)
                    {
                        Fptr fptr = new Fptr();
                        fptr.setFILEID(fileID);
                        div0.getContent().add(0, fptr);
                    }

                    // if this is content, add to structmap too:
                    if (isContentBundle)
                    {
                        div0.getContent().add(makeFileDiv(fileID, getObjectTypeString(bitstreams[bits])));
                    }

                    /*
                     * If we're in THUMBNAIL or TEXT bundles, the bitstream is
                     * extracted text or a thumbnail, so we use the name to work
                     * out which bitstream to be in the same group as
                     */
                    String groupID = "GROUP_" + bitstreamIDstart + sid;
                    if ((bundles[i].getName() != null)
                            && (bundles[i].getName().equals("THUMBNAIL") ||
                                bundles[i].getName().startsWith("TEXT")))
                    {
                        // Try and find the original bitstream, and chuck the
                        // derived bitstream in the same group
                        Bitstream original = findOriginalBitstream(item,
                                bitstreams[bits]);
                        if (original != null)
                        {
                                groupID = "GROUP_" + bitstreamIDstart
                                    + original.getSequenceID();
                        }
                    }
                    file.setGROUPID(groupID);
                    file.setMIMETYPE(bitstreams[bits].getFormat().getMIMEType());
                    file.setSIZE(auth ? bitstreams[bits].getSize() : 0);

                    // Translate checksum and type to METS
                    String csType = bitstreams[bits].getChecksumAlgorithm();
                    String cs = bitstreams[bits].getChecksum();
                    if (auth && cs != null && csType != null)
                    {
                        try
                        {
                            file.setCHECKSUMTYPE(Checksumtype.parse(csType));
                            file.setCHECKSUM(cs);
                        }
                        catch (MetsException e)
                        {
                            log.warn("Cannot set bitstream checksum type="+csType+" in METS.");
                        }
                    }

                    // FLocat: point to location of bitstream contents.
                    FLocat flocat = new FLocat();
                    flocat.setLOCTYPE(Loctype.URL);
                    flocat.setXlinkHref(makeBitstreamURL(bitstreams[bits], params));
                    file.getContent().add(flocat);

                    // technical metadata for bitstream
                    String techID = addAmdSec(context, bitstreams[bits], params, mets, extraStreams);
                    if (techID != null)
                    {
                        file.setADMID(techID);
                    }
                }
                fileSec.getContent().add(fileGrp);
            }
        }
        else if (dso.getType() == Constants.COLLECTION)
        {
            Collection collection = (Collection)dso;
            ItemIterator ii = collection.getItems();
            while (ii.hasNext())
            {
                //add a child <div> for each item in collection
                Item item = ii.next();
                Div childDiv = makeChildDiv(getObjectTypeString(item), item, params);
                if(childDiv!=null)
                {
                    div0.getContent().add(childDiv);
                }
            }

            // add metadata & info for Template Item, if exists
            Item templateItem = collection.getTemplateItem();
            if(templateItem!=null)
            {
                String templateDmdId[] = new String[dmdTypes.length];
                // index where we should add the first template item <dmdSec>.
                // Index = number of <dmdSecs> already added + number of <metsHdr> = # of dmdSecs + 1
                // (Note: in order to be a valid METS file, all dmdSecs must be before the 1st amdSec)
                int dmdIndex = dmdTypes.length + 1;
                //For each type of dmdSec specified,
                // add a new dmdSec which contains the Template Item metadata
                // (Note: Template Items are only metadata -- they have no content files)
                for (int i = 0; i < dmdTypes.length; ++i)
                {
                    MdSec templateDmdSec = makeMdSec(context, templateItem, DmdSec.class, dmdTypes[i], params, extraStreams);
                    if (templateDmdSec != null)
                    {
                        mets.getContent().add(dmdIndex, templateDmdSec);
                        dmdIndex++;
                        templateDmdId[i] = templateDmdSec.getID();
                    }
                }

                //Now add a child <div> in structMap to represent that Template Item
                Div templateItemDiv = new Div();
                templateItemDiv.setID(gensym("div"));
                templateItemDiv.setTYPE(getObjectTypeString(templateItem) + TEMPLATE_TYPE_SUFFIX);
                //Link up the dmdSec(s) for the Template Item to this <div>
                StringBuilder templateDmdIds = new StringBuilder();
                for (String currdmdId : templateDmdId)
                {
                    templateDmdIds.append(" ").append(currdmdId);
                }
                templateItemDiv.setDMDID(templateDmdIds.substring(1));
                //add this child <div> before the listing of normal Items
                div0.getContent().add(0, templateItemDiv);
            }

            // add link to Collection Logo, if one exists
            Bitstream logoBs = collection.getLogo();
            if (logoBs != null)
            {
                fileSec = new FileSec();
                addLogoBitstream(logoBs, fileSec, div0, params);
            }
        }
        else if (dso.getType() == Constants.COMMUNITY)
        {
            // Subcommunities are directly under "DSpace Object Contents" <div>,
            // but are labeled as Communities.
            Community subcomms[] = ((Community)dso).getSubcommunities();
            for (int i = 0; i < subcomms.length; ++i)
            {
                //add a child <div> for each subcommunity in this community
                Div childDiv = makeChildDiv(getObjectTypeString(subcomms[i]), subcomms[i], params);
                if(childDiv!=null)
                {
                    div0.getContent().add(childDiv);
                }
            }
            // Collections are also directly under "DSpace Object Contents" <div>,
            // but are labeled as Collections.
            Collection colls[] = ((Community)dso).getCollections();
            for (int i = 0; i < colls.length; ++i)
            {
                //add a child <div> for each collection in this community
                Div childDiv = makeChildDiv(getObjectTypeString(colls[i]), colls[i], params);
                if(childDiv!=null)
                {
                    div0.getContent().add(childDiv);
                }
            }
            //add Community logo bitstream
            Bitstream logoBs = ((Community)dso).getLogo();
            if (logoBs != null)
            {
                fileSec = new FileSec();
                addLogoBitstream(logoBs, fileSec, div0, params);
            }
        }
        else if (dso.getType() == Constants.SITE)
        {
            // This is a site-wide <structMap>, which just lists the top-level
            // communities.  Each top level community is referenced by a div.
            Community comms[] = Community.findAllTop(context);
            for (int i = 0; i < comms.length; ++i)
            {
                //add a child <div> for each top level community in this site
                Div childDiv = makeChildDiv(getObjectTypeString(comms[i]),
                        comms[i], params);
                if(childDiv!=null)
                {
                    div0.getContent().add(childDiv);
                }
            }
        }

        //Only add the <fileSec> to the METS file if it has content.  A <fileSec> must have content.
        if (fileSec != null && fileSec.getContent()!=null && !fileSec.getContent().isEmpty())
        {
            mets.getContent().add(fileSec);
        }
       
        mets.getContent().add(structMap);

        // set links to metadata for object -- after type-specific
        // code since that can add to the object metadata.
        StringBuilder dmdIds = new StringBuilder();
        for (String currdmdId : dmdId)
View Full Code Here

TOP

Related Classes of edu.harvard.hul.ois.mets.Mets

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.