Example usage for com.mongodb.gridfs GridFSInputFile validate

List of usage examples for com.mongodb.gridfs GridFSInputFile validate

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFSInputFile validate.

Prototype

@Deprecated
public void validate() 

Source Link

Document

Verifies that the MD5 matches between the database and the local file.

Usage

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

/**
 * Save GRID FS file./*  w  w w . j  a  va  2s.c  o m*/
 * 
 * @param gfsInputFile
 *            the gfs input file
 * @param m
 *            the m
 */
private void saveGridFSFile(GridFSInputFile gfsInputFile, EntityMetadata m) {
    try {
        DBCollection coll = mongoDb.getCollection(m.getTableName() + MongoDBUtils.FILES);
        createUniqueIndexGFS(coll, ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());
        gfsInputFile.save();
        log.info("Input GridFS file: " + gfsInputFile.getFilename() + " is saved successfully in "
                + m.getTableName() + MongoDBUtils.CHUNKS + " and metadata in " + m.getTableName()
                + MongoDBUtils.FILES);
    } catch (MongoException e) {
        log.error("Error in saving GridFS file in " + m.getTableName() + MongoDBUtils.FILES + " or "
                + m.getTableName() + MongoDBUtils.CHUNKS + " collections.");
        throw new KunderaException("Error in saving GridFS file in " + m.getTableName() + MongoDBUtils.FILES
                + " or " + m.getTableName() + MongoDBUtils.CHUNKS + " collections. Caused By: ", e);
    }
    try {
        gfsInputFile.validate();
        log.info("Input GridFS file: " + gfsInputFile.getFilename() + " is validated.");
    } catch (MongoException e) {
        log.error(
                "Error in validating GridFS file in " + m.getTableName() + MongoDBUtils.FILES + " collection.");
        throw new KunderaException("Error in validating GridFS file in " + m.getTableName() + MongoDBUtils.FILES
                + " collection. Caused By: ", e);
    }
}

From source file:com.linuxbox.enkive.docstore.mongogrid.MongoGridDocStoreService.java

License:Open Source License

@Override
protected StoreRequestResult storeKnownHash(Document document, byte[] hash, byte[] data, int length)
        throws DocStoreException {
    try {//w  w  w.ja v  a  2  s  . c o  m
        final String identifier = getIdentifierFromHash(hash);
        final int shardKey = getShardIndexFromHash(hash);

        try {
            documentLockingService.lockWithRetries(identifier, DocStoreConstants.LOCK_TO_STORE, LOCK_RETRIES,
                    LOCK_RETRY_DELAY_MILLISECONDS);
        } catch (LockAcquisitionException e) {
            throw new DocStoreException("could not acquire lock to store document \"" + identifier + "\"");
        }
        try {
            if (fileExists(identifier)) {
                return new StoreRequestResultImpl(identifier, true, shardKey);
            }
            GridFSInputFile newFile = gridFS.createFile(new ByteArrayInputStream(data, 0, length));
            newFile.setFilename(identifier);
            setFileMetaData(newFile, document, shardKey);
            newFile.save();
            try {
                newFile.validate();
            } catch (MongoException e) {
                throw new DocStoreException("file saved to GridFS did not validate", e);
            }
            return new StoreRequestResultImpl(identifier, false, shardKey);
        } finally {
            documentLockingService.releaseLock(identifier);
        }
    } catch (Exception e) {
        LOGGER.error("Could not save document to MongoDB GridFS", e);
        throw new DocStoreException(e);
    }
}

From source file:com.linuxbox.enkive.docstore.mongogrid.MongoGridDocStoreService.java

License:Open Source License

/**
 * Since we don't know the name, we'll have to save the data before we can
 * determine the name. So save it under a random UUID, calculate the name,
 * and if the name is not already in the file system then rename it.
 * Otherwise delete it./*from   www  .  j  a va  2  s.c o  m*/
 * 
 * @throws DocSearchException
 */
@Override
protected StoreRequestResult storeAndDetermineHash(Document document, HashingInputStream inputStream)
        throws DocStoreException {
    final String temporaryName = java.util.UUID.randomUUID().toString();
    GridFSInputFile newFile = gridFS.createFile(inputStream);
    newFile.setFilename(temporaryName);
    setFileMetaData(newFile, document, -1);
    newFile.save();
    try {
        newFile.validate();
    } catch (MongoException e) {
        throw new DocStoreException("file saved to GridFS did not validate", e);
    }

    final byte[] actualHash = inputStream.getDigest();
    final String actualName = getIdentifierFromHash(actualHash);
    final int shardKey = getShardIndexFromHash(actualHash);

    try {
        try {
            documentLockingService.lockWithRetries(actualName, DocStoreConstants.LOCK_TO_STORE, LOCK_RETRIES,
                    LOCK_RETRY_DELAY_MILLISECONDS);
        } catch (LockAcquisitionException e) {
            gridFS.remove((ObjectId) newFile.getId());
            throw new DocStoreException("could not acquire lock to store document \"" + actualName + "\"");
        }

        // so now we're in "control" of that file

        try {
            if (fileExists(actualName)) {
                gridFS.remove(temporaryName);
                return new StoreRequestResultImpl(actualName, true, shardKey);
            } else {
                final boolean wasRenamed = setFileNameAndShardKey(newFile.getId(), actualName, shardKey);
                if (!wasRenamed) {
                    throw new DocStoreException("expected to find and rename a GridFS file with id \""
                            + newFile.getId() + "\" but could not find it");
                }
                return new StoreRequestResultImpl(actualName, false, shardKey);
            }
        } finally {
            documentLockingService.releaseLock(actualName);
        }
    } catch (LockServiceException e) {
        throw new DocStoreException(e);
    }
}

From source file:org.mule.transport.mongodb.MongoDBMessageDispatcher.java

License:Open Source License

protected Object doDispatchToBucket(MuleEvent event, String bucket) throws Exception {
    DB db;/*from ww w. j a  va  2s  . co m*/

    if (StringUtils.isNotBlank(connector.getMongoURI().getDatabase())) {
        db = connector.getMongo().getDB(connector.getMongoURI().getDatabase());

    } else {
        db = connector.getMongo().getDB(connector.getMongoURI().getDatabase());
    }

    GridFS gridFS = new GridFS(db, bucket);

    db.requestStart();

    Object payload = event.getMessage().getPayload();

    GridFSInputFile file = null;

    if (payload instanceof File) {
        file = gridFS.createFile((File) payload);
    }

    if (payload instanceof InputStream) {
        file = gridFS.createFile((InputStream) payload);
    }

    if (payload instanceof byte[]) {
        file = gridFS.createFile((byte[]) payload);
    }

    if (payload instanceof String) {
        file = gridFS.createFile(((String) payload).getBytes());
    }

    if (file == null) {
        throw new MongoDBException(
                String.format("Cannot persist objects of type %s to GridFS", payload.getClass()));
    }

    String filename = event.getMessage().getOutboundProperty(MongoDBConnector.PROPERTY_FILENAME, "");

    if (StringUtils.isNotBlank(filename)) {
        logger.debug("Setting filename on GridFS file to: " + filename);
        file.setFilename(filename);
    }

    String contentType = event.getMessage().getOutboundProperty(MongoDBConnector.PROPERTY_CONTENT_TYPE, "");

    if (StringUtils.isBlank(contentType) && event.getEndpoint().getProperties().containsKey("contentType")) {
        contentType = (String) event.getEndpoint().getProperty("contentType");
    }

    if (StringUtils.isNotBlank(contentType)) {
        logger.debug("Setting contentType on GridFS file to: " + contentType);
        file.setContentType(contentType);
    }

    logger.debug("Attempting to save file: " + file.getFilename());

    Date startTime = new Date();
    file.save();
    Date endTime = new Date();

    long elapsed = endTime.getTime() - startTime.getTime();

    logger.debug(String.format("GridFS file %s saved in %s seconds", file.getId(), elapsed / 1000.0));

    try {
        file.validate();
    } catch (MongoException ex) {
        if (ex.getMessage().startsWith("md5 differ")) {
            logger.error("MD5 checksum mismatch while saving the file. "
                    + "This may be the real deal or is possibly an issue that keeps recurring with"
                    + " some releases of the Java driver ");
        }
    }

    ObjectId id = (ObjectId) file.getId();
    event.getMessage().setOutboundProperty(MongoDBConnector.PROPERTY_OBJECT_ID, id.toStringMongod());

    db.requestDone();

    return file;
}