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.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 w w w.  j  a  va2 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.bc.fiduceo.db.MongoDbDriver.java

License:Open Source License

@Override
public void open(BasicDataSource dataSource) throws SQLException {
    final String address = parseAddress(dataSource.getUrl());
    final String port = parsePort(dataSource.getUrl());
    final ServerAddress serverAddress = new ServerAddress(address, Integer.parseInt(port));

    final String username = dataSource.getUsername();
    final String password = dataSource.getPassword();
    if (StringUtils.isNotNullAndNotEmpty(password) && StringUtils.isNotNullAndNotEmpty(username)) {
        final MongoCredential credential = MongoCredential.createCredential(username, DATABASE_NAME,
                password.toCharArray());
        final List<MongoCredential> credentialsList = new ArrayList<>();
        credentialsList.add(credential);
        mongoClient = new MongoClient(serverAddress, credentialsList);
    } else {//from www  . ja  v  a2s.co  m
        mongoClient = new MongoClient(serverAddress);
    }
    database = mongoClient.getDatabase(DATABASE_NAME);
}

From source file:com.bdnc.ecommercebdnc.dao.DAODocumentos.java

public boolean salvarCompra(Compra compra) {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase dataBase = client.getDatabase("ecommerce-bdnc");
    MongoCollection<Document> collection = dataBase.getCollection("vendas");
    collection.insertOne(compra.toDocument());
    client.close();//from  ww w .j av a2 s. co m
    return true;
}

From source file:com.bdnc.ecommercebdnc.dao.DAODocumentos.java

public List<Compra> buscarCompras() {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase dataBase = client.getDatabase("ecommerce-bdnc");
    MongoCollection<Document> collection = dataBase.getCollection("vendas");
    List<Compra> compras = new ArrayList<>();
    MongoCursor<Document> cursor = collection.find().iterator();
    while (cursor.hasNext()) {
        Compra compra = new Compra();
        compras.add(compra.fromDocument(cursor.next()));
    }//from   w w  w  .  j  a  v a2s . co m
    client.close();
    return compras;
}

From source file:com.bigdid.model.DBFactory.java

private static MongoClient getMongoClient() throws UnknownHostException {
    MongoClient mongo;/*  w  ww .  j  av  a  2s. co  m*/
    mongo = new MongoClient("172.16.61.21", 27017);

    return mongo;
}

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;//from   w  ww .  j  a va  2 s  .c om

    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  w  w w  . ja  v  a2 s.  c  o  m
        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.reader.MongoReader.java

License:Apache License

/**
 * Init void.//  w w w . ja  v  a  2  s .  c om
 *
 * @param partition the partition
 */
public void init(Partition partition) {
    try {

        List<ServerAddress> addressList = new ArrayList<>();

        for (String s : (List<String>) ((HadoopPartition) partition).splitWrapper().getReplicas()) {
            addressList.add(new ServerAddress(s));
        }

        //Credentials
        List<MongoCredential> mongoCredentials = new ArrayList<>();

        if (mongoDeepJobConfig.getUsername() != null && mongoDeepJobConfig.getPassword() != null) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(
                    mongoDeepJobConfig.getUsername(), mongoDeepJobConfig.getDatabase(),
                    mongoDeepJobConfig.getPassword().toCharArray());
            mongoCredentials.add(credential);

        }

        mongoClient = new MongoClient(addressList, mongoCredentials);
        //mongoClient.setReadPreference(ReadPreference.valueOf(mongoDeepJobConfig.getReadPreference()));
        db = mongoClient.getDB(mongoDeepJobConfig.getDatabase());
        collection = db.getCollection(mongoDeepJobConfig.getCollection());

        dbCursor = collection.find(generateFilterQuery((MongoPartition) partition),
                mongoDeepJobConfig.getDBFields());

    } catch (UnknownHostException e) {
        throw new ExtractorInitializationException(e);
    }
}

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;/*from w ww  .j  a  v  a 2  s.  c o m*/
        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;
            }
        }

        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;
}