Example usage for org.apache.poi.poifs.filesystem DirectoryEntry createDocument

List of usage examples for org.apache.poi.poifs.filesystem DirectoryEntry createDocument

Introduction

In this page you can find the example usage for org.apache.poi.poifs.filesystem DirectoryEntry createDocument.

Prototype


public DocumentEntry createDocument(final String name, final int size, final POIFSWriterListener writer)
        throws IOException;

Source Link

Document

create a new DocumentEntry; the data will be provided later

Usage

From source file:tv.amwa.maj.io.aaf.AAFBuilder.java

License:Apache License

public final static void generateAAFStructure(DirectoryEntry classDir, AAFWriterListener aafWriter,
        MetadataObject rootObject) throws IOException {

    ClassDefinition rootClass = MediaEngine.getClassDefinition(rootObject);

    //      if (rootClass instanceof PropertyDefinition)
    //         aafWriter.registerLocalID((PropertyDefinition) rootClass);

    String path = makePathForDirectory(classDir);
    classDir.setStorageClsid(new AAFClassID(rootClass.getAUID()));

    //      System.out.println(path + " " + classDir.getStorageClsid());
    //      System.out.println(path + File.separator + "properties");

    Set<PropertyDefinition> properties = rootClass.getAllPropertyDefinitions();
    if (rootObject instanceof MetaDefinition)
        ((MetaDefinition) rootObject).setAAFNamesInUse(true);
    SortedMap<? extends PropertyDefinition, ? extends PropertyValue> valueMap = rootClass
            .getProperties(rootObject);/*from   w w w.  j  a  v a2  s.c o  m*/
    if (rootObject instanceof MetaDefinition)
        ((MetaDefinition) rootObject).setAAFNamesInUse(false);

    int propertyCount = 0;
    int propertiesSize = 0;
    for (PropertyDefinition property : properties) {

        // No need to process optional not present values
        if (property.getIsOptional()) {
            if (!valueMap.containsKey(property))
                continue;
        }

        // No need to write object class property
        if (property.getAUID().equals(ObjectClassID))
            continue;

        // Not interested in member of properties in AAF serialization
        if (property.getAUID().equals(MemberOfID))
            continue;

        // Check to see if we don't have a value for everything else
        if (!valueMap.containsKey(property)) {
            System.err.println("Found a required property not in the value map for " + rootClass.getName() + "."
                    + property.getName() + ".");
            System.err.println(rootObject.toString());
            continue;
        }

        TypeDefinition propertyType = property.getTypeDefinition();
        PropertyValue value = valueMap.get(property);

        if (propertyType.equals(TypeDefinitions.ApplicationPluginObjectStrongReferenceSet)) {

            Set<PropertyValue> setElements = ((TypeDefinitionSet) propertyType).getElements(value);

            if (setElements.size() == 1) {
                // Possibly an extension class
                PropertyValue theElement = null;
                for (PropertyValue item : setElements)
                    theElement = item;
                ApplicationPluginObject plugin = (ApplicationPluginObject) theElement.getValue();
                if (!(plugin.getObjectClass().getAUID().equals(AAFConstants.ApplicationPluginObjectID))) {
                    classDir.setStorageClsid(new AAFClassID(plugin.getObjectClass().getAUID()));
                }
            }

            for (PropertyValue item : setElements) {
                // TODO unnecessarily defensive?
                if (!(item.getValue() instanceof ApplicationPluginObject))
                    continue;

                ApplicationPluginObject plugin = (ApplicationPluginObject) item.getValue();
                if (plugin == null)
                    continue;

                Set<AUID> extensionPropertyIDs = plugin.getExtensionPropertyIDs();
                for (AUID extensionPropertyID : extensionPropertyIDs) {
                    PropertyDefinition extensionPropertyDefinition = Warehouse
                            .lookForProperty(extensionPropertyID);
                    PropertyValue extensionPropertyValue = plugin.getExtensionProperty(extensionPropertyID);

                    if ((extensionPropertyDefinition != null) && (extensionPropertyValue != null)) {
                        propertyCount++;
                        aafWriter.registerLocalID(extensionPropertyDefinition);
                        aafWriter.addProperty(path, extensionPropertyDefinition, extensionPropertyValue);
                        propertiesSize += processPropertyValue(extensionPropertyDefinition,
                                extensionPropertyValue, classDir, aafWriter, path);
                    }
                }
            }
            continue;
        }

        aafWriter.registerLocalID(property);

        aafWriter.addProperty(path, property, value);
        propertyCount++;

        propertiesSize += processPropertyValue(property, value, classDir, aafWriter, path);
    }

    propertiesSize += 4 + 6 * propertyCount;
    classDir.createDocument(PROPERTIES_STREAMNAME, propertiesSize, aafWriter);
}

From source file:tv.amwa.maj.io.aaf.AAFBuilder.java

License:Apache License

final static int processPropertyValue(PropertyDefinition property, PropertyValue value, DirectoryEntry classDir,
        AAFWriterListener aafWriter, String path) throws IOException {

    int propertySize = 0;
    TypeDefinition propertyType = value.getType();
    String dirName = null;/*www .  ja  v a2 s .c  om*/

    if (property.getAUID().equals(AAFConstants.ParametersID)) {

        //         TypeDefinition setRefType = ((TypeDefinitionVariableArray) propertyType).getType();

        List<PropertyValue> setElements = ((TypeDefinitionVariableArray) propertyType).getElements(value);

        dirName = makeAAFPathPartReference(property, aafWriter.getLocalID(property.getAUID()));
        propertySize += dirName.length() * 2 + 2;

        int elementCount = 0;

        byte identificationSize = 16;

        classDir.createDocument(dirName + " index", 15 + ((8 + identificationSize) * setElements.size()),
                aafWriter);
        aafWriter.addIndexValue(path + File.separator + dirName + " index", value);

        for (PropertyValue setElement : setElements) {

            DirectoryEntry newSetDir = classDir
                    .createDirectory(dirName + "{" + Integer.toHexString(elementCount) + "}");
            generateAAFStructure(newSetDir, aafWriter, (MetadataObject) setElement.getValue());

            elementCount++;
        }

        return propertySize;
    }

    switch (propertyType.getTypeCategory()) {

    case WeakObjRef:
        propertySize += 21;
        aafWriter.registerWeakType((TypeDefinitionWeakObjectReference) propertyType);
        break;
    case StrongObjRef:
        MetadataObject propertyValue = (MetadataObject) value.getValue();
        dirName = makeAAFPathPartName(property, aafWriter.getLocalID(property.getAUID()));
        propertySize += dirName.length() * 2 + 2;

        DirectoryEntry newDir = classDir.createDirectory(dirName);
        generateAAFStructure(newDir, aafWriter, propertyValue);
        break;

    case Set:
        TypeDefinition setRefType = ((TypeDefinitionSet) propertyType).getElementType();

        Set<PropertyValue> setElements = ((TypeDefinitionSet) propertyType).getElements(value);

        if (property.getAUID().equals(PropertiesID)) {
            PropertyValue toRemove = null;
            for (PropertyValue element : setElements) {
                if (((PropertyDefinition) element.getValue()).getAUID().equals(ApplicationPluginsID)) {
                    toRemove = element;
                    break;
                }
            }

            if (toRemove != null) {
                setElements.remove(toRemove);
                aafWriter.setInterchangePath(path);
            }
        }

        if ((setRefType.getTypeCategory() != TypeCategory.StrongObjRef)
                && (setRefType.getTypeCategory() != TypeCategory.WeakObjRef)) {

            if (setElements.size() == 0)
                break;

            PropertyValue sampleValue = null;
            for (PropertyValue findMeASample : setElements) {
                sampleValue = findMeASample;
                break;
            }

            propertySize += setElements.size() * setRefType.lengthAsBytes(sampleValue);
            break;
        }

        dirName = makeAAFPathPartReference(property, aafWriter.getLocalID(property.getAUID()));
        propertySize += dirName.length() * 2 + 2;

        int elementCount = 0;

        if (setRefType.getTypeCategory() == TypeCategory.StrongObjRef) {

            PropertyValue sampleValue = null;
            for (PropertyValue findMeASample : setElements) {
                sampleValue = findMeASample;
                break;
            }

            ClassDefinition referencedValueClass = ((TypeDefinitionStrongObjectReference) setRefType)
                    .getObjectType();
            byte identificationSize = 0;
            PropertyDefinition uniqueProperty = null;
            if ((setElements.size() > 0) && (referencedValueClass.isUniquelyIdentified())) {
                uniqueProperty = referencedValueClass.getUniqueIdentifierProperty();
                PropertyValue sampleIDValue = uniqueProperty
                        .getPropertyValue((MetadataObject) sampleValue.getValue());
                identificationSize = (byte) uniqueProperty.getTypeDefinition().lengthAsBytes(sampleIDValue);
            } else {
                identificationSize = 0;
            }

            classDir.createDocument(dirName + " index", 15 + ((8 + identificationSize) * setElements.size()),
                    aafWriter);
            aafWriter.addIndexValue(path + File.separator + dirName + " index", value);
        }

        if (setRefType.getTypeCategory() == TypeCategory.WeakObjRef) {
            classDir.createDocument(dirName + " index", 9 + 16 * setElements.size(), aafWriter);
            aafWriter.addIndexValue(path + File.separator + dirName + " index", value);
        }

        for (PropertyValue setElement : setElements) {

            switch (setRefType.getTypeCategory()) {

            case StrongObjRef:
                DirectoryEntry newSetDir = classDir
                        .createDirectory(dirName + "{" + Integer.toHexString(elementCount) + "}");
                generateAAFStructure(newSetDir, aafWriter, (MetadataObject) setElement.getValue());
                break;
            case WeakObjRef:
                aafWriter.registerWeakType((TypeDefinitionWeakObjectReference) setRefType);
                break;
            default:
                break;
            }
            elementCount++;
        }

        break;

    case VariableArray:
        TypeDefinition arrayRefType = ((TypeDefinitionVariableArray) propertyType).getType();

        List<PropertyValue> listElements = ((TypeDefinitionVariableArray) propertyType).getElements(value);

        //         if ((arrayRefType.getTypeCategory() != TypeCategory.StrongObjRef) &&
        //               (arrayRefType.getTypeCategory() != TypeCategory.WeakObjRef)) {
        //            
        //            if (listElements.size() == 0) return;
        //            
        //            propertiesSize += listElements.size() * arrayRefType.lengthAsBytes(listElements.get(0));
        //            break;
        //         }

        if (arrayRefType.getTypeCategory() == TypeCategory.StrongObjRef) {
            dirName = makeAAFPathPartReference(property, aafWriter.getLocalID(property.getAUID()));
            propertySize += dirName.length() * 2 + 2;
            classDir.createDocument(dirName + " index", 12 + 4 * listElements.size(), aafWriter); // TODO size
            aafWriter.addIndexValue(path + File.separator + dirName + " index", value);
        }
        if (arrayRefType.getTypeCategory() == TypeCategory.WeakObjRef) {
            dirName = makeAAFPathPartReference(property, aafWriter.getLocalID(property.getAUID()));
            propertySize += dirName.length() * 2 + 2;
            classDir.createDocument(dirName + " index", 9 + 16 * listElements.size(), aafWriter);
            aafWriter.addIndexValue(path + File.separator + dirName + " index", value);
        }

        for (int x = 0; x < listElements.size(); x++) {

            PropertyValue listElement = listElements.get(x);

            switch (arrayRefType.getTypeCategory()) {

            case StrongObjRef:
                DirectoryEntry newArrayDir = classDir
                        .createDirectory(dirName + "{" + Integer.toHexString(x) + "}");
                generateAAFStructure(newArrayDir, aafWriter, (MetadataObject) listElement.getValue());
                break;
            case WeakObjRef:
                aafWriter.registerWeakType((TypeDefinitionWeakObjectReference) arrayRefType);
                break;
            case Character:
                // TODO Assuming UTF16String
                propertySize += ((String) listElement.getValue()).length() * 2 + 2;
                break;
            default:
                propertySize += listElement.getType().lengthAsBytes(listElement);
                break;
            } // switch
        } // for
        break;

    case Indirect:
        propertySize += value.getType().lengthAsBytes(value) + 1; // for the mystery 4c
        break;

    case Stream:
        dirName = makeAAFPathPartName(property, aafWriter.getLocalID(property.getAUID()));
        Stream stream = (Stream) value.getValue();
        DocumentEntry streamDocument = classDir.createDocument(dirName, (int) stream.getLength(), aafWriter);

        aafWriter.registerStreamDocument(streamDocument, stream);

        propertySize += dirName.length() * 2 + 2 + 1;
        break;

    default:
        if (property.getAUID().equals(ByteOrderPropertyID))
            propertySize += 2;
        else
            propertySize += value.getType().lengthAsBytes(value);
        break;
    }

    return propertySize;
}

From source file:tv.amwa.maj.io.aaf.AAFBuilder.java

License:Apache License

/**
 * @param args/*from  w w  w . j  a va  2  s . com*/
 */
public static void main(String[] args) throws IOException {

    if (args.length != 2)
        System.exit(1);

    final String inputFilename = args[0];
    final String outputFilename = args[1];

    POIFSReader r = new AAFReader();

    LocalAAFEventReader eventReader = new LocalAAFEventReader();
    r.registerListener(eventReader);

    AvidFactory.registerAvidExtensions();

    FileInputStream fis = null;

    long startTime = System.nanoTime();
    try {
        fis = new FileInputStream(inputFilename);
        r.read(new FileInputStream(inputFilename));
        eventReader.resolveEntries();
    } finally {
        if (fis != null)
            try {
                fis.close();
            } catch (Exception e) {
            }
    }
    long endTime = System.nanoTime();

    System.out.println("AAF file read in " + (endTime - startTime) + "ns.");

    ((PrefaceImpl) eventReader.getPreface()).setByteOrder(tv.amwa.maj.enumeration.ByteOrder.Big);
    System.out.println(eventReader.getPreface().getByteOrder());

    POIFSFileSystem outputFileSystem = new POIFSFileSystem();

    DirectoryEntry rootDir = outputFileSystem.getRoot();

    AAFWriterListener aafWriter = makeAAFWriterListener();
    DirectoryEntry metaDictionaryDir = rootDir.createDirectory(META_DICTIONARY_DIRNAME);
    DirectoryEntry prefaceDir = rootDir.createDirectory(PREFACE_DIRNAME);

    generateAAFStructure(prefaceDir, aafWriter, eventReader.getPreface());
    generateMetaDictionary(metaDictionaryDir, aafWriter, eventReader.getPreface());
    rootDir.createDocument(PROPERTIES_STREAMNAME, 70, aafWriter);
    rootDir.createDocument(REFERENCED_PROPERTIES_STREAMNAME, aafWriter.getReferencedPropertiesSize(),
            aafWriter);

    //       rootDir.setStorageClsid(
    //             (outputFileSystem.getBigBlockSize() == 4096) ?
    //                   new AAFClassID(AAFSignatureSSBin4K) :
    //                      new AAFClassID(AAFSignatureSSBinary));

    rootDir.setStorageClsid(new ClassID(rootEntryClassID, 0));

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outputFilename);
        outputFileSystem.writeFilesystem(fos);
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (Exception e) {
            }
    }

    // AAF puts a signature in bytes 8-23 of the file
    // POIFS cannot write this

    RandomAccessFile fixFile = null;
    FileChannel fixChannel = null;
    try {
        fixFile = new RandomAccessFile(outputFilename, "rw");
        fixChannel = fixFile.getChannel();

        fixChannel.position(8);
        if (outputFileSystem.getBigBlockSize() == 4096)
            fixChannel.write(ByteBuffer.wrap(AAFSignatureSSBin4KBytes));
        else
            fixChannel.write(ByteBuffer.wrap(AAFSignatureSSBinaryBytes));
    } finally {
        if (fixChannel != null)
            fixChannel.close();
    }
}

From source file:tv.amwa.maj.io.aaf.AAFFactory.java

License:Apache License

/**
 * <p>Write an AAF file with the given filename that is constructed from the given {@linkplain Preface preface}.<p>
 * /*from  w w  w.ja v  a  2 s.  c  o m*/
 * <p>Note that this version of MAJ only supports writing metadata-only files.</p>
 * 
 * @param preface Preface to use to construct an AAF file from.
 * @param outputFilename File path specification for the file to write the preface to.
 * 
 * @throws IOException An error occurred when writing the AAF file.
 * 
 * @see #readPreface(String)
 */
public final static void writePreface(Preface preface, String outputFilename) throws IOException {

    POIFSFileSystem outputFileSystem = new POIFSFileSystem();

    DirectoryEntry rootDir = outputFileSystem.getRoot();

    preface.updateDictionaries();
    //       System.out.println(preface);

    AAFWriterListener aafWriter = AAFBuilder.makeAAFWriterListener();
    DirectoryEntry metaDictionaryDir = rootDir.createDirectory(META_DICTIONARY_DIRNAME);
    DirectoryEntry prefaceDir = rootDir.createDirectory(PREFACE_DIRNAME);

    AAFBuilder.generateAAFStructure(prefaceDir, aafWriter, preface);
    AAFBuilder.generateMetaDictionary(metaDictionaryDir, aafWriter, preface);
    rootDir.createDocument(PROPERTIES_STREAMNAME, 70, aafWriter);
    rootDir.createDocument(REFERENCED_PROPERTIES_STREAMNAME, aafWriter.getReferencedPropertiesSize(),
            aafWriter);

    //       rootDir.setStorageClsid(
    //             (outputFileSystem.getBigBlockSize() == 4096) ?
    //                   new AAFClassID(AAFSignatureSSBin4K) :
    //                      new AAFClassID(AAFSignatureSSBinary));

    rootDir.setStorageClsid(new ClassID(rootEntryClassID, 0));

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outputFilename);
        outputFileSystem.writeFilesystem(fos);
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (Exception e) {
            }
    }

    // AAF puts a signature in bytes 8-23 of the file
    // POIFS cannot write this

    RandomAccessFile fixFile = null;
    FileChannel fixChannel = null;
    try {
        fixFile = new RandomAccessFile(outputFilename, "rw");
        fixChannel = fixFile.getChannel();

        fixChannel.position(8);
        if (outputFileSystem.getBigBlockSize() == 4096)
            fixChannel.write(ByteBuffer.wrap(AAFSignatureSSBin4KBytes));
        else
            fixChannel.write(ByteBuffer.wrap(AAFSignatureSSBinaryBytes));
    } finally {
        if (fixChannel != null)
            fixChannel.close();
    }
}