Search in sources :

Example 56 with MongoClient

use of com.mongodb.MongoClient in project vcell by virtualcell.

the class VCMongoDbDriver method storeBLOB.

public ObjectId storeBLOB(String blobName, String blobType, byte[] blob) {
    try {
        // send to MongoDB
        if (m == null) {
            String mongoDbHost = PropertyLoader.getRequiredProperty(PropertyLoader.mongodbHostInternal);
            // default 27017
            int mongoDbPort = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.mongodbPortInternal));
            m = new MongoClient(mongoDbHost, mongoDbPort);
        }
        MongoDatabase db = m.getDatabase(mongoDbDatabaseName);
        GridFSBucket gridFSBucket = GridFSBuckets.create(db);
        Document metadata = new Document();
        metadata.put("type", blobType);
        long msgTime = System.currentTimeMillis();
        metadata.put("inserttime", msgTime);
        metadata.put("inserttime_nice", new Date(msgTime).toString());
        GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024).metadata(metadata);
        ByteArrayInputStream in = new ByteArrayInputStream(blob);
        ObjectId fileId = gridFSBucket.uploadFromStream(blobName, in, options);
        return fileId;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        try {
            if (m != null) {
                m.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace(System.out);
        } finally {
            m = null;
        }
        throw new RuntimeException("failed to store BLOB named " + blobName + ": " + e.getMessage(), e);
    }
}
Also used : ObjectId(org.bson.types.ObjectId) Document(org.bson.Document) Date(java.util.Date) MongoException(com.mongodb.MongoException) GridFSBucket(com.mongodb.client.gridfs.GridFSBucket) MongoClient(com.mongodb.MongoClient) ByteArrayInputStream(java.io.ByteArrayInputStream) MongoDatabase(com.mongodb.client.MongoDatabase) GridFSUploadOptions(com.mongodb.client.gridfs.model.GridFSUploadOptions)

Example 57 with MongoClient

use of com.mongodb.MongoClient in project vcell by virtualcell.

the class VCMongoDbDriver method getBLOB.

public byte[] getBLOB(ObjectId objectId) {
    try {
        if (m == null) {
            String mongoDbHost = PropertyLoader.getRequiredProperty(PropertyLoader.mongodbHostInternal);
            // default 27017
            int mongoDbPort = Integer.parseInt(PropertyLoader.getRequiredProperty(PropertyLoader.mongodbPortInternal));
            m = new MongoClient(mongoDbHost, mongoDbPort);
        }
        ByteArrayOutputStream streamToDownloadTo = new ByteArrayOutputStream();
        MongoDatabase db = m.getDatabase(mongoDbDatabaseName);
        GridFSBucket gridFSBucket = GridFSBuckets.create(db);
        gridFSBucket.downloadToStream(objectId, streamToDownloadTo);
        byte[] blob = streamToDownloadTo.toByteArray();
        return blob;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        try {
            if (m != null) {
                m.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace(System.out);
        } finally {
            m = null;
        }
        throw new RuntimeException("failed to retrieve BLOB with ObjectId " + objectId.toHexString() + ": " + e.getMessage(), e);
    }
}
Also used : GridFSBucket(com.mongodb.client.gridfs.GridFSBucket) MongoClient(com.mongodb.MongoClient) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) MongoException(com.mongodb.MongoException) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 58 with MongoClient

use of com.mongodb.MongoClient in project cas by apereo.

the class MongoAuthenticationHandler method getAuthenticator.

@Override
protected Authenticator<UsernamePasswordCredentials> getAuthenticator(final Credential credential) {
    final MongoClientURI uri = new MongoClientURI(this.mongoHostUri);
    final MongoClient client = new MongoClient(uri);
    LOGGER.info("Connected to MongoDb instance @ [{}] using database [{}]", uri.getHosts(), uri.getDatabase());
    final MongoAuthenticator mongoAuthenticator = new MongoAuthenticator(client, this.attributes);
    mongoAuthenticator.setUsersCollection(this.collectionName);
    mongoAuthenticator.setUsersDatabase(uri.getDatabase());
    mongoAuthenticator.setUsernameAttribute(this.usernameAttribute);
    mongoAuthenticator.setPasswordAttribute(this.passwordAttribute);
    mongoAuthenticator.setPasswordEncoder(this.mongoPasswordEncoder);
    return mongoAuthenticator;
}
Also used : MongoClient(com.mongodb.MongoClient) MongoClientURI(com.mongodb.MongoClientURI) MongoAuthenticator(org.pac4j.mongo.credentials.authenticator.MongoAuthenticator)

Example 59 with MongoClient

use of com.mongodb.MongoClient in project presto by prestodb.

the class MongoClientModule method createMongoSession.

@Singleton
@Provides
public static MongoSession createMongoSession(TypeManager typeManager, MongoClientConfig config) {
    requireNonNull(config, "config is null");
    MongoClientOptions.Builder options = MongoClientOptions.builder();
    options.connectionsPerHost(config.getConnectionsPerHost()).connectTimeout(config.getConnectionTimeout()).socketTimeout(config.getSocketTimeout()).socketKeepAlive(config.getSocketKeepAlive()).sslEnabled(config.getSslEnabled()).maxWaitTime(config.getMaxWaitTime()).minConnectionsPerHost(config.getMinConnectionsPerHost()).readPreference(config.getReadPreference().getReadPreference()).writeConcern(config.getWriteConcern().getWriteConcern());
    if (config.getRequiredReplicaSetName() != null) {
        options.requiredReplicaSetName(config.getRequiredReplicaSetName());
    }
    MongoClient client = new MongoClient(config.getSeeds(), config.getCredentials(), options.build());
    return new MongoSession(typeManager, client, config);
}
Also used : MongoClient(com.mongodb.MongoClient) MongoClientOptions(com.mongodb.MongoClientOptions) Singleton(javax.inject.Singleton) Provides(com.google.inject.Provides)

Example 60 with MongoClient

use of com.mongodb.MongoClient in project graylog2-server by Graylog2.

the class MongoConnectionImpl method connect.

/**
     * Connect the instance.
     */
@Override
public synchronized Mongo connect() {
    if (m == null) {
        final String dbName = mongoClientURI.getDatabase();
        if (isNullOrEmpty(dbName)) {
            LOG.error("The MongoDB database name must not be null or empty (mongodb_uri was: {})", mongoClientURI);
            throw new RuntimeException("MongoDB database name is missing.");
        }
        m = new MongoClient(mongoClientURI);
        db = m.getDB(dbName);
        db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        mongoDatabase = m.getDatabase(dbName).withWriteConcern(WriteConcern.ACKNOWLEDGED);
    }
    try {
        db.command("{ ping: 1 }");
    } catch (MongoCommandException e) {
        if (e.getCode() == 18) {
            throw new MongoException("Couldn't connect to MongoDB. Please check the authentication credentials.", e);
        } else {
            throw new MongoException("Couldn't connect to MongoDB: " + e.getMessage(), e);
        }
    }
    final Version mongoVersion = getMongoVersion(m.getDB("admin"));
    if (mongoVersion != null && mongoVersion.lessThan(MINIMUM_MONGODB_VERSION)) {
        LOG.warn("You're running MongoDB {} but Graylog requires at least MongoDB {}. Please upgrade.", mongoVersion, MINIMUM_MONGODB_VERSION);
    }
    return m;
}
Also used : MongoClient(com.mongodb.MongoClient) MongoException(com.mongodb.MongoException) MongoCommandException(com.mongodb.MongoCommandException) Version(com.github.zafarkhaja.semver.Version)

Aggregations

MongoClient (com.mongodb.MongoClient)126 Test (org.junit.Test)31 MongoClientURI (com.mongodb.MongoClientURI)29 Document (org.bson.Document)26 ServerAddress (com.mongodb.ServerAddress)21 MongoDatabase (com.mongodb.client.MongoDatabase)21 Before (org.junit.Before)20 BasicDBObject (com.mongodb.BasicDBObject)11 ArrayList (java.util.ArrayList)11 MongoCredential (com.mongodb.MongoCredential)9 MongoException (com.mongodb.MongoException)8 DB (com.mongodb.DB)7 DBCollection (com.mongodb.DBCollection)7 UnknownHostException (java.net.UnknownHostException)7 MongoTemplate (org.springframework.data.mongodb.core.MongoTemplate)7 DBObject (com.mongodb.DBObject)6 MongoClientOptions (com.mongodb.MongoClientOptions)6 IOException (java.io.IOException)5 List (java.util.List)5 MongoDbFactory (org.springframework.data.mongodb.MongoDbFactory)5