List of usage examples for com.mongodb MongoClient MongoClient
public MongoClient(final MongoClientURI uri, final MongoDriverInformation mongoDriverInformation)
From source file:com.ibm.gaiandb.mongodb.MongoConnectionFactory.java
License:Open Source License
/** * Returns a handle to a Mongo DB object - which may be used to manage collections. * /*from w w w .jav a 2s. co m*/ * @param connectionParams - object containing all the parameters needed to connect to MongoDB * @exception UnknownHostException - if we cannot connect to the mongoDB host specified * @exception AuthenticationException - if authentication with the mongoDB process fails. * */ public static DB getMongoDB(MongoConnectionParams connectionParams) throws Exception { // connect to the mongo process MongoClient mongoClient = new MongoClient(connectionParams.getHostAddress(), connectionParams.getHostPort()); if (mongoClient == null) throw new ConnectException(MongoMessages.DSWRAPPER_MONGODB_CONNECTION_ERROR); // Connect to the specific database DB mongoDb = mongoClient.getDB(connectionParams.getDatabaseName()); // TBD possibly try to reuse these. if (mongoDb == null) throw new ConnectException(MongoMessages.DSWRAPPER_MONGODB_DATABASE_CONN_ERROR); // Authenticate if the configuration parameters have been set String userName = connectionParams.getUserName(); String password = connectionParams.getPassword(); if (userName != null && password != null) { boolean authenticated = mongoDb.authenticate(userName, password.toCharArray()); if (!authenticated) { throw new AuthenticationException(MongoMessages.DSWRAPPER_MONGODB_AUTHENTICATION_ERROR); } } return mongoDb; }
From source file:com.ibm.research.mongotx.daytrader.MongoTrade.java
License:Open Source License
public MongoTrade() { MongoClient client;/*w ww.ja v a2 s . co m*/ try { client = new MongoClient(// System.getProperty("trade.mongo.url", "localhost"), // Integer.parseInt(System.getProperty("trade.mongo.port", "27017"))); } catch (Exception e) { throw new IllegalStateException(e); } MongoDatabase db = client.getDatabase(System.getProperty("trade.mongo.db", "trade")); txDB = new LatestReadCommittedTxDB(client, db); }
From source file:com.ifactory.service.weather.photo.PhotoService.java
License:Apache License
public PhotoService(String host, int port, String dbName, String origin) throws UnknownHostException { this.weatherId = -1; this.mongoClient = new MongoClient(host, port); this.dbName = dbName; this.origin = origin; }
From source file:com.iluwatar.hexagonal.banking.MongoBank.java
License:Open Source License
/** * Connect to database with given parameters *///from w ww . j av a 2s. c om public void connect(String dbName, String accountsCollectionName) { if (mongoClient != null) { mongoClient.close(); } mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); accountsCollection = database.getCollection(accountsCollectionName); }
From source file:com.iluwatar.hexagonal.database.MongoTicketRepository.java
License:Open Source License
/** * Connect to database with given parameters *///from w w w .j ava2 s . c om public void connect(String dbName, String ticketsCollectionName, String countersCollectionName) { if (mongoClient != null) { mongoClient.close(); } mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); ticketsCollection = database.getCollection(ticketsCollectionName); countersCollection = database.getCollection(countersCollectionName); if (countersCollection.count() <= 0) { initCounters(); } }
From source file:com.iluwatar.hexagonal.eventlog.MongoEventLog.java
License:Open Source License
/** * Connect to database with given parameters *//*from w w w.j a v a2s.com*/ public void connect(String dbName, String eventsCollectionName) { if (mongoClient != null) { mongoClient.close(); } mongoClient = new MongoClient(System.getProperty("mongo-host"), Integer.parseInt(System.getProperty("mongo-port"))); database = mongoClient.getDatabase(dbName); eventsCollection = database.getCollection(eventsCollectionName); }
From source file:com.imos.sample.MongoDBJDBC.java
public static void main(String args[]) { try {/*from w w w. ja v a 2 s . c o m*/ // To connect to mongodb server MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases DB db = mongoClient.getDB("test"); System.out.println("Connect to database successfully"); // boolean auth = db.authenticate(myUserName, myPassword); // System.out.println("Authentication: "+auth); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.impetus.client.mongodb.MongoDBClientFactory.java
License:Apache License
/** * On set mongo server properties./*from w ww .j a v a 2s . co m*/ * * @param contactNode * the contact node * @param defaultPort * the default port * @param poolSize * the pool size * @param addrs * the addrs * @return the mongo client * @throws UnknownHostException * the unknown host exception */ private MongoClient onSetMongoServerProperties(String contactNode, String defaultPort, String poolSize, List<ServerAddress> addrs) throws UnknownHostException { MongoClient mongo = null; MongoClientOptions mo = null; MongoDBSchemaMetadata metadata = MongoDBPropertyReader.msmd; ClientProperties cp = metadata != null ? metadata.getClientProperties() : null; Properties propsFromCp = null; if (cp != null) { DataStore dataStore = metadata != null ? metadata.getDataStore() : null; List<Server> servers = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection().getServers() : null; if (servers != null && !servers.isEmpty()) { for (Server server : servers) { addrs.add( new ServerAddress(server.getHost().trim(), Integer.parseInt(server.getPort().trim()))); } } propsFromCp = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection().getProperties() : null; } else { for (String node : contactNode.split(Constants.COMMA)) { if (StringUtils.countMatches(node, Constants.COLON) == 1) { // node is given with hostname and port // count == 1 is to exclude IPv6 addresses String host = node.split(":")[0]; int port = Integer.parseInt(node.split(Constants.COLON)[1]); addrs.add(new ServerAddress(host.trim(), port)); } else { addrs.add(new ServerAddress(node.trim(), Integer.parseInt(defaultPort.trim()))); } } } MongoClientOptions.Builder b = new PopulateMongoOptions(propsFromCp, externalProperties).prepareBuilder(); mo = b.build(); if (mo.getConnectionsPerHost() <= 0 && !StringUtils.isEmpty(poolSize)) { mo = b.connectionsPerHost(Integer.parseInt(poolSize)).build(); } mongo = new MongoClient(addrs, mo); return mongo; }
From source file:com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager.java
License:Apache License
/** * initiate client method initiates the client. * /*from w w w . j a v a 2s.c o m*/ * @return boolean value ie client started or not. * */ protected boolean initiateClient() { String message = null; for (String host : hosts) { if (host == null || !StringUtils.isNumeric(port) || port.isEmpty()) { logger.error("Host or port should not be null / port should be numeric"); throw new IllegalArgumentException("Host or port should not be null / port should be numeric"); } try { mongo = new MongoClient(host, Integer.parseInt(port)); db = mongo.getDB(databaseName); try { MongoDBUtils.authenticate(puMetadata.getProperties(), externalProperties, db); } catch (ClientLoaderException e) { throw new SchemaGenerationException(e); } catch (KunderaAuthenticationException e) { throw new SchemaGenerationException(e); } return true; } catch (UnknownHostException e) { message = e.getMessage(); logger.error("Database host cannot be resolved, Caused by", e); } } throw new SchemaGenerationException("Database host cannot be resolved, Caused by" + message); }
From source file:com.intuit.tweetstest.TweetsController.java
@RequestMapping(value = "/feed", method = RequestMethod.GET) protected String fetchFeeds(HttpServletRequest request, HttpServletResponse response) throws ParseException, ServletException, IOException, Exception { JSONObject result = new JSONObject(); String user = request.getParameter("user"); if (user != null && !user.isEmpty()) { String countStr = request.getParameter("count"); int count; // If count parameter is not sent in request, set it to 100 if (countStr != null && !countStr.isEmpty()) { count = Integer.parseInt(countStr); } else {//from ww w . ja v a2 s.c o m count = 100; } // The access to the MongoDB should itself be a part of a separate // package with all the DB APIs wrapped around and published to the users. // Not doing it here to save some time. MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("tweetsdb"); DBCollection usersCollection = db.getCollection("userscollection"); // Not checking if the user is a valid user or not here. That's a // separate code flow on itself. DBObject query = new BasicDBObject("user", user); // Here I am retrieving the list of users the current user is following DBObject userDocument = usersCollection.findOne(query); if (userDocument == null) { result.put(user, "No such user"); result.put("isSuccess", false); sendResponse(response, result); return null; } JSONObject json = (JSONObject) new JSONParser().parse(userDocument.toString()); JSONArray following = (JSONArray) json.get("following"); // A sample of the following array looks like ["user4", "user3"] List<String> followingList = getFollowingList(following); // Once the following list is retrieved, the tweets of those users are // read from the db. JSONArray tweetsArray = retrieveTweetsFromDB(db, followingList, count); result.put("tweets", tweetsArray); result.put("isSuccess", true); } else { System.out.println("Missing user parameter in the request. Returning error"); result.put("Missing parameter", "user"); result.put("isSuccess", false); } sendResponse(response, result); return null; }