List of usage examples for com.mongodb MongoClient getDB
@Deprecated public DB getDB(final String dbName)
From source file:com.azure.api.MongoDAO.java
public static LinkedList<String> MongoConnection2() throws IOException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("test"); DBCollection table = db.getCollection("DataFinal"); DBObject sortFields = new BasicDBObject("count", -1); DBObject groupGenreFields = new BasicDBObject("_id", "$Genre1"); groupGenreFields.put("count", new BasicDBObject("$sum", 1)); DBObject genregroup = new BasicDBObject("$group", groupGenreFields); AggregationOutput Genreoutput = table.aggregate(genregroup, new BasicDBObject("$sort", sortFields)); LinkedList<String> stringResult = new LinkedList<String>(); int count = 0; for (DBObject res : Genreoutput.results()) { stringResult.add(res.get("_id").toString()); System.out.println(res.get("_id").toString()); count++;/*from ww w. j ava2 s . c om*/ if (count == 8) break; } System.out.print("strinResult Size" + stringResult.size()); return stringResult; }
From source file:com.azure.api.MongoDAO.java
public static LinkedList<String> MongoConnection3() throws IOException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("test"); DBCollection table = db.getCollection("DataFinal"); DBObject sortFields = new BasicDBObject("count", -1); DBObject groupGenreFields = new BasicDBObject("_id", "$Author"); groupGenreFields.put("count", new BasicDBObject("$sum", 1)); DBObject genregroup = new BasicDBObject("$group", groupGenreFields); AggregationOutput Genreoutput = table.aggregate(genregroup, new BasicDBObject("$sort", sortFields)); LinkedList<String> stringResult = new LinkedList<String>(); int count = 0; for (DBObject res : Genreoutput.results()) { stringResult.add(res.get("_id").toString()); System.out.println(res.get("_id").toString()); count++;//from www .j a va2 s . c o m if (count == 8) break; } System.out.print("strinResult Size" + stringResult.size()); return stringResult; }
From source file:com.badger.observationmongotest.execute.Main.java
public static void main(String[] args) throws ParseException, UnknownHostException, IOException { List<Observation> observations = new LinkedList(); Customer customer = new Customer(); customer.setName("Mr Customer"); customer.setId("cid123"); customer.setBackOfficeId("boid123"); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); String dateStr = "2015/08/10"; Date date = format.parse(dateStr); CustomerObservationReport report = new CustomerObservationReport(customer); MonthlyProductOrderCountIssue productOrderCountIssue = new MonthlyProductOrderCountIssue(); productOrderCountIssue.setActionRequired(true); productOrderCountIssue.setCatagory("product issue"); productOrderCountIssue.setCurrentYear(2015); productOrderCountIssue.setCurrentYearValue(30); productOrderCountIssue.setCustomerId(customer.getId()); productOrderCountIssue.setDate(date); productOrderCountIssue.setDrop(50.0); productOrderCountIssue.setLastYearValue(60); productOrderCountIssue.setMonth("Feb"); productOrderCountIssue.setObservationId("oid123"); productOrderCountIssue.setPreviousYear(2014); productOrderCountIssue.setProductName("cool product"); productOrderCountIssue.setScore(4500); productOrderCountIssue.setType("monthy order count"); MonthlyProductOrderCountIssue monthlyProductOrderCountIssue = new MonthlyProductOrderCountIssue(); monthlyProductOrderCountIssue.setActionRequired(true); monthlyProductOrderCountIssue.setCatagory("product issue"); monthlyProductOrderCountIssue.setCurrentYear(2015); monthlyProductOrderCountIssue.setCurrentYearValue(30); monthlyProductOrderCountIssue.setCustomerId(customer.getId()); monthlyProductOrderCountIssue.setDate(date); monthlyProductOrderCountIssue.setDrop(50.0); monthlyProductOrderCountIssue.setLastYearValue(60); monthlyProductOrderCountIssue.setMonth("March"); monthlyProductOrderCountIssue.setObservationId("oid456"); monthlyProductOrderCountIssue.setPreviousYear(2014); monthlyProductOrderCountIssue.setProductName("cool product"); monthlyProductOrderCountIssue.setScore(4500); monthlyProductOrderCountIssue.setType("monthy order count"); MonthlyProductRevenueIssue monthlyProductRevenueIssue = new MonthlyProductRevenueIssue(); monthlyProductRevenueIssue.setActionRequired(true); monthlyProductRevenueIssue.setCatagory("product issue"); monthlyProductRevenueIssue.setCurrentYear(2015); monthlyProductRevenueIssue.setCurrentYearValue(3000.00); monthlyProductRevenueIssue.setCustomerId(customer.getId()); monthlyProductRevenueIssue.setDate(date); monthlyProductRevenueIssue.setDrop(50.0); monthlyProductRevenueIssue.setLastYearValue(6000.00); monthlyProductRevenueIssue.setMonth("Dec"); monthlyProductRevenueIssue.setObservationId("oid3445"); monthlyProductRevenueIssue.setPreviousYear(2014); monthlyProductRevenueIssue.setProductName("test product"); monthlyProductRevenueIssue.setScore(5667); monthlyProductRevenueIssue.setType("monthly product ervenue"); MonthlyRevenueIssue monthlyRevenueIssue = new MonthlyRevenueIssue(); monthlyRevenueIssue.setActionRequired(true); monthlyRevenueIssue.setCatagory("Reveue Issue"); monthlyRevenueIssue.setCurrentValue(3000); monthlyRevenueIssue.setCurrentYear(2015); monthlyRevenueIssue.setCustomerId(customer.getId()); monthlyRevenueIssue.setDate(date);//from ww w .j a v a 2 s . c o m monthlyRevenueIssue.setDrop(45.0); monthlyRevenueIssue.setMonth("Nov"); monthlyRevenueIssue.setObservationId("oid4646646"); monthlyRevenueIssue.setPreviousValue(5000); monthlyRevenueIssue.setPreviousYear(2014); monthlyRevenueIssue.setScore(5600); monthlyRevenueIssue.setType("monthly revenue issue"); observations.add(monthlyRevenueIssue); observations.add(monthlyProductRevenueIssue); observations.add(monthlyProductOrderCountIssue); observations.add(productOrderCountIssue); report.setAccountId("acid123"); report.addObservations(observations); // BasicDBObject documentDetail = new BasicDBObject(); /** * documentDetail.put("accountId", report.getAccountId()); * documentDetail.put("customerId", report.getCustomerId()); * documentDetail.put("Observations", * report.getObservations().toString()); * */ MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("ObservationReports"); DBCollection col = db.getCollection("reports"); Gson gson = new Gson(); String json = gson.toJson(report); DBObject dbObject = (DBObject) JSON.parse(json); col.insert(dbObject); //DBObject query = BasicDBObjectBuilder.start().add("_id", report.getId()).get(); DBCursor cursor = col.find(); while (cursor.hasNext()) { System.out.println("First Cursor: " + cursor.next().get("observations")); } while (cursor.hasNext()) { DBObject dbobj = cursor.next(); Map map = dbObject.toMap(); CustomerObservationReport report2 = new CustomerObservationReport(customer); //System.out.println("observations " +dbObject.get("observations")); List<Observation> dbObservations = (List<Observation>) dbObject.get("observations"); report2.setAccountId(report.getAccountId()); report2.setCustomerId(report.getCustomerName()); report2.setBackOfficeId(report.getBackOfficeId()); report2.setObservations((dbObservations)); System.out.println(report2.getClass().getTypeName()); } }
From source file:com.bancvue.mongomigrate.MigrationHistoryRepository.java
License:Apache License
public MigrationHistoryRepository(String host, String databaseName) throws UnknownHostException { this.databaseName = databaseName; MongoClient mongoClient = new MongoClient(host); DB db = mongoClient.getDB(databaseName); DBCollection dbCollection = db.getCollection("MigrationHistory"); collection = JacksonDBCollection.wrap(dbCollection, Migration.class, String.class); }
From source file:com.bigdid.scrap.model.ConnectionDB.java
public ConnectionDB() throws UnknownHostException { MongoClient m = new MongoClient("172.16.61.21", 27017); db = m.getDB("firstdb"); }
From source file:com.board.games.dao.nodebb.NodeBBJdbcDAOImpl.java
License:Open Source License
private PlayerProfile selectPlayerProfile(int id, String externalId, int accountId, boolean useExternalId) throws Exception { WalletAdapter walletAdapter = null;//w w w . j a v a 2s. c o m if (getUseIntegrations().equals("Y")) { walletAdapter = new WalletAdapter(); } String query = ""; query = "select " + " n1.externalId, " + " n1.id, " + " n3.id " + " from " + getDbNetworkUserService() + "." + "User n1 " + " inner join " + getDbNetworkUserService() + "." + "UserAttribute n2 on n1.id=n2.user_id " + " inner join " + getDbNetWorkWalletService() + "." + "Account n3 on n1.id=n3.userId " + " where " + (useExternalId ? " n1.id= ? " : " n1.externalId= ? ") + " and " + " n3.name = n2.value "; log.warn("**** Query " + query); log.warn("User id to query " + (useExternalId ? externalId : id)); /** * Define the connection, preparedStatement and resultSet parameters */ Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /** * Open the connection */ connection = dataSource.getConnection(); /** * Prepare the statement */ preparedStatement = connection.prepareStatement(query); /** * Bind the parameters to the PreparedStatement */ // use ipb user id instead only the other for account balance log.warn("external id to look : " + Integer.parseInt(externalId)); preparedStatement.setInt(1, (useExternalId ? Integer.parseInt(externalId) : id)); /** * Execute the statement */ resultSet = preparedStatement.executeQuery(); PlayerProfile playerProfile = null; /** * Extract data from the result set */ if (resultSet.next()) { playerProfile = new PlayerProfile(); String avatar_location = ""; // playerProfile.setId(resultSet.getInt("t2.uid")); // String imageUrl = resultSet.getString("t2.avatar"); // avatar_location = getSiteUrl() + "/" + imageUrl; // String name = resultSet.getString("t2.username"); // int groupId = resultSet.getInt("t2.usergroup"); // playerProfile.setGroupId(groupId); // log.warn("name " + name); // playerProfile.setName(name); int externalRealId = resultSet.getInt("n1.externalId"); // To connect to mongodb server MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases DB db = mongoClient.getDB("nodebb"); // log.debug("Connect to database successfully"); log.debug("Execute query: authenticate"); DBCursor cursor = null; try { DBCollection collection = db.getCollection("objects"); log.warn("Collection find " + "user:" + String.valueOf(externalRealId)); cursor = collection.find(new BasicDBObject("_key", "user:" + String.valueOf(externalRealId)), new BasicDBObject("_id", 0)); avatar_location = (String) cursor.next().get("picture"); //Picture /uploads/profile/1-profileimg.png log.warn("url before " + avatar_location); if (avatar_location.indexOf("uploads") != -1) { log.warn("avatar is an upload avatar"); avatar_location = getSiteUrl() + avatar_location; } log.warn("url after " + avatar_location); playerProfile.setAvatar_location(avatar_location); } finally { if (cursor != null) { cursor.close(); } } log.warn("calling wallet account balance"); int walletAccountId = resultSet.getInt("n3.id"); AccountBalanceResult accountBalance = walletAdapter .getAccountBalance(new Long(String.valueOf(walletAccountId))); if (accountBalance != null) { Money playerMoney = (Money) accountBalance.getBalance(); log.warn(walletAccountId + " has " + playerMoney.getAmount()); playerProfile.setBalance(playerMoney.getAmount()); } int userAccountId = resultSet.getInt("n1.id"); log.warn("Getting user level for " + userAccountId); int level = walletAdapter.getUserLevel(new Long(String.valueOf(userAccountId))); log.warn("Level found : " + level); playerProfile.setLevel(level); log.warn("Level retrieved as # : " + playerProfile.getLevel()); return playerProfile; } else { log.debug("Found no user"); } } catch (SQLException e) { e.printStackTrace(); log.error("SQLException : " + e.toString()); } catch (Exception e) { log.error("Exception in selectPlayerProfile " + e.toString()); throw e; } finally { try { /** * Close the resultSet */ if (resultSet != null) { resultSet.close(); } /** * Close the preparedStatement */ if (preparedStatement != null) { preparedStatement.close(); } /** * Close the connection */ if (connection != null) { connection.close(); } } catch (SQLException e) { /** * Handle any exception */ e.printStackTrace(); } } return null; }
From source file:com.board.games.handler.nodebb.NodeBBPokerLoginServiceImpl.java
License:Open Source License
private String authenticate(String user, String password, ServerConfig serverConfig, boolean checkAge, int authTypeId) throws Exception { try {/*from ww w.ja v a 2 s. com*/ if (serverConfig == null) { log.error("ServerConfig is null."); return "-3"; } int idx = user.indexOf("_"); if (idx != -1) { // let bots through String idStr = user.substring(idx + 1); if (user.toUpperCase().startsWith("BOT")) { if (serverConfig.isUseIntegrations()) { WalletAdapter walletAdapter = new WalletAdapter(); log.debug("Calling createWalletAccount"); //walletAdapter.createWalletAccount(new Long(String.valueOf(member_id))); Long userId = walletAdapter.checkCreateNewUser(idStr, idStr, "UNUSED", new Long(0), serverConfig.getCurrency(), serverConfig.getWalletBankAccountId(), (serverConfig.getInitialAmount().multiply(new BigDecimal(20))), true, false, 0); return String.valueOf(userId); } else { return idStr; } } } if (user.toUpperCase().startsWith("GUESTXDEMO")) { return String.valueOf(pid.incrementAndGet()); } log.debug("Execute query: authenticate"); String members_pass_hash = null; String members_display_name = null; boolean authenticated = false; int member_id = 0; int posts = 0; // To connect to mongodb server MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases DB db = mongoClient.getDB("nodebb"); // log.debug("Connect to database successfully"); log.debug("Execute query: authenticate"); DBCollection collection = db.getCollection("objects"); cursor = collection.find(new BasicDBObject("username", user), new BasicDBObject("_id", 0)); members_pass_hash = (String) cursor.next().get("password"); log.error("DB members_pass_hash = " + members_pass_hash); cursor2 = collection.find(new BasicDBObject("username", user), new BasicDBObject("_id", 0)); member_id = (int) cursor2.next().get("uid"); log.error("DB member_id = " + member_id); log.debug("User: " + user + " Password " + "********"); if (members_pass_hash != null) { // Check it against database stored hash authenticated = BCrypt.checkpw(password, members_pass_hash); } else { log.debug("failed verification of hashing"); } if (authenticated) { log.debug("Authentication successful"); log.debug("Member id " + String.valueOf(member_id)); if (serverConfig.isUseIntegrations()) { WalletAdapter walletAdapter = new WalletAdapter(); log.error("Calling createWalletAccount"); //walletAdapter.createWalletAccount(new Long(String.valueOf(member_id))); Long userId = walletAdapter.checkCreateNewUser(String.valueOf(member_id), user, "UNUSED", new Long(1), serverConfig.getCurrency(), serverConfig.getWalletBankAccountId(), serverConfig.getInitialAmount(), checkAge, needAgeAgreement, authTypeId); if (userId < 0) { // user did not accept age clauses return "-5"; } log.debug("assigned new id as #" + String.valueOf(userId)); return String.valueOf(userId); } else { return String.valueOf(member_id); } /* if (posts >= 1) { return String.valueOf(member_id); } else { log.error("Required number of posts not met, denied login"); return "-2"; }*/ } else { log.error("hash not matched for user " + user + " password " + password); return "-1"; } } catch (Exception e) { log.error("Error : " + e.toString()); // throw e; } finally { close(); } return "-3"; }
From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java
License:Apache License
@Override public Partition[] getPartitions(S config) { MongoClient mongoClient = null; try {//from ww w . ja v a 2s.com mongoDeepJobConfig = initConfig(config, mongoDeepJobConfig); DBCollection collection; ServerAddress address = new ServerAddress(mongoDeepJobConfig.getHost()); List<ServerAddress> addressList = new ArrayList<>(); addressList.add(address); mongoClient = new MongoClient(addressList); //mongoClient.setReadPreference(ReadPreference.nearest()); DB db = mongoClient.getDB(mongoDeepJobConfig.getDatabase()); collection = db.getCollection(mongoDeepJobConfig.getCollection()); return isShardedCollection(collection) ? calculateShardChunks(collection) : calculateSplits(collection); } catch (UnknownHostException e) { throw new GenericException(e); } finally { if (mongoClient != null) { mongoClient.close(); } } }
From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java
License:Apache License
/** * Gets split data collection shard enviroment. * * @param shards the shards//from w w w . j av a2 s. com * @param dbName the db name * @param collectionName the collection name * @return the split data collection shard enviroment */ private Pair<BasicDBList, List<ServerAddress>> getSplitDataCollectionShardEnviroment( Map<String, String[]> shards, String dbName, String collectionName) { MongoClient mongoClient = null; try { Set<String> keys = shards.keySet(); for (String key : keys) { List<ServerAddress> addressList = getServerAddressList(Arrays.asList(shards.get(key))); mongoClient = new MongoClient(addressList); BasicDBList dbList = getSplitData(mongoClient.getDB(dbName).getCollection(collectionName)); if (dbList != null) { return Pair.create(dbList, addressList); } } } catch (UnknownHostException e) { throw new GenericException(e); } finally { if (mongoClient != null) { mongoClient.close(); } } return null; }
From source file:com.boulmier.machinelearning.jobexecutor.mongodb.Mongo.java
public static Mongo getInstance(MongoConfig wrapper) throws UnknownHostException { if (instance == null) { StringBuilder host = new StringBuilder(); MongoClient client; for (Map.Entry<String, String> param : wrapper.entrySet()) { switch (param.getKey()) { case MongoConfig.IP_FIELD: host.append(param.getValue()); break; case MongoConfig.PORT_FIELD: host.append(':').append(param.getValue()); break; }//w ww . j av a 2s . c om } client = new MongoClient(host.toString(), MongoClientOptions.builder().connectTimeout(100).build());//new MongoClient(ip, port); try { client.getDB(JobExecutorConfig.OPTIONS.LOGGING.MONGO_DEFAULT_DATABASE).command("ping"); instance = new Mongo(client); JobExecutor.logger.info("mongodb accessible at " + host); } catch (MongoTimeoutException e) { throw new UnknownHostException(); } } return instance; }