Example usage for com.mongodb MongoCredential createMongoCRCredential

List of usage examples for com.mongodb MongoCredential createMongoCRCredential

Introduction

In this page you can find the example usage for com.mongodb MongoCredential createMongoCRCredential.

Prototype

@SuppressWarnings("deprecation")
@Deprecated
public static MongoCredential createMongoCRCredential(final String userName, final String database,
        final char[] password) 

Source Link

Document

Creates a MongoCredential instance for the MongoDB Challenge Response protocol.

Usage

From source file:net.gtaun.wl.vehicle.VehicleManagerPlugin.java

License:Open Source License

@Override
protected void onEnable() throws Throwable {
    config = new VehicleManagerConfig(new File(getDataDir(), "config.yml"));

    if (config.getDbUser().isEmpty() || config.getDbPass().isEmpty()) {
        mongoClient = new MongoClient(config.getDbHost());
    } else {//from ww  w  .  j a  v a2s  . com
        mongoClient = new MongoClient(Arrays.asList(new ServerAddress(config.getDbHost())),
                Arrays.asList(MongoCredential.createMongoCRCredential(config.getDbName(), config.getDbName(),
                        config.getDbPass().toCharArray())));
    }

    morphia = new Morphia();
    morphia.getMapper().getOptions().objectFactory = new DefaultCreator() {
        @Override
        protected ClassLoader getClassLoaderForClass(String clazz, DBObject object) {
            return getClass().getClassLoader();
        }
    };
    morphia.map(GlobalVehicleStatisticImpl.class);
    morphia.map(PlayerVehicleStatisticImpl.class);

    datastore = morphia.createDatastore(mongoClient, config.getDbName());

    vehicleManagerSerivce = new VehicleManagerServiceImpl(getEventManager(), this, datastore);
    registerService(VehicleManagerService.class, vehicleManagerSerivce);

    LOGGER.info(getDescription().getName() + " " + getDescription().getVersion() + " Enabled.");
}

From source file:nl.mawoo.wcmscript.modules.mongodb.MongoDB.java

License:Apache License

/**
 * Connect to MongoDB with authentication
 * This methods opens the connection to the MongoDB server and sets the database that is set.
 * @param username the username of the MongoDB server
 * @param password the password of the MongoDB server
 * @return this//w  ww .  j a  v a2 s.c  o  m
 */
public MongoDB connectAuthenticated(String username, String password) {
    MongoCredential mongoCredential = MongoCredential.createMongoCRCredential(username, this.currentDatabase,
            password.toCharArray());
    client = new MongoClient(new ServerAddress(host, port), Arrays.asList(mongoCredential));
    database = client.getDatabase(currentDatabase);
    return this;
}

From source file:org.apache.calcite.adapter.mongodb.MongoSchemaFactory.java

License:Apache License

private MongoCredential createCredentials(Map<String, Object> map) {
    final String authMechanismName = (String) map.get("authMechanism");
    final AuthenticationMechanism authenticationMechanism = AuthenticationMechanism
            .fromMechanismName(authMechanismName);
    final String username = (String) map.get("username");
    final String authDatabase = (String) map.get("authDatabase");
    final String password = (String) map.get("password");

    switch (authenticationMechanism) {
    case PLAIN:/*from  www.  j a  v  a2s. c  o m*/
        return MongoCredential.createPlainCredential(username, authDatabase, password.toCharArray());
    case SCRAM_SHA_1:
        return MongoCredential.createScramSha1Credential(username, authDatabase, password.toCharArray());
    case GSSAPI:
        return MongoCredential.createGSSAPICredential(username);
    case MONGODB_CR:
        return MongoCredential.createMongoCRCredential(username, authDatabase, password.toCharArray());
    case MONGODB_X509:
        return MongoCredential.createMongoX509Credential(username);
    }
    throw new IllegalArgumentException("Unsupported authentication mechanism " + authMechanismName);
}

From source file:org.araqne.logdb.mongo.MongoProfile.java

License:Apache License

public List<MongoCredential> getCredentials() {
    if (authProfiles == null || authProfiles.isEmpty())
        return null;

    ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();

    for (MongoAuthProfile p : authProfiles) {
        MongoCredential c = MongoCredential.createMongoCRCredential(p.getUser(), p.getDb(),
                p.getPassword().toCharArray());
        credentials.add(c);//from   w ww .  j ava 2  s  .c  o m
    }

    return credentials;
}

From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java

License:Apache License

private MongoClient createMongoClient(ServerConfiguration configuration) throws UnknownHostException {
    List<String> serverUrls = configuration.getServerUrls();
    String username = configuration.getUsername();
    String password = configuration.getPassword();
    String userDatabase = configuration.getUserDatabase();
    if (serverUrls.isEmpty()) {
        throw new ConfigurationException("server host is not set");
    }//from  ww w  .  j a  v a 2 s . com

    List<ServerAddress> serverAddresses = new LinkedList<ServerAddress>();
    for (String serverUrl : serverUrls) {
        String[] host_port = serverUrl.split(":");
        serverAddresses.add(new ServerAddress(host_port[0], Integer.valueOf(host_port[1])));
    }

    MongoClientOptions.Builder optionBuilder = MongoClientOptions.builder();
    if (configuration.isSslConnection()) {
        optionBuilder.socketFactory(SSLSocketFactory.getDefault());
    }

    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        MongoCredential credential = MongoCredential.createMongoCRCredential(username, userDatabase,
                password.toCharArray());
        return new MongoClient(serverAddresses, Arrays.asList(credential), optionBuilder.build());
    }
    return new MongoClient(serverAddresses, optionBuilder.build());
}

From source file:org.kaaproject.kaa.server.appenders.mongo.appender.LogEventMongoDao.java

License:Apache License

/**
 * Create new instance of <code>LogEventMongoDao</code> using configuration instance of
 * <code>MongoDbConfig</code>.
 *
 * @param configuration the configuration of log event mongo dao, it contain server size,
 *                      credentials, max wait time, etc.
 *//*from   w w  w  .j a va2s .  c om*/
@SuppressWarnings("deprecation")
public LogEventMongoDao(MongoDbConfig configuration) throws Exception {

    List<ServerAddress> seeds = new ArrayList<>(configuration.getMongoServers().size());
    for (MongoDbServer server : configuration.getMongoServers()) {
        seeds.add(new ServerAddress(server.getHost(), server.getPort()));
    }

    List<MongoCredential> credentials = new ArrayList<>();
    if (configuration.getMongoCredentials() != null) {
        for (MongoDBCredential credential : configuration.getMongoCredentials()) {
            credentials.add(MongoCredential.createMongoCRCredential(credential.getUser(),
                    configuration.getDbName(), credential.getPassword().toCharArray()));
        }
    }

    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    if (configuration.getConnectionsPerHost() != null) {
        optionsBuilder.connectionsPerHost(configuration.getConnectionsPerHost());
    }
    if (configuration.getMaxWaitTime() != null) {
        optionsBuilder.maxWaitTime(configuration.getMaxWaitTime());
    }
    if (configuration.getConnectionTimeout() != null) {
        optionsBuilder.connectTimeout(configuration.getConnectionTimeout());
    }
    if (configuration.getSocketTimeout() != null) {
        optionsBuilder.socketTimeout(configuration.getSocketTimeout());
    }
    if (configuration.getSocketKeepalive() != null) {
        optionsBuilder.socketKeepAlive(configuration.getSocketKeepalive());
    }

    MongoClientOptions options = optionsBuilder.build();
    mongoClient = new MongoClient(seeds, credentials, options);

    MongoDbFactory dbFactory = new SimpleMongoDbFactory(mongoClient, configuration.getDbName());

    MappingMongoConverter converter = new MappingMongoConverter(dbFactory, new MongoMappingContext());
    converter.setTypeMapper(new DefaultMongoTypeMapper(null));

    mongoTemplate = new MongoTemplate(dbFactory, converter);
    mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION);
}

From source file:org.metaservice.core.utils.MongoCache.java

License:Apache License

public MongoCache(@NotNull String address, @NotNull String database, @NotNull String username,
        @NotNull String password) {
    try {/*from   w  w  w .  ja v  a2 s  .  c  o  m*/
        MongoCredential credential = MongoCredential.createMongoCRCredential(username, database,
                password.toCharArray());
        client = new MongoClient(new ServerAddress(address), Arrays.asList(credential));
        db = client.getDB(database);
        db.authenticate(username, password.toCharArray());
        collection = db.getCollection("debiansnapshot");
        fileCollection = db.getCollection("files");
        collection.ensureIndex("uri");
        fileCollection.ensureIndex("md5");
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.metaservice.kryo.mongo.MongoConnectionWrapper.java

License:Apache License

public MongoConnectionWrapper(String address, String database, String username, String password) {
    try {/*from  ww  w . j a  v a2s  . c  o  m*/
        MongoCredential credential = MongoCredential.createMongoCRCredential(username, database,
                password.toCharArray());
        client = new MongoClient(new ServerAddress(address), Arrays.asList(credential));
        DB db = client.getDB(database);

        db.authenticate(username, password.toCharArray());
        ObjectMapper objectMapper = MongoJackModule.configure(new ObjectMapper());
        objectMapper.addMixInAnnotations(URI.class, UriMixin.class);

        queueCollection = JacksonDBCollection.wrap(db.getCollection("queues"), QueueConfig.class, Long.class,
                objectMapper);
        postProcessorMessageCollection = JacksonDBCollection.wrap(db.getCollection("postProcessor"),
                PostProcessorMessage.class, Long.class, objectMapper);
        providerCreateMessageCollection = JacksonDBCollection.wrap(db.getCollection("create"),
                ProviderCreateMessage.class, Long.class, objectMapper);
        providerRefreshMessageCollection = JacksonDBCollection.wrap(db.getCollection("refresh"),
                ProviderRefreshMessage.class, Long.class, objectMapper);
        postProcessorMessageCollectionFailed = JacksonDBCollection.wrap(db.getCollection("postProcessorFailed"),
                ResponseMessage.class, Long.class, objectMapper);
        providerCreateMessageCollectionFailed = JacksonDBCollection.wrap(db.getCollection("createFailed"),
                ResponseMessage.class, Long.class, objectMapper);
        providerRefreshMessageCollectionFailed = JacksonDBCollection.wrap(db.getCollection("refreshFailed"),
                ResponseMessage.class, Long.class, objectMapper);
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.metaservice.Md5Runner.java

License:Apache License

public static void main(String[] args) {
    try {// w w  w  .  jav a 2 s. c  om
        MongoCredential credential = MongoCredential.createMongoCRCredential("nilo", "crawlcache",
                "alokin".toCharArray());
        client = new MongoClient(new ServerAddress("metaservice.org"), Arrays.asList(credential));
        db = client.getDB("crawlcache");
        db.authenticate("nilo", "alokin".toCharArray());
        collection = db.getCollection("debiansnapshot");
        fileCollection = db.getCollection("files");
        collection.ensureIndex("uri");
        fileCollection.ensureIndex("md5");

        DBObject query = new BasicDBObject();
        query.put("md5", new BasicDBObject("$exists", true));
        query.put("content", new BasicDBObject("$type", 5));
        BasicDBObject group = new BasicDBObject();
        group.put("_id", "$md5");
        group.put("total", new BasicDBObject("$sum", 1));

        System.err.println(
                fileCollection.aggregate(new BasicDBObject("$match", query), new BasicDBObject("$group", group),
                        new BasicDBObject("$sort", new BasicDBObject("total", -1))));

        /*
        while(true){
                
        DBObject query = new BasicDBObject();
        query.put("md5",new BasicDBObject("$exists",false));
        query.put("content",new BasicDBObject("$type",5));
                
        DBObject object = collection.findOne(query);
        if(object == null)
        break;
                
                
        System.err.println(object.get("uri"));
                
        byte[] x = (byte[]) object.get("content");
                
        object.put("md5",DigestUtils.md5Hex(x));
        collection.save(object,WriteConcern.SAFE);
        }
                
                
        while (true){
        DBObject query = new BasicDBObject();
        query.put("md5",new BasicDBObject("$exists",true));
        query.put("content",new BasicDBObject("$type",5));
        DBObject object = collection.findOne(query);
                
                
        String md5  = (String) object.get("md5");
        object.removeField("md5");
        collection.save(object,WriteConcern.SAFE);
        ObjectId id = (ObjectId) object.get("_id");
                
        object.put("md5",md5);
        object.removeField("_id");
        fileCollection.insert(object,WriteConcern.SAFE);
        System.err.println("INSERTED " + object.get("_id"));
        query = new BasicDBObject();
        query.put("md5",md5);
                
        // update self
        DBObject x  =collection.findOne(id);
        x.put("contentRef",object.get("_id"));
        x.removeField("content");
        collection.save(x,WriteConcern.SAFE);
                
        // updatePackage others
        DBObject updatePackage = new BasicDBObject();
        updatePackage.put("$set",new BasicDBObject("contentRef",object.get("_id")));
        updatePackage.put("$unset",new BasicDBObject("content",1));
        WriteResult result = collection.updatePackage(query,updatePackage);
        System.err.println("MD5 " + md5 + " existed  " + result.getN() + " times");
                
        }
        */
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.opencb.cellbase.mongodb.serializer.CellBaseMongoDBSerializer.java

License:Apache License

public void init() throws UnknownHostException {
    ServerAddress serverAddres = new ServerAddress(host, port);
    if (this.user != null) {
        mongoClient = new MongoClient(serverAddres,
                Arrays.asList(MongoCredential.createMongoCRCredential(user, database, password)));
    } else {//from   w w w.  ja v a 2s.  c om
        mongoClient = new MongoClient(serverAddres);
    }
    db = mongoClient.getDB(database);
    // TODO: mongo clients options, like write concern
    jsonObjectMapper = new ObjectMapper();
    jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}