Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final MongoClientURI uri, final MongoDriverInformation mongoDriverInformation) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

From source file:com.github.yongchristophertang.database.guice.provider.MongoFactory.java

License:Apache License

@Override
protected MongoClient createClient(Mongo mongo) {
    String config = mongo.config();
    String host = mongo.host();//  ww w. j  a v a 2s.  c om
    int port = mongo.port();
    String database = mongo.database();

    if (StringUtils.isBlank(config)) {
        if (StringUtils.isBlank(host) || StringUtils.isBlank(database)) {
            throw new IllegalArgumentException("Necessary config is missing for Mongo connection.");
        }
    } else {
        Properties prop = new Properties();
        try {
            prop.load(this.getClass().getClassLoader().getResourceAsStream(config));
            host = prop.getProperty("mongo.host");
            port = Integer.parseInt(prop.getProperty("mongo.port"));
        } catch (IOException e) {
            return null;
        }
    }

    try {
        return new MongoClient(host, port);
    } catch (UnknownHostException e) {
        return null;
    }
}

From source file:com.github.yongchristophertang.database.guice.provider.MongoTemplateFactory.java

License:Apache License

/**
 * Transfer an annotation to a T object.
 *
 * @param anno Mongo annotation/*w w  w.j  av  a2s.co  m*/
 */
@Override
protected MongoTemplate createClient(Mongo anno) {
    if (StringUtils.isBlank(anno.database()) || StringUtils.isBlank(anno.host())) {
        throw new IllegalArgumentException("Mongo annotation must has database argument configured");
    }
    try {
        return new MongoTemplate(new MongoClient(anno.host(), anno.port()), anno.database());
    } catch (UnknownHostException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.globocom.grou.configurations.MongoConfiguration.java

License:Open Source License

@Override
public Mongo mongo() throws Exception {
    if ("".equals(MONGO_URI.getValue())) {
        LOGGER.info("MONGO_HOST: {}, MONGO_PORT: {}, MONGO_DB: {}", MONGO_HOST.getValue(),
                MONGO_PORT.getValue(), MONGO_DB.getValue());
        final List<MongoCredential> credentialsList = "".equals(MONGO_USER.getValue())
                || "".equals(MONGO_PASS.getValue()) ? Collections.emptyList()
                        : singletonList(MongoCredential.createCredential(MONGO_USER.getValue(),
                                MONGO_DB.getValue(), MONGO_PASS.getValue().toCharArray()));
        return new MongoClient(
                singletonList(/*w w w .  j ava 2  s .co m*/
                        new ServerAddress(MONGO_HOST.getValue(), Integer.parseInt(MONGO_PORT.getValue()))),
                credentialsList);
    } else {
        LOGGER.info("MONGO_URI: {}", MONGO_URI.getValue().replaceAll("([/,]).*@", "$1xxxx:xxxx@"));
        return new MongoClient(getMongoClientUri());
    }
}

From source file:com.gmail.kunicins.olegs.gridfs_server.Server.java

License:Creative Commons License

/**
 * Initialize HTTP server/*from www .j  ava2  s  . co  m*/
 * 
 * @param gridFSHost
 * @param gridFSPort
 * @param gridFSDB
 * @param httpPort
 * @param concurrentConnections
 */
public Server(String gridFSHost, int gridFSPort, String gridFSDB, int httpPort, int concurrentConnections) {
    try {
        // GridFS initialization
        MongoClient mongo = new MongoClient(gridFSHost, gridFSPort);
        this.gridFs = new GridFS(mongo.getDB(gridFSDB));
        this.gridFsCollection = mongo.getDB(gridFSDB).getCollection("fs.chunks");

        // HTTP initialization
        this.selector = SelectorProvider.provider().openSelector();
        this.server = ServerSocketChannel.open();
        this.server.configureBlocking(false);
        this.server.socket().bind(new InetSocketAddress(httpPort), concurrentConnections);
        this.server.register(this.selector, server.validOps());

        System.out.println("Listening on *:" + httpPort + ", uses GridFS '" + gridFSDB + "' on " + gridFSHost
                + ":" + gridFSPort);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java

License:Apache License

/**
 * Main demo. This first initializes an Analytics service object. It then queries for the top 25
 * organic search keywords and traffic sources by visits. Finally each important part of the
 * response is printed to the screen.//from  w  ww  . j a v a 2 s  .c  o m
 *
 * @param args command line args.
 */
public static void main(String[] args) {

    try {
        if (args.length == 2) {
            // Start and end date are supplied
            startDate = new SimpleDateFormat("yyyy-MM-dd").parse(args[0]);
            endDate = new SimpleDateFormat("yyyy-MM-dd").parse(args[1]);
        }
        System.out.println("Retrieving for dates " + startDate + " " + endDate);

        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        Analytics analytics = initializeAnalytics();

        MongoClient mongo = new MongoClient("localhost", 27017);
        DB regus_analytics_db = mongo.getDB("regus_analytics");

        DBCollection regus_visited_companies = regus_analytics_db.getCollection("ga");
        DBCollection regus_visit_attributes = regus_analytics_db.getCollection("visit_attrs");
        DBCollection centerMapping = regus_analytics_db.getCollection("center_mapping");

        GaData gaData;

        for (Date d = startDate; !DateUtils.isSameDay(d, DateUtils.addDays(endDate, 1)); d = DateUtils
                .addDays(d, 1)) {
            int startIndex = 0;
            do {
                System.out.println("Executing data query for visited companies for date: " + d);
                gaData = executeDataQueryForVisitedCompanies(analytics, TABLE_ID, startIndex, d);
                insertVisitedCompaniesData(gaData, regus_visited_companies, d);
                startIndex = gaData.getQuery().getStartIndex() + gaData.getQuery().getMaxResults();
            } while (gaData.getNextLink() != null && !gaData.getNextLink().isEmpty());

            startIndex = 0;
            do {
                System.out.println("Executing data query for visit attributes for date: " + d);
                gaData = executeDataQueryForVisitAttributes(analytics, TABLE_ID, startIndex, d);
                insertVisitAttributesData(gaData, regus_visit_attributes, d, centerMapping);

                startIndex = gaData.getQuery().getStartIndex() + gaData.getQuery().getMaxResults();
            } while (gaData.getNextLink() != null && !gaData.getNextLink().isEmpty());
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.groupon.jenkins.DotCiModule.java

License:Open Source License

@Provides
@Singleton//  w  ww .jav  a 2  s.  c  om
Mongo providesMongo() {
    Mongo mongo = null;

    try {
        mongo = new MongoClient(SetupConfig.get().getDbHost(), SetupConfig.get().getDbPort());
    } catch (UnknownHostException e) {
        addError(e);
    }

    return mongo;
}

From source file:com.groupon.jenkins.mongo.MongoRepository.java

License:Open Source License

/**
 * System.setProperty("DEBUG.MONGO", "true"); Enable DB operation tracing
 * System.setProperty("DB.TRACE", "true");
 * //from   ww  w .  j a  va  2  s  . c  om
 * @return {@link MongoClient}
 */
protected static MongoClient getClient() {
    try {
        return new MongoClient(SetupConfig.get().getDbHost(), SetupConfig.get().getDbPort());
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.handu.open.dubbo.monitor.config.MongoConfig.java

License:Apache License

@Override
@Bean/*  w  w w .j  av a2 s  . com*/
public Mongo mongo() throws Exception {
    final String url = Preconditions.checkNotNull(env.getProperty(DB_URL));
    final int port = Integer.parseInt(env.getProperty(DB_PORT, "27017"));
    final String username = env.getProperty(DB_USERNAME);
    final String database = env.getProperty(DB_DATABASE);
    final String password = env.getProperty(DB_PASSWORD);

    return new MongoClient(singletonList(new ServerAddress(url, port)),
            singletonList(MongoCredential.createCredential(username, database, password.toCharArray())));
}

From source file:com.health.smart.util.MongoC.java

private static synchronized MongoClient getClient() throws UnknownHostException {
    if (client == null) {
        MongoCredential credential = MongoCredential.createMongoCRCredential("m.smart.health", "comp5527",
                "comp5527g3".toCharArray());
        client = new MongoClient(new ServerAddress("ds031947.mongolab.com", 31947), Arrays.asList(credential));
    }// ww  w.  ja va2 s. c  o  m
    return client;
}

From source file:com.helion3.prism.storage.mongodb.MongoStorageAdapter.java

License:MIT License

/**
 * Establish connections to the database
 *
 * @return Whether we could connect properly
 *///from   ww w.j  a  v  a  2 s  . co  m
@Override
public boolean connect() throws Exception {
    String host = Prism.getConfig().getNode("db", "mongo", "host").getString();
    int port = Prism.getConfig().getNode("db", "mongo", "port").getInt();

    mongoClient = new MongoClient(host, port);

    // @todo support auth: boolean auth = db.authenticate(myUserName, myPassword);

    // Connect to the database
    database = mongoClient.getDatabase(databaseName);

    // Create indexes
    try {
        getCollection(collectionEventRecordsName).createIndex(new Document("Location.X", 1)
                .append("Location.Z", 1).append("Location.Y", 1).append("Created", -1));
        getCollection(collectionEventRecordsName)
                .createIndex(new Document("Created", -1).append("EventName", 1));

        // TTL
        IndexOptions options = new IndexOptions().expireAfter(0L, TimeUnit.SECONDS);
        getCollection(collectionEventRecordsName).createIndex(new Document("Expires", 1), options);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return false;
}