org.mongodb.Document - java examples

Here are the examples of the java api org.mongodb.Document taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

61 Examples 7

19 View Complete Implementation : QueryTest.java
Copyright Apache License 2.0
Author : trishagee
@Test
public void shouldFindAllDoreplacedentsWithTheNameCharlesAndOnlyReturnNameAndId() {
    // Given
    Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74));
    collection.insert(charlie.toDoreplacedent());
    Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854));
    collection.insert(bob.toDoreplacedent());
    // When
    // TODO create the correct query to find Charlie by name (see above)
    Doreplacedent query = null;
    // TODO use this query, combined with the "fields" selector, to get a list of result doreplacedents with only the name and ID fields
    List<Doreplacedent> results = null;
    // Then
    replacedertThat(results.size(), is(1));
    Doreplacedent theOnlyResult = results.get(0);
    // ID is always included unless specificatlly excluded
    replacedertThat((String) theOnlyResult.get("_id"), is(charlie.getId()));
    replacedertThat((String) theOnlyResult.get("name"), is(charlie.getName()));
    replacedertThat(theOnlyResult.get("address"), is(nullValue()));
    replacedertThat(theOnlyResult.get("books"), is(nullValue()));
}

19 View Complete Implementation : MongoFSOnTopOfGridFSTest.java
Copyright Apache License 2.0
Author : dbuschman7
// 
// internal
private void dumpChunks(String bucket, Object id, PrintStream out) {
    MongoCollection<Doreplacedent> collection = database.getCollection(bucket + ".chunks", MongoCollectionOptions.builder().build());
    MongoCursor<Doreplacedent> cursor = collection.find(new Doreplacedent("files_id", id)).sort(new Doreplacedent("n", 1)).get();
    while (cursor.hasNext()) {
        Doreplacedent current = cursor.next();
        out.println(current.toString());
    }
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
private void setExpiresAt(final Doreplacedent filesQuery, final Doreplacedent chunksQuery, final Date when, final boolean multi) {
    // files collection
    Doreplacedent filesUpdate = // 
    new Doreplacedent().append(MongoFileConstants.expireAt.toString(), // 
    when).append(MongoFileConstants.deleted.toString(), // 
    when.before(new Date()));
    filesUpdate = new Doreplacedent().append("$set", filesUpdate);
    // 
    getFilesCollection().find(filesQuery).withWriteConcern(// 
    WriteConcern.JOURNALED).update(filesUpdate);
    // chunks collection - wait until the file objects are removed
    Doreplacedent chunksUpdate = // 
    new Doreplacedent().append(MongoFileConstants.expireAt.toString(), when);
    chunksUpdate = new Doreplacedent("$set", chunksUpdate);
    // 
    getChunksCollection().find(chunksQuery).withWriteConcern(// 
    WriteConcern.JOURNALED).update(chunksUpdate);
}

19 View Complete Implementation : FindAndModifyTest.java
Copyright Apache License 2.0
Author : trishagee
@Test
public void shouldUpdateDoreplacedentAndReturnNewDoreplacedent() {
    // Given
    Doreplacedent order1 = new Doreplacedent("orderNo", 1L).append("product", "Some Book").append("quanreplacedy", 2);
    collection.insert(order1);
    // When
    // TODO create query to find order1 by ID
    Doreplacedent query = null;
    // TODO use one of the find and modify methods combined with the query to increment the quanreplacedy of order1 by one and return
    // the updated doreplacedent
    Doreplacedent resultOfFindAndModify = null;
    // Then
    replacedertThat((int) resultOfFindAndModify.get("quanreplacedy"), is(3));
}

19 View Complete Implementation : MongoFileTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test
public void testGetters() {
    Doreplacedent surrogate = // 
    new Doreplacedent().append(MongoFileConstants.compressedLength.name(), 123L);
    MongoFile mongoFile = new MongoFile(null, surrogate);
    replacedertEquals(123, mongoFile.getStorageLength());
    replacedertEquals(-1, mongoFile.getInt(MongoFileConstants.chunkSize));
    replacedertEquals(234, mongoFile.getLong(MongoFileConstants.chunkSize, 234));
    replacedertEquals(1234.56, mongoFile.getDouble(MongoFileConstants.chunkSize, 1234.56), 0.01);
    replacedertEquals("def", mongoFile.getString(MongoFileConstants.chunkSize, "def"));
    ObjectId objectId = new ObjectId();
    replacedertEquals(objectId, mongoFile.getObjectId(MongoFileConstants._id, objectId));
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
private void checkForManifestIndex(final MongoCollection<Doreplacedent> coll) {
    String name = MongoFileConstants.manifestId.name();
    // check for existing
    for (Doreplacedent doreplacedent : coll.tools().getIndexes()) {
        if (name.equals(doreplacedent.get("name"))) {
            return;
        }
    }
    // build one
    Index idx = // 
    Index.builder().addKey(name, // 
    OrderBy.ASC).name(// 
    name).sparse().background(// 
    true).build();
    coll.tools().createIndexes(java.util.Collections.singletonList(idx));
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * Returns a MongoFile for the preplaceded in file url
 *
 * @param url
 *
 * @return a reader object
 *
 * @throws MongoException
 * @throws IllegalArgumentException
 *             if required parameters are null
 */
public MongoFile findOne(final MongoFileUrl url) {
    if (url == null) {
        throw new IllegalArgumentException("url cannot be null");
    }
    MongoCursor<Doreplacedent> cursor = // 
    filesCollection.find(new Doreplacedent().append(MongoFileConstants._id.toString(), url.getMongoFileId())).get();
    if (!cursor.hasNext()) {
        return null;
    }
    Doreplacedent file = deletedFileCheck(cursor.next());
    return file == null ? null : new MongoFile(this, file);
}

19 View Complete Implementation : FileChunksInputStreamSource.java
Copyright Apache License 2.0
Author : dbuschman7
byte[] getChunk(final int i) {
    if (store == null) {
        throw new IllegalStateException("No MongoFileStore instance defined!");
    }
    Doreplacedent chunk = store.getChunksCollection().find(new Doreplacedent("files_id", file.getId()).append("n", i)).get().next();
    if (chunk == null) {
        throw new MongoException("Can't find a chunk!  file id: " + file.getId().toString() + " chunk: " + i);
    }
    return (byte[]) chunk.get("data");
}

19 View Complete Implementation : MongoFileTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test(expected = IllegalArgumentException.clreplaced)
public void testGetBooleanInvalid() {
    Doreplacedent surrogate = // 
    new Doreplacedent().append(MongoFileConstants.chunkCount.name(), "This is a string");
    MongoFile mongoFile = new MongoFile(null, surrogate);
    replacedertTrue(mongoFile.getBoolean(MongoFileConstants.chunkCount, false));
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * finds a list of files matching the given query
 *
 * @param query
 * @param sort
 * @return the MongoFileCursor object
 * @throws MongoException
 */
public MongoFileCursor find(final Doreplacedent query, final Doreplacedent sort) {
    MongoView<Doreplacedent> c = this.getFilesCollection().find(query);
    if (sort != null) {
        c.sort(sort);
    }
    MongoCursor<Doreplacedent> cursor = c.get();
    return new MongoFileCursor(this, cursor);
}

19 View Complete Implementation : CodecsTest.java
Copyright Apache License 2.0
Author : trishagee
@Test
public void shouldUseCodecsToSimplifyRetrieval() {
    // Given
    // TODO: setup a collection of Person
    MongoCollection<Person> peopleCollection = null;
    Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74));
    peopleCollection.insert(charlie);
    Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854));
    peopleCollection.insert(bob);
    // When
    Doreplacedent query = new Doreplacedent("name", "Charles");
    // TODO: query the collection of Person objects for people with the name Charles
    List<Person> results = null;
    // Then
    replacedertThat(results.size(), is(1));
    replacedertThat(results.get(0), is(charlie));
}

19 View Complete Implementation : MongoFileTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test(expected = MongoException.clreplaced)
public void noMd5() {
    Doreplacedent surrogate = new Doreplacedent();
    MongoFile mongoFile = new MongoFile(null, surrogate);
    mongoFile.validate();
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
// 
// remove methods
// ////////////////////
/**
 * Give a file an expiration date so I can be removed and resources its recovered.
 *
 * Use the TimeMachine DSL to easily create expiration dates.
 *
 * This uses MongoDB's TTL indexes feature to allow a server background thread to remove the file. According to their doreplacedentation,
 * this may not happen immediately at the time the file is set to expire.
 *
 * NOTE: The MongoFileStore has remove methods which perform immediate removal of the file in the MongoFileStore.
 *
 * @param file
 *            the MongoFile to fix
 * @param when
 *            - the date to expire the file by
 *
 * @throws MalformedURLException
 */
public void expireFile(final MongoFile file, final Date when) throws MalformedURLException {
    MongoFileUrl url = file.getURL();
    Doreplacedent filesQuery = new Doreplacedent("_id", url.getMongoFileId());
    Doreplacedent chunksQuery = new Doreplacedent("files_id", url.getMongoFileId());
    setExpiresAt(filesQuery, chunksQuery, when, false);
}

19 View Complete Implementation : QueryTest.java
Copyright Apache License 2.0
Author : trishagee
// BONUS - same as previous test but excluding a single field, not including one
@Test
public void shouldFindAllDoreplacedentsWithTheNameCharlesAndExcludeAddressInReturn() {
    // Given
    Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74));
    collection.insert(charlie.toDoreplacedent());
    Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854));
    collection.insert(bob.toDoreplacedent());
    // When
    // TODO create the correct query to find Charlie by name (see above)
    Doreplacedent query = null;
    // TODO use this query, combined with the "fields" selector, to get a list of result doreplacedents without address subdoreplacedent
    List<Doreplacedent> results = null;
    // Then
    replacedertThat(results.size(), is(1));
    Doreplacedent theOnlyResult = results.get(0);
    replacedertThat((String) theOnlyResult.get("_id"), is(charlie.getId()));
    replacedertThat((String) theOnlyResult.get("name"), is(charlie.getName()));
    replacedertThat(theOnlyResult.get("address"), is(nullValue()));
    replacedertThat((List<Integer>) theOnlyResult.get("books"), is(charlie.getBookIds()));
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * Delete all files that match the given criteria
 *
 * NOTE: this is not asynchronous
 *
 * @param query
 */
public void remove(final Doreplacedent query) {
    remove(query, false);
}

19 View Complete Implementation : RetreiveTest.java
Copyright Apache License 2.0
Author : trishagee
// @Test
// public void shouldConstructListOfPersonFromQueryResultsJava8() {
// // Given
// Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74));
// collection.insert(charlie.toDoreplacedent());
// 
// Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854));
// collection.insert(bob.toDoreplacedent());
// 
// // When
// List<Person> results = new ArrayList<>();
// // TODO: lambda version here
// 
// // Then
// replacedertThat(results.size(), is(2));
// replacedertThat(results, contains(charlie, bob));
// }
// Other ways of getting stuff out of the database
@Test
public void shouldRetrieveBobFromTheDatabase() {
    // Given
    Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854));
    collection.insert(bob.toDoreplacedent());
    // When
    // TODO: get this from querying the collection.  Hint: you can find just one
    Doreplacedent result = null;
    // Then
    replacedertThat((String) result.get("_id"), is("bob"));
}

19 View Complete Implementation : MongoFile.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * Add an object to the metadata subclreplaced
 *
 * @param key
 * @param value
 */
public Object setInMetaData(final String key, final Object value) {
    Doreplacedent object = getMetaData();
    if (object == null) {
        object = new Doreplacedent();
        setMetaData(object);
    }
    return object.put(key, value);
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * finds a list of files matching the given filename
 *
 * @param filename
 * @param sort
 * @return the MongoFileCursor object
 * @throws MongoException
 */
public MongoFileCursor find(final String filename, final Doreplacedent sort) {
    return find(new Doreplacedent(MongoFileConstants.filename.toString(), filename), sort);
}

19 View Complete Implementation : MongoFile.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * Gets the file metadata.
 *
 * @param metadata
 *            metadata to be set
 */
public void setMetaData(final Doreplacedent metadata) {
    put(MongoFileConstants.metadata, metadata);
}

19 View Complete Implementation : MongoFSOnTopOfGridFSTest.java
Copyright Apache License 2.0
Author : dbuschman7
public clreplaced MongoFSOnTopOfGridFSTest {

    private static final String bucket = "original";

    private static final String DB_NAME = "MongoFSTest-onTop";

    private static Doreplacedent ID = new Doreplacedent(MongoFileConstants._id.name(), new ObjectId());

    private static MongoDatabase database;

    private static MongoClient mongoClient;

    // initializer
    @BeforeClreplaced
    public static void initial() {
        mongoClient = MongoTestConfig.construct();
        mongoClient.dropDatabase(DB_NAME);
        database = new MongoDatabase(mongoClient.getDB(DB_NAME));
    }

    @Test
    public void doTheTest() throws IOException {
        createOriginalGridFSFile();
        verifyReadFromRefactoredGridFS();
        verifyReadFromMongoFS();
    }

    public Object createOriginalGridFSFile() throws IOException {
        com.mongodb.gridfs.GridFS gridFS = new com.mongodb.gridfs.GridFS(database.getSurrogate(), bucket);
        com.mongodb.gridfs.GridFSInputFile file = gridFS.createFile("originalGridFS.txt");
        file.setId(ID.get(MongoFileConstants._id.toString()));
        file.put("aliases", Arrays.asList("one", "two", "three"));
        file.put(MongoFileConstants.contentType.toString(), "text/plain");
        file.setMetaData(new BasicDBObject("key", "value"));
        OutputStream stream = file.getOutputStream();
        try {
            byte[] bytes = LoremIpsum.LOREM_IPSUM.getBytes();
            stream.write(bytes);
        } finally {
            stream.close();
        }
        System.out.println("Original GridFS (2.11.4)");
        System.out.println("==============================");
        System.out.println(String.format("id = %s, filepath = %s", file.getId(), file.getFilename()));
        System.out.println("==============================");
        System.out.println(JSONHelper.prettyPrint(file.toString()));
        System.out.println("======");
        dumpChunks(bucket, file.getId(), System.out);
        System.out.println("==============================");
        System.out.println();
        // md5 validation
        try {
            file.validate();
        } catch (MongoException e) {
            fail(e.getMessage());
        }
        replacedertEquals(com.mongodb.gridfs.GridFS.DEFAULT_CHUNKSIZE, file.getChunkSize());
        replacedertEquals(1, file.numChunks());
        com.mongodb.gridfs.GridFSDBFile findOne = gridFS.findOne(ID.getSurrogate());
        replacedertNotNull(findOne);
        ByteArrayOutputStream out = new ByteArrayOutputStream(32 * 1024);
        new BytesCopier(findOne.getInputStream(), out).transfer(true);
        replacedertEquals(LoremIpsum.LOREM_IPSUM, out.toString());
        return ID;
    }

    public void verifyReadFromRefactoredGridFS() throws IOException {
        me.lightspeed7.mongofs.gridfs.GridFS gridFS = new me.lightspeed7.mongofs.gridfs.GridFS(database.getSurrogate(), bucket);
        me.lightspeed7.mongofs.gridfs.GridFSDBFile findOne = gridFS.findOne(ID.getSurrogate());
        replacedertNotNull(findOne);
        ByteArrayOutputStream out = new ByteArrayOutputStream(32 * 1024);
        new BytesCopier(findOne.getInputStream(), out).transfer(true);
        replacedertEquals(LoremIpsum.LOREM_IPSUM, out.toString());
        System.out.println("Preplaceded - RefactoredGridFS");
    }

    public void verifyReadFromMongoFS() throws IOException {
        MongoFileStore store = new MongoFileStore(database, MongoFileStoreConfig.builder().bucket(bucket).build());
        MongoFile findOne = store.findOne((ObjectId) ID.get(MongoFileConstants._id.name()));
        ByteArrayOutputStream out = new ByteArrayOutputStream(32 * 1024);
        MongoFileReader mongoFileReader = new MongoFileReader(store, findOne);
        InputStream inputStream = mongoFileReader.getInputStream();
        try {
            new BytesCopier(inputStream, out).transfer(true);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        replacedertEquals(LoremIpsum.LOREM_IPSUM, out.toString());
        System.out.println("Preplaceded - MongoFS");
    }

    // 
    // internal
    private void dumpChunks(String bucket, Object id, PrintStream out) {
        MongoCollection<Doreplacedent> collection = database.getCollection(bucket + ".chunks", MongoCollectionOptions.builder().build());
        MongoCursor<Doreplacedent> cursor = collection.find(new Doreplacedent("files_id", id)).sort(new Doreplacedent("n", 1)).get();
        while (cursor.hasNext()) {
            Doreplacedent current = cursor.next();
            out.println(current.toString());
        }
    }
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * Run a test command to the mongoDB to test connectivity and the server is running
 *
 * @return true if a connection could be made
 *
 * @throws MongoException
 */
public boolean validateConnection() {
    try {
        // String command = String.format(
        // "{ touch: \"%s\", data: false, index: true }",
        // config.getBucket() + ".files");
        Doreplacedent doc = // 
        new Doreplacedent().append("touch", // 
        config.getBucket() + ".files").append("data", // 
        Boolean.FALSE).append("index", Boolean.TRUE);
        CommandResult commandResult = filesCollection.getDatabase().executeCommand(doc);
        if (!commandResult.isOk()) {
            throw new MongoException(commandResult.getErrorMessage());
        }
        return true;
    } catch (Exception e) {
        throw new MongoException("Unable to run command on server", e);
    }
}

19 View Complete Implementation : MongoFileTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test(expected = IllegalArgumentException.clreplaced)
public void testGetDoubleKeyNull() {
    Doreplacedent surrogate = new Doreplacedent();
    MongoFile mongoFile = new MongoFile(null, surrogate);
    mongoFile.getDouble(null, 0.0);
}

19 View Complete Implementation : ChunksStatisticsAdapter.java
Copyright Apache License 2.0
Author : dbuschman7
public void collectFromChunk(final Doreplacedent obj) {
    byte[] data = (byte[]) obj.get("data");
    // acreplacedulate
    ++chunkCount;
    this.messageDigest.update(data);
    this.totalSize += data.length;
}

19 View Complete Implementation : MongoFileTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test(expected = IllegalArgumentException.clreplaced)
public void testGetStringKeyNull() {
    Doreplacedent surrogate = new Doreplacedent();
    MongoFile mongoFile = new MongoFile(null, surrogate);
    mongoFile.getString(null, "def");
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
private Doreplacedent deletedFileCheck(final Doreplacedent file) {
    if (new MongoFile(this, file).isDeleted()) {
        return null;
    }
    return file;
}

19 View Complete Implementation : MongoManifestQueryTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test
public void testSearchZipArchiveRegex() throws Exception {
    MongoZipArchiveQuery zipArchiveQuery = store.findInZipArchive(manifest.getZip());
    replacedertNotNull(zipArchiveQuery);
    Pattern namesRegex = Pattern.compile("^file.*");
    Doreplacedent query = new Doreplacedent(MongoFileConstants.filename.name(), namesRegex);
    MongoFileCursor find = zipArchiveQuery.find(query);
    replacedertNotNull(find);
    replacedertTrue(find.hasNext());
    MongoFile mongoFile = find.next();
    replacedertNotNull(mongoFile);
    replacedertEquals("file1.txt", mongoFile.getFilename());
    replacedertTrue(find.hasNext());
    mongoFile = find.next();
    replacedertNotNull(mongoFile);
    replacedertEquals("file2.txt", mongoFile.getFilename());
    // should only be two returned
    replacedertFalse(find.hasNext());
}

19 View Complete Implementation : StorageComparisonTest.java
Copyright Apache License 2.0
Author : dbuschman7
// internal
protected void dumpChunks(final String bucket, final Object id, final PrintStream out) {
    MongoCollection<Doreplacedent> collection = database.getCollection(bucket + ".chunks", MongoCollectionOptions.builder().build());
    MongoCursor<Doreplacedent> cursor = collection.find(new Doreplacedent("files_id", id)).sort(new Doreplacedent("n", 1)).get();
    while (cursor.hasNext()) {
        Doreplacedent current = cursor.next();
        out.println(current.toString());
    }
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * finds a list of files matching the given query
 *
 * @param query
 * @return the MongoFileCursor object
 * @throws MongoException
 */
public MongoFileCursor find(final Doreplacedent query) {
    return find(query, null);
}

19 View Complete Implementation : FindAndModifyTest.java
Copyright Apache License 2.0
Author : trishagee
@Test
public void shouldUpdateDoreplacedentAndReturnOriginalDoreplacedent() {
    // Given
    Doreplacedent order1 = new Doreplacedent("orderNo", 1L).append("product", "Some Book").append("status", "PENDING");
    collection.insert(order1);
    // When
    // TODO create query to find order1 by ID
    Doreplacedent query = null;
    // TODO use one of the find and modify methods combined with the query to change the status of order1 to "APPROVED" but return
    // the original doreplacedent
    Doreplacedent resultOfFindAndModify = null;
    // Then
    replacedertThat((String) resultOfFindAndModify.get("status"), is("PENDING"));
    replacedertThat((String) collection.find(query).getOne().get("status"), is("APPROVED"));
}

19 View Complete Implementation : MongoFile.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * Object to hold the state of the file's metatdata. To persist this outside of MongoFS, use the getURL() and persist that.
 *
 * @author David Buschman
 */
public clreplaced MongoFile implements InputFile {

    private final Doreplacedent surrogate;

    private final MongoFileStore store;

    private StorageFormat format;

    /**
     * Construct a MongoFile object for reading data
     *
     * @param store
     * @param o
     */
    /* package */
    MongoFile(final MongoFileStore store, final Doreplacedent surrogate) {
        this.store = store;
        this.surrogate = surrogate;
        this.format = fetchFormat(surrogate);
    }

    private StorageFormat fetchFormat(final Doreplacedent surrogate) {
        String format = surrogate.getString(MongoFileConstants.format);
        if (format == null) {
            format = surrogate.getString(MongoFileConstants.compressionFormat);
        }
        if (format == null) {
            return StorageFormat.GRIDFS;
        }
        return StorageFormat.find(format);
    }

    /**
     * Construct a MongoFile object for writing data
     *
     * @param collection
     * @param url
     */
    /* package */
    MongoFile(final MongoFileStore store, final MongoFileUrl url, final long chunkSize) {
        this.store = store;
        this.format = url.getFormat();
        surrogate = new Doreplacedent();
        surrogate.put(MongoFileConstants._id.toString(), url.getMongoFileId());
        surrogate.put(MongoFileConstants.uploadDate.toString(), new Date());
        surrogate.put(MongoFileConstants.chunkSize.toString(), chunkSize);
        surrogate.put(MongoFileConstants.filename.toString(), url.getFilePath());
        surrogate.put(MongoFileConstants.contentType.toString(), url.getMediaType());
        if (url.getFormat() != null) {
            surrogate.put(MongoFileConstants.format.toString(), url.getFormat().getCode());
        }
    }

    // 
    // logic methods
    // //////////////////
    private String getBucketName() {
        return store.getFilesCollection().getName().split("\\.")[0];
    }

    /**
     * Saves the file entry meta data to the files collection
     *
     * @throws MongoException
     */
    public void save() {
        store.getFilesCollection().save(surrogate);
    }

    /**
     * Verifies that the MD5 matches between the database and the local file. This should be called after transferring a file.
     *
     * @throws MongoException
     */
    public void validate() {
        MongoFileConstants md5key = MongoFileConstants.md5;
        String md5 = getString(md5key);
        if (md5 == null) {
            throw new MongoException("no md5 stored");
        }
        Doreplacedent cmd = new Doreplacedent("filemd5", get(MongoFileConstants._id));
        cmd.put("root", getBucketName());
        Doreplacedent res = store.getFilesCollection().getDatabase().executeCommand(cmd).getResponse();
        if (res != null && res.containsKey(md5key.toString())) {
            String m = res.get(md5key.toString()).toString();
            if (m.equals(md5)) {
                return;
            }
            throw new MongoException("md5 differ.  mine [" + md5 + "] theirs [" + m + "]");
        }
        // no md5 from the server
        throw new MongoException("no md5 returned from server: " + res);
    }

    public MongoFileUrl getURL() throws MalformedURLException {
        // compression and encrypted read from stored format
        URL url = Parser.construct(getId(), getFilename(), getContentType(), this.format);
        return MongoFileUrl.construct(url);
    }

    /**
     * Return an input stream to read the file content data from
     *
     * @return an input stream to read from
     *
     * @throws IOException
     */
    public final InputStream getInputStream() throws IOException {
        // /////////////////////////////////////////////////////////
        // replacedembled backwards
        // 
        // Plain Text -- returned <- counting <- chunks
        // Compressed -- returned <- gzip <- counting <- chunks
        // Encryption -- returned <- decrypt <- counting <- chunks
        // Enc + Comp -- returned <- gzip <- decrypt <- counting <- chunks
        // 
        // /////////////////////////////////////////////////////////
        InputStream returned = new FileChunksInputStreamSource(store, this);
        returned = new CountingInputStream(this, returned);
        if (getURL().isStoredEncrypted()) {
            if (store.getConfig().getEncryption() == null) {
                throw new IllegalStateException("File is stored in ecrypted but store is not configured for decryption");
            }
            returned = new DecryptInputStream(store.getConfig().getEncryption(), this, returned);
        }
        if (getURL().isStoredCompressed()) {
            returned = new GZIPInputStream(returned);
        }
        return returned;
    }

    /**
     * Copy the content to the given output stream
     *
     * @param out
     *            the output stream to write to
     *
     * @param flush
     *            should the output stream be flush when all the data has been written.
     *
     * @throws IOException
     */
    public OutputStream readInto(final OutputStream out, final boolean flush) throws IOException {
        new BytesCopier(getInputStream(), out).transfer(flush);
        return out;
    }

    /**
     * Read the contents on the file into a String
     *
     * NOTE : This uses heap memory to store the contents on the file, the user is responsible to know that the file can safely fit into the
     * memory space of the running application. The memory allocated is chunkSize * chunkCount
     *
     * @return the file contents as a string
     * @throws IOException
     */
    public String readIntoString() throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream(this.getChunkSize() * this.getChunkCount());
        new BytesCopier(getInputStream(), out).transfer(true);
        return out.toString("UTF-8");
    }

    // 
    // read-only fields
    // ///////////////////////
    /**
     * Returns the number of chunks that store the file data.
     *
     * @return number of chunks
     */
    public int getChunkCount() {
        // for compatibility with legacy GridFS implementations, if -1 comes
        // back, then legacy file
        int chunkCount = getInt(MongoFileConstants.chunkCount, -1);
        if (chunkCount == -1) {
            chunkCount = (int) Math.ceil((double) getLength() / getChunkSize());
        }
        return chunkCount;
    }

    /**
     * Gets the file's length.
     *
     * @return the length of the file
     */
    public long getLength() {
        return getLong(MongoFileConstants.length);
    }

    /**
     * Gets the file's length on MongoDB, this is the actual size stored.
     *
     * NOTE: For compressed and encrypted files, this size will differ from the getLength() method.
     *
     * @return the length of the file
     */
    public long getStorageLength() {
        if (containsKey(MongoFileConstants.storage.name())) {
            return getLong(MongoFileConstants.storage);
        } else {
            // deprecated, files stored from 0.7.x versions and before
            return getLong(MongoFileConstants.compressedLength);
        }
    }

    /**
     * Gets the observed MD5 during transfer
     *
     * @return md5
     */
    public String getMD5() {
        return getString(MongoFileConstants.md5);
    }

    /**
     * Gets the id.
     *
     * @return the id of the file.
     */
    public ObjectId getId() {
        return (ObjectId) surrogate.get("_id");
    }

    /**
     * Gets the filename.
     *
     * @return the name of the file
     */
    public String getFilename() {
        return getString(MongoFileConstants.filename);
    }

    /**
     * Gets the content type.
     *
     * @return the content type
     */
    public String getContentType() {
        return getString(MongoFileConstants.contentType);
    }

    /**
     * Gets the size of a chunk.
     *
     * @return the chunkSize
     */
    public int getChunkSize() {
        return getInt(MongoFileConstants.chunkSize);
    }

    /**
     * Gets the upload date.
     *
     * @return the date
     */
    public Date getUploadDate() {
        return (Date) get(MongoFileConstants.uploadDate);
    }

    /**
     * Has the file been marked deleted but not yet removed from the store
     *
     * @return true is the file is scheduled for deletion
     */
    public boolean isDeleted() {
        return getBoolean(MongoFileConstants.deleted, false);
    }

    // 
    // getters and setters
    // /////////////////////////
    /**
     * Gets the aliases from the metadata. note: to set aliases, call put( "aliases" , List<String> )
     *
     * @return list of aliases
     */
    @SuppressWarnings("unchecked")
    public List<String> getAliases() {
        return (List<String>) get(MongoFileConstants.aliases);
    }

    public void setAliases(final List<String> aliases) {
        put(MongoFileConstants.aliases, aliases);
    }

    /**
     * Gets the file metadata.
     *
     * @return the metadata
     */
    public Doreplacedent getMetaData() {
        Object object = get(MongoFileConstants.metadata);
        if (object == null) {
            return null;
        }
        return new Doreplacedent((BasicDBObject) object);
    }

    /**
     * Gets the file metadata.
     *
     * @param metadata
     *            metadata to be set
     */
    public void setMetaData(final Doreplacedent metadata) {
        put(MongoFileConstants.metadata, metadata);
    }

    /**
     * Add an object to the metadata subclreplaced
     *
     * @param key
     * @param value
     */
    public Object setInMetaData(final String key, final Object value) {
        Doreplacedent object = getMetaData();
        if (object == null) {
            object = new Doreplacedent();
            setMetaData(object);
        }
        return object.put(key, value);
    }

    /**
     * Internal use only
     *
     * @param when
     */
    /* package */
    void setExpiresAt(final Date when) {
        put(MongoFileConstants.expireAt, when);
    }

    /**
     * Return the expiration date for this file.
     *
     * @return the expiration date for the file, null if is has none
     */
    public Date getExpiresAt() {
        return getDate(MongoFileConstants.expireAt, null);
    }

    // 
    // helpers
    // /////////////////
    /**
     * Put a value into the object for a given key
     *
     * @param key
     * @param value
     * @return the previous value
     */
    public Object put(final String key, final Object value) {
        if (key == null) {
            throw new IllegalArgumentException("key should never be null");
        }
        return surrogate.put(key, value);
    }

    /**
     * Set a value based on the defined MongoFileConstants
     *
     * @param key
     * @param value
     * @return the current value, or the default if its null
     */
    public Object put(final MongoFileConstants key, final Object value) {
        if (key == null) {
            throw new IllegalArgumentException("key should never be null");
        }
        return surrogate.put(key.name(), value);
    }

    /**
     * Get an the value on any attribute in the system
     *
     * @param key
     * @return the current value
     */
    public Object get(final String key) {
        if (key == null) {
            throw new IllegalArgumentException("Key should never be null");
        }
        return surrogate.get(key);
    }

    /**
     * Get an the value on any attribute in the system
     *
     * @param key
     * @return the current value
     */
    public Object get(final MongoFileConstants key) {
        if (key == null) {
            throw new IllegalArgumentException("Key should never be null");
        }
        return surrogate.get(key.name());
    }

    /**
     * Return the value for the given key as a string
     *
     * @param key
     *
     * @return the string value
     */
    public String getString(final MongoFileConstants key) {
        return (String) surrogate.get(key.name());
    }

    /**
     * Return the value for the given key as a integer
     *
     * @param key
     *
     * @return the key's value as an integer
     */
    public int getInt(final MongoFileConstants key) {
        return getInt(key, -1);
    }

    /**
     * Return the value for the given key as a long
     *
     * @param key
     *
     * @return the value as a long
     */
    public long getLong(final MongoFileConstants key) {
        return getLong(key, -1);
    }

    /**
     * Returns the value of a field as an <code>int</code>.
     *
     * @param key
     *            the field to look for
     * @param def
     *            the default to return
     * @return the field value (or default)
     */
    public int getInt(final MongoFileConstants key, final int def) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        Object value = surrogate.get(key.name());
        if (value == null) {
            return def;
        }
        return Integer.parseInt(value.toString());
    }

    /**
     * Returns the value of a field as an <code>long</code>.
     *
     * @param key
     *            the field to look for
     * @param def
     *            the default to return
     * @return the field value (or default)
     */
    public long getLong(final MongoFileConstants key, final long def) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        Object value = surrogate.get(key.name());
        if (value == null) {
            return def;
        }
        return Long.parseLong(value.toString());
    }

    /**
     * Returns the value of a field as an <code>double</code>.
     *
     * @param key
     *            the field to look for
     * @param def
     *            the default to return
     * @return the field value (or default)
     */
    public double getDouble(final MongoFileConstants key, final double def) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        Object value = surrogate.get(key.name());
        if (value == null) {
            return def;
        }
        return Double.parseDouble(value.toString());
    }

    /**
     * Returns the value of a field as a string
     *
     * @param key
     *            the field to look up
     * @param def
     *            the default to return
     * @return the value of the field, converted to a string
     */
    public String getString(final MongoFileConstants key, final String def) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        Object value = surrogate.get(key.name());
        if (value == null) {
            return def;
        }
        return value.toString();
    }

    /**
     * Returns the value of a field as a boolean
     *
     * @param key
     *            the field to look up
     * @param def
     *            the default value in case the field is not found
     * @return the value of the field, converted to a string
     */
    public boolean getBoolean(final MongoFileConstants key, final boolean def) {
        Object foo = surrogate.get(key.name());
        if (foo == null) {
            return def;
        }
        if (foo instanceof Number) {
            return ((Number) foo).intValue() > 0;
        }
        if (foo instanceof Boolean) {
            return ((Boolean) foo).booleanValue();
        }
        throw new IllegalArgumentException("can't coerce to bool:" + foo.getClreplaced());
    }

    /**
     * Returns the object id or def if not set.
     *
     * @param key
     *            The field to return
     * @param def
     *            the default value in case the field is not found
     * @return The field object value or def if not set.
     */
    public ObjectId getObjectId(final MongoFileConstants key, final ObjectId def) {
        final Object foo = surrogate.get(key.toString());
        return (foo != null) ? (ObjectId) foo : def;
    }

    /**
     * Returns the date or def if not set.
     *
     * @param key
     *            The key to return
     * @param def
     *            the default value in case the field is not found
     * @return The field object value or def if not set.
     */
    public Date getDate(final MongoFileConstants key, final Date def) {
        final Object foo = surrogate.get(key.toString());
        return (foo != null) ? (Date) foo : def;
    }

    /**
     * Does a key exist in the object
     *
     * @param key
     *
     * @return true if it exists
     */
    public boolean containsKey(final String key) {
        return this.surrogate.containsKey(key);
    }

    // private Set<String> keySet() {
    // 
    // Set<String> keys = new HashSet<String>();
    // keys.addAll(MongoFileConstants.getFields(true));
    // keys.addAll(surrogate.keySet());
    // return keys;
    // }
    @Override
    public String toString() {
        return surrogate.toString();
    }

    public boolean isCompressed() {
        return this.format.isCompressed();
    }

    public boolean isEncrypted() {
        return this.format.isEncrypted();
    }

    public boolean isExpandedZipFile() {
        if (0 == this.getInt(MongoFileConstants.manifestNum, -1)) {
            return true;
        }
        return false;
    }
}

19 View Complete Implementation : InsertTest.java
Copyright Apache License 2.0
Author : trishagee
@Test
public void shouldTurnAPersonIntoADoreplacedent() {
    // Given
    Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854));
    // When
    Doreplacedent bobAsDoreplacedent = bob.toDoreplacedent();
    // Then
    String expectedDoreplacedent = "{" + " \"_id\" : \"bob\"," + " \"name\" : \"Bob The Amazing\"," + " \"address\" : {" + " \"street\" : \"123 Fake St\"," + " \"city\" : \"LondonTown\"," + " \"phone\" : 1234567890" + " }," + " \"books\" : [27464, 747854] " + "}";
    replacedertThat(bobAsDoreplacedent.toString(), is(expectedDoreplacedent));
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * Delete all files that match the given criteria
 *
 * This code was taken from -- https://github.com/mongodb/mongo-java-driver/pull/171
 *
 * @param query
 *            the selection criteria
 * @param async
 *            - can the file be deleted asynchronously
 * @throws IllegalArgumentException
 *             if required parameters are null
 */
public void remove(final Doreplacedent query, final boolean async) {
    if (query == null) {
        throw new IllegalArgumentException("query can not be null");
    }
    // can't remove chunks without files_id thus keep them
    List<ObjectId> filesIds = new ArrayList<ObjectId>();
    for (MongoFile f : find(query)) {
        // add all files in from the expanded zip file
        if (f.isExpandedZipFile()) {
            for (MongoFile f2 : this.getManifest(f).getFiles()) {
                filesIds.add(f2.getId());
            }
        }
        filesIds.add(f.getId());
    }
    Doreplacedent filesQuery = new Doreplacedent("_id", new Doreplacedent("$in", filesIds));
    Doreplacedent chunksQuery = new Doreplacedent("files_id", new Doreplacedent("$in", filesIds));
    // flag delete always for quick "logically" removal
    setExpiresAt(filesQuery, chunksQuery, TimeMachine.now().backward(1).seconds().inTime(), true);
    // do the real delete if requested
    if (!async) {
        // remove files from bucket
        WriteResult writeResult = getFilesCollection().remove(filesQuery);
        if (writeResult.getCount() > 0) {
            // then remove chunks, for those file objects
            getChunksCollection().remove(chunksQuery);
        }
    }
}

19 View Complete Implementation : QueryTest.java
Copyright Apache License 2.0
Author : trishagee
// BONUS
@Test
public void shouldReturnADoreplacedentWithAPhoneNumberLessThan1000000000() {
    // Given
    Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74));
    collection.insert(charlie.toDoreplacedent());
    Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 987654321), asList(27464, 747854));
    collection.insert(bob.toDoreplacedent());
    // When
    // TODO build up a query which checks the numeric value
    Doreplacedent query = null;
    // TODO use this query to get a List of matching Doreplacedents from the database
    List<Doreplacedent> results = null;
    replacedertThat(results.size(), is(1));
    replacedertThat((String) results.get(0).get("_id"), is(bob.getId()));
}

19 View Complete Implementation : MongoFile.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * Verifies that the MD5 matches between the database and the local file. This should be called after transferring a file.
 *
 * @throws MongoException
 */
public void validate() {
    MongoFileConstants md5key = MongoFileConstants.md5;
    String md5 = getString(md5key);
    if (md5 == null) {
        throw new MongoException("no md5 stored");
    }
    Doreplacedent cmd = new Doreplacedent("filemd5", get(MongoFileConstants._id));
    cmd.put("root", getBucketName());
    Doreplacedent res = store.getFilesCollection().getDatabase().executeCommand(cmd).getResponse();
    if (res != null && res.containsKey(md5key.toString())) {
        String m = res.get(md5key.toString()).toString();
        if (m.equals(md5)) {
            return;
        }
        throw new MongoException("md5 differ.  mine [" + md5 + "] theirs [" + m + "]");
    }
    // no md5 from the server
    throw new MongoException("no md5 returned from server: " + res);
}

19 View Complete Implementation : QueryTest.java
Copyright Apache License 2.0
Author : trishagee
@Test
public void shouldFindAllDoreplacedentsWithTheNameCharles() {
    // Given
    Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74));
    collection.insert(charlie.toDoreplacedent());
    Person bob = new Person("bob", "Bob The Amazing", new Address("123 Fake St", "LondonTown", 1234567890), asList(27464, 747854));
    collection.insert(bob.toDoreplacedent());
    // When
    // TODO create the correct query to find Charlie by name
    Doreplacedent query = null;
    // TODO use this query to get a List of matching Doreplacedents from the database
    List<Doreplacedent> results = null;
    // Then
    replacedertThat(results.size(), is(1));
    replacedertThat((String) results.get(0).get("_id"), is(charlie.getId()));
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
private void checkForExpireAtIndex(final MongoCollection<Doreplacedent> coll, final int secondsDelay) {
    // check for existing
    for (Doreplacedent doreplacedent : coll.tools().getIndexes()) {
        if ("ttl".equals(doreplacedent.get("name"))) {
            return;
        }
    }
    // build one
    Index idx = // 
    Index.builder().addKey("expireAt", // 
    OrderBy.ASC).expireAfterSeconds(// 
    secondsDelay).name(// 
    "ttl").sparse().background(// 
    true).build();
    coll.tools().createIndexes(java.util.Collections.singletonList(idx));
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
// 
// manifest
// ////////////////////
public MongoManifest getManifest(final MongoFile file) {
    if (file == null) {
        throw new IllegalArgumentException("file cannot be null");
    }
    if (!file.isExpandedZipFile()) {
        throw new IllegalStateException("");
    }
    // 
    Doreplacedent query = new Doreplacedent(MongoFileConstants.manifestId.name(), file.getId());
    Doreplacedent sort = new Doreplacedent(MongoFileConstants.manifestNum.name(), 1);
    MongoFileCursor mongoFileCursor = find(query, sort);
    if (!mongoFileCursor.hasNext()) {
        throw new IllegalStateException("Cannot generate manifest correctly");
    }
    // generate the manifest
    MongoManifest manifest = new MongoManifest(mongoFileCursor.next());
    while (mongoFileCursor.hasNext()) {
        manifest.addMongoFile(mongoFileCursor.next());
    }
    return manifest;
}

19 View Complete Implementation : FileChunksOutputStreamSink.java
Copyright Apache License 2.0
Author : dbuschman7
@Override
public void write(final byte[] buffer, final int offset, final int length) throws IOException {
    // replacedume the whole preplaceded in buffer for
    byte[] internal = buffer;
    // efficiency
    // if partial buffer, then we have to copy the data until serialized
    if (offset != 0 || length != buffer.length) {
        internal = new byte[length];
        System.arraycopy(buffer, offset, internal, 0, length);
    }
    // construct the chunk
    Doreplacedent dbObject = // 
    new Doreplacedent("files_id", id).append("n", // Sequence number of the chunk
    currentChunkNumber).append("sz", // length of the chunk data portion on the
    length).append("data", // the data encoded
    internal);
    if (expiresAt != null) {
        dbObject.put(MongoFileConstants.expireAt.toString(), expiresAt);
    }
    ++currentChunkNumber;
    // persist it
    collection.save(dbObject);
    adapter.collectFromChunk(dbObject);
}

19 View Complete Implementation : MongoFile.java
Copyright Apache License 2.0
Author : dbuschman7
private StorageFormat fetchFormat(final Doreplacedent surrogate) {
    String format = surrogate.getString(MongoFileConstants.format);
    if (format == null) {
        format = surrogate.getString(MongoFileConstants.compressionFormat);
    }
    if (format == null) {
        return StorageFormat.GRIDFS;
    }
    return StorageFormat.find(format);
}

19 View Complete Implementation : MongoFileStore.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * finds one file matching the given id. Equivalent to findOne(id)
 *
 * @param id
 * @return the MongoFile object
 * @throws MongoException
 */
public MongoFile findOne(final ObjectId id) {
    MongoCursor<Doreplacedent> cursor = this.getFilesCollection().find(new Doreplacedent("_id", id)).get();
    if (!cursor.hasNext()) {
        return null;
    }
    Doreplacedent one = deletedFileCheck(cursor.next());
    if (one == null) {
        return null;
    }
    return new MongoFile(this, one);
}

19 View Complete Implementation : MongoManifestQueryTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test
public void testSearchZipArchiveRegexSorted() throws Exception {
    MongoZipArchiveQuery zipArchiveQuery = store.findInZipArchive(manifest.getZip());
    replacedertNotNull(zipArchiveQuery);
    Pattern namesRegex = Pattern.compile("^file.*");
    Doreplacedent query = new Doreplacedent(MongoFileConstants.filename.name(), namesRegex);
    Doreplacedent sort = new Doreplacedent(MongoFileConstants.filename.name(), -1);
    MongoFileCursor find = zipArchiveQuery.find(query, sort);
    replacedertNotNull(find);
    replacedertTrue(find.hasNext());
    MongoFile mongoFile = find.next();
    replacedertNotNull(mongoFile);
    replacedertEquals("file2.txt", mongoFile.getFilename());
    replacedertTrue(find.hasNext());
    mongoFile = find.next();
    replacedertNotNull(mongoFile);
    replacedertEquals("file1.txt", mongoFile.getFilename());
    // should only be two returned
    replacedertFalse(find.hasNext());
}

18 View Complete Implementation : MongoZipArchiveQuery.java
Copyright Apache License 2.0
Author : dbuschman7
/**
 * finds a list of files matching the given query
 *
 * @param query
 * @param sort
 * @return the MongoFileCursor object
 * @throws MongoException
 */
public MongoFileCursor find(final Doreplacedent query, final Doreplacedent sort) {
    return store.find(query.append(MongoFileConstants.manifestId.name(), zipFileUrl.getMongoFileId()), sort);
}

18 View Complete Implementation : FileChunkOutputStreamSinkTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test
public void testPartialBufferWrite() throws IOException {
    GridFSInputFile file = gridFS.createFile("bar");
    GridFSInputFileAdapter adapter = new GridFSInputFileAdapter(file);
    FileChunksOutputStreamSink sink = new // 
    FileChunksOutputStreamSink(chunksCollection, file.getId(), adapter, null);
    try {
        byte[] array = "This is a test".getBytes();
        sink.write(array, 10, 4);
    } finally {
        sink.close();
    }
    // replacedert
    MongoView<Doreplacedent> view = chunksCollection.find(new Doreplacedent("files_id", file.getId()));
    MongoCursor<Doreplacedent> cursor = view.get();
    replacedertTrue(cursor.hasNext());
    Doreplacedent found = cursor.next();
    replacedertNotNull(found.get("files_id"));
    replacedertEquals(file.getId(), found.get("files_id"));
    replacedertNotNull(found.get("data"));
    byte[] bytes = (byte[]) found.get("data");
    replacedertEquals(4, bytes.length);
    replacedertEquals("test", new String(bytes, "UTF-8"));
}

18 View Complete Implementation : FileChunkOutputStreamSinkTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test
public void testFullBufferWrite() throws IOException {
    GridFSInputFile file = gridFS.createFile("foo");
    ChunksStatisticsAdapter adapter = new GridFSInputFileAdapter(file);
    FileChunksOutputStreamSink sink = new // 
    FileChunksOutputStreamSink(chunksCollection, file.getId(), adapter, null);
    try {
        byte[] array = "This is a test".getBytes();
        sink.write(array, 0, array.length);
    } finally {
        sink.close();
    }
    // replacedert
    MongoView<Doreplacedent> view = chunksCollection.find(new Doreplacedent("files_id", file.getId()));
    MongoCursor<Doreplacedent> cursor = view.get();
    replacedertTrue(cursor.hasNext());
    Doreplacedent found = cursor.next();
    replacedertNotNull(found.get("files_id"));
    replacedertEquals(file.getId(), found.get("files_id"));
    replacedertNotNull(found.get("data"));
    byte[] bytes = (byte[]) found.get("data");
    replacedertEquals(14, bytes.length);
    replacedertEquals("This is a test", new String(bytes, "UTF-8"));
}

18 View Complete Implementation : MongoFileExpirationTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test
public void testASyncDelete() throws IOException {
    MongoFile file = store.upload(LoremIpsum.getFile(), "text/plain");
    replacedertNotNull(file);
    // should return default
    replacedertTrue(file.getBoolean(MongoFileConstants.deleted, true));
    store.remove(file, true);
    MongoView<Doreplacedent> find = store.getFilesCollection().find(new Doreplacedent("_id", file.getId()));
    Doreplacedent doreplacedent = find.getOne();
    replacedertNotNull(doreplacedent);
    replacedertTrue(doreplacedent.containsKey(MongoFileConstants.deleted.name()));
    replacedertTrue(doreplacedent.getBoolean(MongoFileConstants.deleted.name()));
    replacedertNotNull(doreplacedent.getDate(MongoFileConstants.expireAt.name()));
}

18 View Complete Implementation : MongoFileExpirationTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test
public void testExpireFile() throws IOException {
    MongoFile file = store.upload(LoremIpsum.getFile(), "text/plain");
    replacedertNotNull(file);
    store.expireFile(file, TimeMachine.now().forward(1).minutes().inTime());
    MongoView<Doreplacedent> find = store.getFilesCollection().find(new Doreplacedent("_id", file.getId()));
    Doreplacedent doreplacedent = find.getOne();
    replacedertNotNull(doreplacedent);
    replacedertTrue(doreplacedent.containsKey(MongoFileConstants.deleted.name()));
    replacedertFalse(doreplacedent.getBoolean(MongoFileConstants.deleted.name()));
    replacedertNotNull(doreplacedent.getDate(MongoFileConstants.expireAt.name()));
}

18 View Complete Implementation : MongoFileTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test(expected = MongoException.clreplaced)
public void noMd5OnServer() {
    // setup
    MongoFileStore store = Mockito.mock(MongoFileStore.clreplaced);
    @SuppressWarnings("unchecked")
    MongoCollection<Doreplacedent> coll = (MongoCollection<Doreplacedent>) Mockito.mock(MongoCollection.clreplaced);
    Mockito.when(store.getFilesCollection()).thenReturn(coll);
    MongoDatabase database = Mockito.mock(MongoDatabase.clreplaced);
    Mockito.when(coll.getDatabase()).thenReturn(database);
    Mockito.when(coll.getName()).thenReturn("bucket");
    CommandResult result = Mockito.mock(CommandResult.clreplaced);
    Mockito.when(database.executeCommand(any(Doreplacedent.clreplaced))).thenReturn(result);
    Mockito.when(result.getResponse()).thenReturn(null);
    // execute
    Doreplacedent surrogate = new Doreplacedent(MongoFileConstants.md5.name(), "54321");
    MongoFile mongoFile = new MongoFile(store, surrogate);
    mongoFile.validate();
}

18 View Complete Implementation : MongoFileTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test(expected = MongoException.clreplaced)
public void md5Differ() {
    // setup
    MongoFileStore store = Mockito.mock(MongoFileStore.clreplaced);
    @SuppressWarnings("unchecked")
    MongoCollection<Doreplacedent> coll = (MongoCollection<Doreplacedent>) Mockito.mock(MongoCollection.clreplaced);
    Mockito.when(store.getFilesCollection()).thenReturn(coll);
    MongoDatabase database = Mockito.mock(MongoDatabase.clreplaced);
    Mockito.when(coll.getDatabase()).thenReturn(database);
    Mockito.when(coll.getName()).thenReturn("bucket");
    CommandResult result = Mockito.mock(CommandResult.clreplaced);
    Mockito.when(database.executeCommand(any(Doreplacedent.clreplaced))).thenReturn(result);
    Doreplacedent server = new Doreplacedent(MongoFileConstants.md5.name(), "12345");
    Mockito.when(result.getResponse()).thenReturn(server);
    // execute
    Doreplacedent surrogate = new Doreplacedent(MongoFileConstants.md5.name(), "54321");
    MongoFile mongoFile = new MongoFile(store, surrogate);
    mongoFile.validate();
}

18 View Complete Implementation : MongoFileTest.java
Copyright Apache License 2.0
Author : dbuschman7
@Test
public void testGetBoolean() {
    Doreplacedent surrogate = // 
    new Doreplacedent().append(MongoFileConstants.chunkCount.name(), // 
    Integer.valueOf(1)).append(MongoFileConstants.ratio.name(), // 
    BigInteger.ZERO).append(MongoFileConstants.deleted.name(), Boolean.FALSE);
    MongoFile mongoFile = new MongoFile(null, surrogate);
    replacedertTrue(mongoFile.getBoolean(MongoFileConstants.chunkCount, false));
    replacedertFalse(mongoFile.getBoolean(MongoFileConstants.ratio, true));
    replacedertFalse(mongoFile.getBoolean(MongoFileConstants.deleted, true));
    replacedertFalse(mongoFile.getBoolean(MongoFileConstants.expireAt, false));
}

18 View Complete Implementation : FindAndModifyTest.java
Copyright Apache License 2.0
Author : trishagee
@Test
public void shouldRemoveDoreplacedentAndReturnTheOriginalDoreplacedent() {
    // Given
    Person charlie = new Person("charlie", "Charles", new Address("74 That Place", "LondonTown", 1234567890), asList(1, 74));
    collection.insert(charlie.toDoreplacedent());
    // When
    // TODO create query to find Charlie by ID
    Doreplacedent findCharlie = null;
    // TODO call one of the find and modify methods to remove Charlie and return the doreplacedent that was removed
    Doreplacedent resultOfFindAndModify = null;
    // Then
    // the returned object should be the doreplacedent before it was deleted (frankly the other way around would be dumb)
    replacedertThat((String) resultOfFindAndModify.get("_id"), is(charlie.getId()));
    replacedertThat((String) resultOfFindAndModify.get("name"), is(charlie.getName()));
    replacedertThat((List<Integer>) resultOfFindAndModify.get("books"), is(charlie.getBookIds()));
    Doreplacedent address = (Doreplacedent) resultOfFindAndModify.get("address");
    replacedertThat((String) address.get("street"), is(charlie.getAddress().getStreet()));
    replacedertThat((String) address.get("city"), is(charlie.getAddress().getTown()));
    replacedertThat((int) address.get("phone"), is(charlie.getAddress().getPhone()));
    // but obviously it should have been deleted in the database
    replacedertThat(collection.find(findCharlie).count(), is(0L));
}