Example usage for com.mongodb Mongo Mongo

List of usage examples for com.mongodb Mongo Mongo

Introduction

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

Prototype

Mongo(final MongoClientURI mongoURI, @Nullable final MongoDriverInformation mongoDriverInformation) 

Source Link

Usage

From source file:alto.plugin.webradio.recommender.MongoDBDataModel.java

License:Apache License

private void buildModel() throws UnknownHostException {
    userIsObject = false;/*ww  w.  j  av  a 2  s  .  c  om*/
    itemIsObject = false;
    idCounter = 0;
    preferenceIsString = true;
    Mongo mongoDDBB = new Mongo(mongoHost, mongoPort);
    DB db = mongoDDBB.getDB(mongoDB);
    mongoTimestamp = new Date(0);
    FastByIDMap<Collection<Preference>> userIDPrefMap = new FastByIDMap<Collection<Preference>>();
    if (!mongoAuth || db.authenticate(mongoUsername, mongoPassword.toCharArray())) {
        collection = db.getCollection(mongoCollection);
        collectionMap = db.getCollection(mongoMapCollection);
        DBObject indexObj = new BasicDBObject();
        indexObj.put("element_id", 1);
        collectionMap.ensureIndex(indexObj);
        indexObj = new BasicDBObject();
        indexObj.put("long_value", 1);
        collectionMap.ensureIndex(indexObj);
        collectionMap.remove(new BasicDBObject());
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
            if (!user.containsKey("deleted_at")) {
                long userID = Long.parseLong(fromIdToLong(getID(user.get(mongoUserID), true), true));
                long itemID = Long.parseLong(fromIdToLong(getID(user.get(mongoItemID), false), false));
                float ratingValue = getPreference(user.get(mongoPreference));
                Collection<Preference> userPrefs = userIDPrefMap.get(userID);
                if (userPrefs == null) {
                    userPrefs = Lists.newArrayListWithCapacity(2);
                    userIDPrefMap.put(userID, userPrefs);
                }
                userPrefs.add(new GenericPreference(userID, itemID, ratingValue));
                if (user.containsKey("created_at")
                        && mongoTimestamp.compareTo(getDate(user.get("created_at"))) < 0) {
                    mongoTimestamp = getDate(user.get("created_at"));
                }
            }
        }
    }
    delegate = new GenericDataModel(GenericDataModel.toDataMap(userIDPrefMap, true));
}

From source file:am.ik.support.morphia.spring.MorphiaDataStoreFactoryBean.java

License:Apache License

@Override
public void afterPropertiesSet() throws Exception {
    mongo = new Mongo(host, port);
    ds = new Morphia().createDatastore(mongo, dbName);
    LOGGER.debug("connect mongo {}", mongo);
    LOGGER.debug("create datastore {}", ds);
}

From source file:App.classes.Mongo_BD_conection.java

public static Mongo connect() {
    try {//  w w w  .  j  a v a2  s.com
        Singleton_App.client = new Mongo(getMachine(), Integer.parseInt(getPort()));
        Singleton_App.db = Singleton_App.client.getDB(getNom_bd());
        Singleton_App.collection = Singleton_App.db.getCollection(getNom_table());
    } catch (Exception e) {
        System.out.println("Unable to open client");
        e.printStackTrace();
        if (Singleton_App.client != null) {
            try {
                Singleton_App.client.close();
            } catch (Exception ex) {
                System.out.println("Unable to close client");
                ex.printStackTrace();
            }
        }
    }
    return Singleton_App.client;
}

From source file:ch.agent.crnickl.mongodb.MongoDB.java

License:Apache License

private void open(Database database) throws T2DBException {
    try {//from w  w w . j  av a2  s .  c  o  m
        String host = configuration.getParameter(MONGODB_HOST, false);
        String port = configuration.getParameter(MONGODB_PORT, false);

        if (host != null) {
            if (port != null) {
                connection = new Mongo(host, Integer.parseInt(port));
            } else {
                connection = new Mongo(host);
            }
        } else {
            connection = new Mongo();
        }

        initialize(connection, database);

        // TODO: implement secure mode
        user = configuration.getParameter(MONGODB_USER, true);
        configuration.getParameter(MONGODB_PASSWORD, true);
        configuration.setParameter(MONGODB_USER, "zzzzz");
        configuration.setParameter(MONGODB_PASSWORD, "zzzzz");
    } catch (Exception e) {
        throw T2DBMMsg.exception(e, J.J80050, toString());
    }
}

From source file:com.AlertMailerWebPage.servlet.Show.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww  w.  j  a  v a2s. c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        Properties defaultProps = new Properties();
        InputStream in = GetProcessSpeed.class.getResourceAsStream("configuration.properties");
        defaultProps.load(in);
        in.close();
        String database = (String) defaultProps.get("database_mailerDetails");
        String collection = (String) defaultProps.get("collection_mailerDetails");
        String serverAddress = (String) defaultProps.get("IP_AMDBoard");

        Mongo mongo = new Mongo("localhost", 27017);
        //   Mongo mongo=new Mongo(serverAddress,27017);
        //DB db = mongo.getDB("dashboard" );
        DB db = mongo.getDB(database);

        DBCollection coll = db.getCollection(collection);
        //DBCollection coll=db.getCollection("users");
        DBObject query = new BasicDBObject("AlertMailer", "PRS");
        DBObject query1 = new BasicDBObject("InsertTime", -1);
        //DBObject query = new BasicDBObject("_id",-1);
        DBCursor cursor = coll.find(query).sort(query1).limit(1);

        //String name1= (String)cursor.one().get("name");    
        //while(cursor.hasNext()){
        //    out.println(""+cursor.next()+"");
        //}
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(cursor.one().toString());
    }
}

From source file:com.andreig.jetty.MongoDB.java

License:GNU General Public License

public static Mongo get() {

    if (db == null) {
        try {/*from w w  w  .j a  v a  2  s .c  om*/
            List<ServerAddress> addrs = str2addresses(Config.mongo_servers);
            MongoOptions opts = new MongoOptions();
            opts.autoConnectRetry = true;
            int thrno = Config.server_threadsno;
            if (thrno < 100)
                opts.connectionsPerHost = thrno;
            else
                opts.connectionsPerHost = 100;
            opts.threadsAllowedToBlockForConnectionMultiplier = 10;
            opts.maxWaitTime = 10000; // millisecs
            db = new Mongo(addrs, opts);
            write_concern = Config.mongo_safeoperations ? WriteConcern.FSYNC_SAFE : WriteConcern.NORMAL;
            log.info("getDB():" + db);
        } catch (UnknownHostException e) {
            log.severe("Bad host " + e);
            db = null;
        }
    }

    return db;

}

From source file:com.aperigeek.dropvault.web.dao.MongoService.java

License:Open Source License

@PostConstruct
protected void init() {
    try {/*w  w  w. j av  a  2  s  .  c  o  m*/
        mongo = new Mongo(db_host, db_port);
    } catch (Exception ex) {
        log.log(Level.SEVERE, null, ex);
    }
}

From source file:com.bbc.remarc.db.MongoClient.java

License:Apache License

/**
 * Connect to mongo instance using env variables if present
 * or fall back to local instance//from  www .j av  a2  s .co m
 * @return
 * @throws UnknownHostException
 */
public static synchronized Mongo connect() {

    if (mongo == null) {

        log.debug("Creating new MongoDB connection");

        host = System.getenv(Configuration.ENV_MONGO_HOST_OPENSHIFT);
        if (host == null || "".equals(host)) {
            log.info("Not running on OpenShift. Falling back to local mongodb");

            username = System.getenv(Configuration.ENV_MONGO_USER_LOCAL);
            password = System.getenv(Configuration.ENV_MONGO_PWD_LOCAL);
            db = System.getenv(Configuration.ENV_MONGO_DB_LOCAL);
            host = System.getenv(Configuration.ENV_MONGO_HOST_LOCAL);
            portStr = System.getenv(Configuration.ENV_MONGO_PORT_LOCAL);

            if (username == null || "".equals(username)) {
                log.debug("No username found in local environment variables, assuming default");
                username = "remarc";
            }

            if (password == null || "".equals(password)) {
                log.debug("No password found in local environment variables, assuming default");
                password = "dementia";
            }

            if (db == null || "".equals(db)) {
                log.debug("No database found in local environment variables, assuming default");
                db = "remarc";
            }

            if (host == null || "".equals(host)) {
                log.debug("No host found in local environment variables, assuming default");
                host = "localhost";
            }

            if (portStr == null || "".equals(portStr)) {
                log.debug("No port found in local environment variables, assuming default");
                portStr = "27017";
            }

            port = Integer.decode(portStr);

        } else {

            log.info("Running on OpenShift. Configuring connection");

            portStr = System.getenv(Configuration.ENV_MONGO_PORT_OPENSHIFT);
            port = Integer.decode(portStr);

            username = System.getenv(Configuration.ENV_MONGO_USER_OPENSHIFT);
            password = System.getenv(Configuration.ENV_MONGO_PWD_OPENSHIFT);
            db = System.getenv(Configuration.ENV_MONGO_DB_OPENSHIFT);

        }

        try {
            mongo = new Mongo(host, port);
        } catch (UnknownHostException ex) {
            throw new RuntimeException("Failed to connect to db", ex);
        }

    }

    return mongo;
}

From source file:com.bbytes.zorba.domain.testing.EmbeddedMongoDBFactory.java

License:Apache License

@Override
public DB getDb(String dbName) throws DataAccessException {
    //return if db already exists
    if (db != null && db.getName().equals(dbName)) {
        return db;
    }//w w  w  . ja  v a  2 s.  c o m
    try {
        int port = 12345;
        MongodConfig mongodConfig = new MongodConfig(Version.Main.V2_0, port, Network.localhostIsIPv6());
        MongodStarter runtime = MongodStarter.getDefaultInstance();
        mongodExecutable = runtime.prepare(mongodConfig);
        mongodExecutable.start();
        Mongo mongo = new Mongo("localhost", port);
        db = mongo.getDB(dbName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return db;
}

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

public DB getDB() {
    if (mongo == null) {
        mongo = new Mongo(HOST, PORT);
        db = mongo.getDB(DB_NAME);// w  ww  . jav  a2 s.  c  o m
        System.out.println("Mongo instance equals :> " + mongoInstance++);
    }
    return db;
}