Example usage for com.mongodb.gridfs GridFS createFile

List of usage examples for com.mongodb.gridfs GridFS createFile

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFS createFile.

Prototype

public GridFSInputFile createFile() 

Source Link

Document

This method creates an empty GridFSInputFile instance.

Usage

From source file:org.exist.mongodb.xquery.gridfs.Store.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//  w  w  w  .j av a 2  s . c  o  m
        // Verify clientid and get client
        String mongodbClientId = args[0].itemAt(0).getStringValue();
        MongodbClientStore.getInstance().validate(mongodbClientId);
        MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId);

        // Get parameters
        String dbname = args[1].itemAt(0).getStringValue();
        String bucket = args[2].itemAt(0).getStringValue();
        String documentName = args[3].itemAt(0).getStringValue();
        String contentType = getMimeType(args[4], documentName);

        LOG.info(String.format("Storing document %s (%s)", documentName, contentType));

        // Actual content: File object, doc() element, base64...
        Item content = args[5].itemAt(0);

        // Get database
        DB db = client.getDB(dbname);

        // Creates a GridFS instance for the specified bucket
        GridFS gfs = new GridFS(db, bucket);

        // Create file
        GridFSInputFile gfsFile = gfs.createFile();

        // Set meta data
        gfsFile.setFilename(documentName);
        gfsFile.setContentType(contentType);

        StopWatch stopWatch = new StopWatch();

        // Write data
        if (StringUtils.endsWithAny(documentName, nonCompressables)) {
            writeRaw(gfsFile, stopWatch, content);
        } else {
            int dataType = content.getType();
            writeCompressed(gfsFile, stopWatch, content, dataType);
        }

        LOG.info(String.format("serialization time: %s", stopWatch.getTime()));

        // Report identifier
        return new StringValue(gfsFile.getId().toString());

    } catch (XPathException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, ex.getMessage(), ex);

    } catch (MongoException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, GridfsModule.GRFS0002, ex.getMessage());

    } catch (Throwable ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, GridfsModule.GRFS0003, ex.getMessage());
    }

}

From source file:org.grails.datastore.mapping.mongo.gridfs.GridfsEntityPersister.java

License:Apache License

public GridFSInputFile getNative(Object obj, GridFS gridFS, byte[] data) throws IOException {
    Assert.notNull(obj);/* w  w w  .jav a  2s . c om*/
    Assert.notNull(gridFS);

    GridFSInputFile nativeEntry = data == null ? gridFS.createFile() : gridFS.createFile(data);

    // adapted code from NativeEntryEntityPersister.persistEntity()
    SessionImplementor<Object> si = (SessionImplementor<Object>) session;

    ProxyFactory proxyFactory = getProxyFactory();
    // if called internally, obj can potentially be a proxy, which won't work.
    obj = proxyFactory.unwrap(obj);

    PersistentEntity persistentEntity = getMappingContext().getPersistentEntity(obj.getClass().getName());

    final List<PersistentProperty> props = persistentEntity.getPersistentProperties();
    final Map<Association, List<Serializable>> toManyKeys = new HashMap<Association, List<Serializable>>();

    final EntityAccess entityAccess = createEntityAccess(persistentEntity, obj, nativeEntry);
    Object k = readObjectIdentifier(entityAccess, persistentEntity.getMapping());

    for (PersistentProperty prop : props) {
        PropertyMapping<Property> pm = prop.getMapping();
        final Property mappedProperty = pm.getMappedForm();
        boolean ordinalEnum = false;
        String key = null;
        if (mappedProperty != null) {
            key = mappedProperty.getTargetName();
            if (prop.getType().isEnum() && mappedProperty.getEnumTypeObject() == EnumType.ORDINAL) {
                ordinalEnum = true;
            }
        }
        if (key == null)
            key = prop.getName();
        if ((prop instanceof Simple)) {
            Object propValue = entityAccess.getProperty(prop.getName());

            if (ordinalEnum && (propValue instanceof Enum)) {
                propValue = ((Enum) propValue).ordinal();
            }
            setEntryValue(nativeEntry, key, propValue);
        } else if ((prop instanceof Basic)) {
            Basic basic = (Basic) prop;
            CustomTypeMarshaller customTypeMarshaller = basic.getCustomTypeMarshaller();
            if (customTypeMarshaller != null && customTypeMarshaller.supports(getSession().getDatastore())) {
                Object propValue = entityAccess.getProperty(prop.getName());
                customTypeMarshaller.write(prop, propValue, nativeEntry);
            } else {
                Object propValue = entityAccess.getProperty(prop.getName());

                if (!(key.equals("contentType") && propValue == null)
                        && !(key.equals("uploadDate") && propValue == null)
                        && !(key.equals("filename") && propValue == null)
                        && !(key.equals("md5") && propValue == null)) {
                    setEntryValue(nativeEntry, key, propValue);
                }
            }
        } else if ((prop instanceof Custom)) {
            CustomTypeMarshaller customTypeMarshaller = ((Custom) prop).getCustomTypeMarshaller();
            if (customTypeMarshaller.supports(getSession().getDatastore())) {
                Object propValue = entityAccess.getProperty(prop.getName());
                customTypeMarshaller.write(prop, propValue, nativeEntry);
            }
        } else if (prop instanceof OneToMany) {
            final OneToMany oneToMany = (OneToMany) prop;

            final Object propValue = entityAccess.getProperty(oneToMany.getName());
            if (propValue instanceof Collection) {
                Collection associatedObjects = (Collection) propValue;
                if (isInitializedCollection(associatedObjects)) {
                    PersistentEntity associatedEntity = oneToMany.getAssociatedEntity();
                    if (associatedEntity != null) {
                        EntityPersister associationPersister = (EntityPersister) getSession()
                                .getPersister(associatedEntity);
                        if (associationPersister != null) {
                            PersistentCollection persistentCollection;
                            boolean newCollection = false;
                            if (associatedObjects instanceof PersistentCollection) {
                                persistentCollection = (PersistentCollection) associatedObjects;
                            } else {
                                Class associationType = associatedEntity.getJavaClass();
                                persistentCollection = getPersistentCollection(associatedObjects,
                                        associationType);
                                entityAccess.setProperty(oneToMany.getName(), persistentCollection);
                                persistentCollection.markDirty();
                                newCollection = true;
                            }
                            if (persistentCollection.isDirty()) {
                                persistentCollection.resetDirty();
                                List<Serializable> keys = associationPersister.persist(associatedObjects);
                                toManyKeys.put(oneToMany, keys);
                                if (newCollection) {
                                    entityAccess.setProperty(oneToMany.getName(), associatedObjects);
                                }
                            }
                        }
                    }
                }
            }
        } else if (prop instanceof ManyToMany) {
            final ManyToMany manyToMany = (ManyToMany) prop;

            final Object propValue = entityAccess.getProperty(manyToMany.getName());
            if (propValue instanceof Collection) {
                Collection associatedObjects = (Collection) propValue;
                if (isInitializedCollection(associatedObjects)) {
                    setManyToMany(persistentEntity, obj, nativeEntry, manyToMany, associatedObjects,
                            toManyKeys);
                }
            }
        } else if (prop instanceof ToOne) {
            ToOne association = (ToOne) prop;
            if (prop instanceof Embedded) {
                // For embedded properties simply set the entry value, the underlying implementation
                // will have to store the embedded entity in an appropriate way (as a sub-document in a document store for example)
                handleEmbeddedToOne(association, key, entityAccess, nativeEntry);
            } else if (association.doesCascade(CascadeType.PERSIST)
                    && association.getAssociatedEntity() != null) {
                final Object associatedObject = entityAccess.getProperty(prop.getName());
                if (associatedObject != null) {
                    Serializable associationId;
                    NativeEntryEntityPersister associationPersister = (NativeEntryEntityPersister) getSession()
                            .getPersister(associatedObject);
                    if (proxyFactory.isInitialized(associatedObject)
                            && !getSession().contains(associatedObject)) {
                        Serializable tempId = associationPersister.getObjectIdentifier(associatedObject);
                        if (tempId == null) {
                            if (association.isOwningSide()) {
                                tempId = getSession().persist(associatedObject);
                            }
                        }
                        associationId = tempId;
                    } else {
                        associationId = associationPersister.getObjectIdentifier(associatedObject);
                    }

                    // handling of hasOne inverse key
                    if (association.isForeignKeyInChild()) {
                        DBObject cachedAssociationEntry = (DBObject) si
                                .getCachedEntry(association.getAssociatedEntity(), associationId);
                        if (cachedAssociationEntry != null) {
                            if (association.isBidirectional()) {
                                Association inverseSide = association.getInverseSide();
                                if (inverseSide != null) {
                                    setEntryValue(cachedAssociationEntry, inverseSide.getName(),
                                            formulateDatabaseReference(association.getAssociatedEntity(),
                                                    inverseSide, (Serializable) k));
                                } else {
                                    setEntryValue(cachedAssociationEntry, key, formulateDatabaseReference(
                                            association.getAssociatedEntity(), inverseSide, (Serializable) k));
                                }
                            }
                        }

                        if (association.doesCascade(CascadeType.PERSIST)) {

                            if (association.isBidirectional()) {
                                Association inverseSide = association.getInverseSide();
                                if (inverseSide != null) {
                                    EntityAccess inverseAccess = new EntityAccess(inverseSide.getOwner(),
                                            associatedObject);
                                    inverseAccess.setProperty(inverseSide.getName(), obj);
                                }
                            }
                            associationPersister.persist(associatedObject);
                        }
                    }
                    // handle of standard many-to-one
                    else {
                        if (associationId != null) {
                            setEntryValue(nativeEntry, key,
                                    formulateDatabaseReference(persistentEntity, association, associationId));

                            if (association.isBidirectional()) {
                                Association inverse = association.getInverseSide();
                                // unwrap the entity in case it is a proxy, since we may need to update the reverse link.
                                Object inverseEntity = proxyFactory
                                        .unwrap(entityAccess.getProperty(association.getName()));
                                if (inverseEntity != null) {
                                    EntityAccess inverseAccess = createEntityAccess(
                                            association.getAssociatedEntity(), inverseEntity);
                                    Object entity = entityAccess.getEntity();
                                    if (inverse instanceof OneToMany) {
                                        Collection existingValues = (Collection) inverseAccess
                                                .getProperty(inverse.getName());
                                        if (existingValues == null) {
                                            existingValues = MappingUtils
                                                    .createConcreteCollection(inverse.getType());
                                            inverseAccess.setProperty(inverse.getName(), existingValues);
                                        }
                                        if (!existingValues.contains(entity))
                                            existingValues.add(entity);
                                    } else if (inverse instanceof ToOne) {
                                        inverseAccess.setProperty(inverse.getName(), entity);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    setEntryValue(nativeEntry, getPropertyKey(prop), null);
                }
            }
        } else if (prop instanceof EmbeddedCollection) {
            handleEmbeddedToMany(entityAccess, nativeEntry, prop, key);
        }
    }

    return nativeEntry;
}