Example usage for com.mongodb MongoClient close

List of usage examples for com.mongodb MongoClient close

Introduction

In this page you can find the example usage for com.mongodb MongoClient close.

Prototype

public void close() 

Source Link

Document

Closes all resources associated with this instance, in particular any open network connections.

Usage

From source file:org.springframework.data.mongodb.microbenchmark.MongoResultsWriter.java

License:Apache License

@Override
public void write(Collection<RunResult> results) {

    Date now = new Date();
    StandardEnvironment env = new StandardEnvironment();

    String projectVersion = env.getProperty("project.version", "unknown");
    String gitBranch = env.getProperty("git.branch", "unknown");
    String gitDirty = env.getProperty("git.dirty", "no");
    String gitCommitId = env.getProperty("git.commit.id", "unknown");

    MongoClientURI uri = new MongoClientURI(this.uri);
    MongoClient client = new MongoClient(uri);

    String dbName = StringUtils.hasText(uri.getDatabase()) ? uri.getDatabase()
            : "spring-data-mongodb-benchmarks";
    MongoDatabase db = client.getDatabase(dbName);

    for (BasicDBObject dbo : (List<BasicDBObject>) JSON.parse(ResultsWriter.jsonifyResults(results))) {

        String collectionName = extractClass(dbo.get("benchmark").toString());

        Document sink = new Document();
        sink.append("_version", projectVersion);
        sink.append("_branch", gitBranch);
        sink.append("_commit", gitCommitId);
        sink.append("_dirty", gitDirty);
        sink.append("_method", extractBenchmarkName(dbo.get("benchmark").toString()));
        sink.append("_date", now);
        sink.append("_snapshot", projectVersion.toLowerCase().contains("snapshot"));

        sink.putAll(dbo);/* ww  w .  ja  v a  2  s .  c  o  m*/

        db.getCollection(collectionName).insertOne(fixDocumentKeys(sink));
    }

    client.close();
}

From source file:org.springframework.statemachine.buildtests.tck.mongodb.MongoDbRule.java

License:Apache License

@Override
public Statement apply(Statement base, Description description) {
    MongoClient client = null;
    try {//from  w  ww  .j av  a 2 s  . com
        client = new MongoClient(new ServerAddress(), MongoClientOptions.builder().connectTimeout(50).build());
        client.getAddress();
    } catch (Exception e) {
        return super.apply(new Statement() {
            @Override
            public void evaluate() throws Throwable {
            }
        }, Description.EMPTY);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return super.apply(base, description);
}

From source file:org.tinygroup.mongodb.MogoDbTest1.java

License:GNU General Public License

/**
 * @param args/*from www . ja v a2s .c o m*/
 * @throws Throwable
 */
public static void main(String[] args) throws Throwable {
    MongoClient connection = new MongoClient();
    DB db = connection.getDB("test");
    DBCollection collection = db.getCollection("p");
    DBObject query = new BasicDBObject();
    query.put("_id", new ObjectId("528c53aa5f4089467c5dd15a"));
    for (DBObject object : collection.find(query).toArray()) {
        System.out.println(object.toString());
        DBRef dbref = new DBRef(db, "p", object.get("p_id"));
        DBObject refObj = dbref.fetch();
        System.out.println(refObj.toString());
    }
    connection.close();

}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public byte[] loadBinaryData(String collectionName, String identifier) throws Exception {
    byte[] data = new byte[0];

    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    Document doc = db.getCollection(collectionName).find(Filters.eq(IDENTIFIER_FIELD, identifier)).limit(1)
            .first();/*  w ww .  java  2  s.c o m*/

    if (doc != null) {
        if (doc.containsKey(DATA_FIELD)) {
            data = ((Binary) doc.get(DATA_FIELD)).getData();
        } else {
            logger.info("Model object '{}' from model collection '{}' does not have any associated data at the "
                    + "moment.", identifier, collectionName);
        }
    } else {
        logger.info("The database does not know the specified model object '{}' from model collection '{}'",
                identifier, collectionName);
    }

    client.close();

    return data;
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public void storeBinaryData(byte[] data, String collectionName, String identifier) throws Exception {
    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    MongoCollection<Document> collection = db.getCollection(collectionName);
    Document doc = collection.find(Filters.eq(IDENTIFIER_FIELD, identifier)).limit(1).first();

    if (data == null) {
        // We assume that if the value is set to null, we should delete also the corresponding database entry
        if (doc != null) {
            collection.deleteOne(Filters.eq(IDENTIFIER_FIELD, identifier));
        }//from w w w  .j  a  v a2s.c om
    } else {
        // Check if the document already exists and update it
        if (doc != null) {
            collection.updateOne(Filters.eq(IDENTIFIER_FIELD, identifier),
                    Updates.combine(Updates.set(DATA_FIELD, data), Updates.currentDate("lastModified")));
        } else {
            Document document = new Document(IDENTIFIER_FIELD, identifier).append(DATA_FIELD, data)
                    .append("lastModified", new Date());
            collection.insertOne(document);
        }
    }

    client.close();
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public void deleteBinaryData(String collectionName, String identifier) throws Exception {
    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    Document doc = db.getCollection(collectionName).findOneAndDelete(Filters.eq(IDENTIFIER_FIELD, identifier));

    if (doc != null) {
        logger.info("Model object '{}' from model collection '{}' and its associated data successfully deleted "
                + "from DB.", identifier, collectionName);
    } else {/*from   w w  w.j  a  v  a  2 s . co m*/
        logger.info("The database does not know the specified model object '{}' from model collection '{}'",
                identifier, collectionName);
    }

    client.close();
}

From source file:org.trade.server.IntegrationTestEnvironment.java

License:Apache License

public void destroyEnvironment() {
    // Cleanup the database
    MongoClient dataStoreClient = new MongoClient(new MongoClientURI(properties.getDataPersistenceDbUrl()));
    MongoDatabase dataStore = dataStoreClient.getDatabase(properties.getDataPersistenceDbName());
    dataStore.getCollection(ModelConstants.DATA_MODEL__DATA_COLLECTION).drop();
    dataStore.getCollection(ModelConstants.DATA_DEPENDENCY_GRAPH__DATA_COLLECTION).drop();
    dataStore.getCollection(ModelConstants.DATA_VALUE__DATA_COLLECTION).drop();

    dataStore.getCollection("dataElements").drop();
    dataStore.getCollection("dataObjects").drop();
    dataStore.getCollection("dataModels").drop();
    dataStore.getCollection("dataDependencyGraphs").drop();
    dataStore.getCollection("notifications").drop();
    dataStore.getCollection("dataValues").drop();
    dataStore.getCollection("dataElementInstances").drop();
    dataStore.getCollection("dataObjectInstances").drop();

    dataStoreClient.close();

    // Stop the server
    try {/*  w ww  . j av  a2  s.  c o  m*/
        server.stopHTTPServer();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.datasource.reader.mongo.MongoDataSourceReader.java

License:Open Source License

@Override
public boolean testDataSourceConnection(String xmlConfig) throws DataSourceException {
    MongoClient mongoClient = (MongoClient) this.createDataSource(xmlConfig, true);
    boolean status = false;
    if (mongoClient.getAddress() != null) {
        status = true;// w w  w  . jav a2 s .  c o  m
    }
    mongoClient.close();
    return status;
}

From source file:parlare.application.server.model.Database.java

private String doClientMongo() {

    String print = "";

    System.out.println("User:" + user + " Source:" + source + " Password:" + password);

    try {/*from w ww  . j a v a  2s.  c  om*/

        // connect to the local database server
        MongoClient mongoClient = new MongoClient(new ServerAddress(server),
                Arrays.asList(MongoCredential.createMongoCRCredential(user, source, password.toCharArray())),
                new MongoClientOptions.Builder().build());

        // get handle to "mydb"
        DB db = mongoClient.getDB("html5apps");

        // Authenticate - optional
        // boolean auth = db.authenticate("foo", "bar");

        // get a list of the collections in this database and print them out
        Set<String> collectionNames = db.getCollectionNames();
        for (String s : collectionNames) {

            System.out.println(s);
        }

        // get a collection object to work with
        DBCollection testCollection = db.getCollection("testCollection");

        // drop all the data in it
        testCollection.drop();

        // make a document and insert it
        BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
                .append("info", new BasicDBObject("x", 203).append("y", 102));

        testCollection.insert(doc);

        // get it (since it's the only one in there since we dropped the rest earlier on)
        DBObject myDoc = testCollection.findOne();
        System.out.println(myDoc);

        // now, lets add lots of little documents to the collection so we can explore queries and cursors
        for (int i = 0; i < 100; i++) {
            testCollection.insert(new BasicDBObject().append("i", i));
        }
        System.out.println("total # of documents after inserting 100 small ones (should be 101) "
                + testCollection.getCount());

        //  lets get all the documents in the collection and print them out
        DBCursor cursor = testCollection.find();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //  now use a query to get 1 document out
        BasicDBObject query = new BasicDBObject("i", 71);
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //  now use a range query to get a larger subset
        query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println("Cursor: " + cursor.next());
            }
        } finally {
            cursor.close();
        }

        // range query with multiple constraints
        query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        // create an index on the "i" field
        testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

        //  list the indexes on the collection
        List<DBObject> list = testCollection.getIndexInfo();
        for (DBObject o : list) {
            System.out.println(o);
        }

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        // see if any previous operation had an error
        System.out.println("Previous error : " + db.getPreviousError());

        // force an error
        db.forceError();

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        db.resetError();

        // release resources
        mongoClient.close();

    } catch (UnknownHostException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    }

    return print;

}

From source file:rmi_video.VideoServer.java

@Override
public boolean addVideo(VideoData d) throws RemoteException {
    try {/*w w w  .  j  a v  a  2 s.c  o m*/
        //Conexao com mongoDB
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("VideoDatabase");

        try (FileOutputStream fos = new FileOutputStream("/Users/philcr/Documents/" + d.getFileName())) {
            fos.write(d.getData());
        }

        File videoFile = new File("/Users/philcr/Documents/" + d.getFileName());

        GridFS gfsVideo = new GridFS(db, "video");

        //Cria e salva o arquivo no DB pelo GridFS
        GridFSInputFile gfsFile = gfsVideo.createFile(videoFile);
        gfsFile.setId(new ObjectId()); //Utiliza a criao de ID do mongo
        gfsFile.put("videoId", d.getId()); //Utiliza nosso metodo de ID
        gfsFile.setFilename(d.getFileName());
        gfsFile.save();

        //Exclui o arquivo local
        boolean deletedFlag = videoFile.delete();
        if (!deletedFlag) {
            System.err.println("File could not be deleted!");
        }

        mongoClient.close();

        return true;

    } catch (UnknownHostException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}