List of usage examples for com.mongodb Mongo Mongo
Mongo(final MongoClientURI mongoURI, @Nullable final MongoDriverInformation mongoDriverInformation)
From source file:com.mythesis.userbehaviouranalysis.RequestServlet.java
License:Apache License
/** * Handles the HTTP <code>POST</code> method. * @param request servlet request//from w ww . ja v a 2s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userPath = request.getServletPath(); File input = new File("D://UserBehaviourAnalysisInput.txt"); ProfileAnalysis analysis = new ProfileAnalysis(); switch (userPath) { // if history is sent case "/history": String id = request.getParameter("userID"); String[] urls = request.getParameter("urls").split(","); Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("profileAnalysis"); DBCollection userinfo = db.getCollection("userinfo"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("userID", id); DBCursor cursor = userinfo.find(searchQuery); if (cursor.hasNext()) { DateTime current = new DateTime(); SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm"); DBObject entry = cursor.next(); String check = (String) entry.get("timestamp"); Date temp = null; try { temp = format.parse(check); } catch (ParseException ex) { Logger.getLogger(RequestServlet.class.getName()).log(Level.SEVERE, null, ex); } DateTime previous = new DateTime(temp); System.out.println("last history analysis on: " + previous); System.out.println("current date/time: " + current); Duration duration = new Duration(previous, current); if (duration.getStandardHours() < 24) break; } analysis.perform(id, urls, input); break; // if query is sent case "/query": try { JSONObject data = new JSONObject(request.getParameter("data")); Iterator it = data.keys(); ArrayList<String> profiles = new ArrayList<>(); ArrayList<String> queries = new ArrayList<>(); while (it.hasNext()) { String key = (String) it.next(); profiles.add(key); queries.add((String) data.get(key)); } analysis.storeQueries(profiles, queries, input); } catch (JSONException ex) { Logger.getLogger(RequestServlet.class.getName()).log(Level.SEVERE, null, ex); } break; } }
From source file:com.original.service.channel.config.Initializer.java
License:Open Source License
/** * //from w w w . jav a2 s . c o m * @throws Exception */ public void init(boolean force) throws Exception { try { logger = Logger.getLogger("Channel Service"); if (mongo == null) { mongo = new Mongo(Constants.Channel_DB_Server, Constants.Channel_DB_Server_Port); } db = mongo.getDB(Constants.Channel_DB_Name); // init profile String fileName = System.getProperty("user.dir") + "\\config\\profile.json"; File confDir = new File(fileName); String collectionName = Constants.Channel_Collection_Profile; if (!confDir.exists()) { fileName = "/com/original/service/channel/config/profile.json"; } initProfile(db, collectionName, fileName, force); // init channel collectionName = Constants.Channel_Collection_Channel; fileName = "/com/original/service/channel/config/channel.json"; initPeople(db, collectionName, fileName, force); // init people collectionName = Constants.Channel_Collection_People; fileName = "/com/original/service/channel/config/people.json"; initChannel(db, collectionName, fileName, force); } catch (Exception exp) { throw exp; } }
From source file:com.original.service.channel.core.ChannelService.java
License:Open Source License
/** * ???/*from w w w .j a v a 2s . c o m*/ */ private void initMongoDB() { //?, throws ChannelException //1 log logger = Logger.getLogger("channer"); //2 db morphia = new Morphia(); morphia.map(ChannelAccount.class); morphia.map(Channel.class); morphia.map(Profile.class); morphia.map(Attachment.class); morphia.map(People.class); logger.log(Level.INFO, "Mapping POJO to Mongo DB!"); // DB try { mongo = new Mongo(Channel_DB_Server, Channel_DB_Server_Port); // db mapping to object ds = morphia.createDatastore(mongo, Channel_DB_Name); ds.ensureIndexes(); } catch (Exception exp) { logger.log(Level.SEVERE, "To connect MongoDB Service fail!" + exp.toString()); //Pending, if fail , should throw exception or exit. return; } //reread data from config initializer = new Initializer(mongo); try { initializer.init(false); } catch (Exception exp) { logger.log(Level.SEVERE, "To init channel db fail!" + exp.toString()); } //4 serice managers //?? messageManager = new MessageManager(this, morphia, mongo, ds); //?? channelManager = new ChannelManager(this, mongo, morphia, ds); //???? accountManager = new AccountManager(this, mongo, morphia, ds, channelManager); //?? peopleManager = new PeopleManager(this, morphia, mongo, ds); }
From source file:com.ovea.mongodb.EmbeddedMongoDB.java
License:Apache License
public static EmbeddedMongoDB addRunning(int port, String username, String password) { try {//from w ww .j a v a 2 s . co m Mongo mongo = null; File path = null; try { mongo = new Mongo("localhost", port); DB db = mongo.getDB("admin"); if (username != null && password != null) db.authenticate(username, password.toCharArray()); BSONObject obj = (BSONObject) db.command("getCmdLineOpts").get("parsed"); if (obj != null) { String val = (String) obj.get("dbpath"); if (val != null) path = new File(val); } } finally { if (mongo != null) mongo.close(); } return add(new FileEntry(port, -1, path)); } catch (UnknownHostException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:com.ovea.mongodb.EmbeddedMongoDBMain.java
License:Apache License
public static void main(String[] args) throws InterruptedException, IOException { String path = System.getProperty("os.name").toLowerCase().contains("windows") ? "mongod.exe" : "mongod"; EmbeddedMongoDB embeddedMongoDB = EmbeddedMongoDB.getOrCreate(path, "--nohttpinterface"); // add users/*from w ww. j a v a2 s. c o m*/ try { Mongo mongo = new Mongo("localhost", embeddedMongoDB.port()); DB smt = mongo.getDB("smt"); smt.addUser("smt", "ilovesmt".toCharArray()); DB admin = mongo.getDB("admin"); admin.addUser("admin", "admin".toCharArray()); mongo.close(); } catch (Exception e) { } System.out.println("terminate"); // restart DB with auth option embeddedMongoDB.terminate(); System.out.println("getOrCreate"); embeddedMongoDB = EmbeddedMongoDB.getOrCreate(path, "--nohttpinterface", "--auth", "--dbpath", embeddedMongoDB.dbPath().getAbsolutePath()); System.out.println("waitFor"); System.out.println(embeddedMongoDB.port()); System.out.println(embeddedMongoDB.pid()); System.out.println(embeddedMongoDB.dbPath()); System.in.read(); embeddedMongoDB.terminate(); }
From source file:com.paradigma.recommender.db.MongoDBDataModel.java
License:Apache License
private void buildModel() throws UnknownHostException, MongoException { userIsObject = false;/*from w w w. j a v a2 s .c o m*/ 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 || (mongoAuth && db.authenticate(mongoUsername, mongoPassword.toCharArray()))) { collection = db.getCollection(mongoCollection); collectionMap = db.getCollection(MONGO_MAP_COLLECTION); 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:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java
License:Apache License
/** * Establishes the connection to mongo database. This method relies on the * following configs being passed as arguments: <br> * db.name <br>//from w w w.j a v a2 s . c om * db.host <br> * db.port <br> * <p> * Once the connection is open, the method will ensure that the mongo * collections and indexes are created. * * @throws C3POPersistenceException if something goes wrong. Make sure to check the cause of the * exception. */ @Override public void establishConnection(Map<String, String> config) throws C3POPersistenceException { //this.close(); if (config == null || config.keySet().isEmpty()) { throw new C3POPersistenceException("Cannot establish connection. No configuration provided"); } try { String uri = config.get(CNF_DB_URI); String name = config.get(CNF_DB_NAME); if (uri != null && uri.length() > 0) { MongoClientURI mongoClientURI = new MongoClientURI(uri); mongo = new MongoClient(mongoClientURI); this.db = this.mongo.getDB(name); } else { String host = config.get(CNF_DB_HOST); int port = Integer.parseInt(config.get(CNF_DB_PORT)); this.mongo = new Mongo(host, port); this.db = this.mongo.getDB(name); } DBObject uid = new BasicDBObject("uid", 1); DBObject key = new BasicDBObject("key", 1); DBObject unique = new BasicDBObject("unique", true); this.db.getCollection(TBL_ELEMENTS).createIndex(uid); this.db.getCollection(TBL_PROEPRTIES).createIndex(key); this.collections.put(Source.class.getName(), this.db.getCollection(TBL_SOURCES)); this.collections.put(Element.class.getName(), this.db.getCollection(TBL_ELEMENTS)); this.collections.put(Property.class.getName(), this.db.getCollection(TBL_PROEPRTIES)); this.collections.put(ActionLog.class.getName(), this.db.getCollection(TBL_ACTIONLOGS)); if (this.dbCache == null) { DBCache cache = new DBCache(); cache.setPersistence(this); this.dbCache = cache; } this.connected = true; } catch (NumberFormatException e) { LOG.error("Cannot parse port information! Error: {}", e.getMessage()); throw new C3POPersistenceException("Could not parse port information", e); } catch (MongoException e) { LOG.error("The mongo driver threw an exception! Error: {}", e.getMessage()); throw new C3POPersistenceException("A mongo specific error occurred", e); } }
From source file:com.photon.phresco.service.api.MongoConfig.java
License:Apache License
@Override public @Bean Mongo mongo() throws PhrescoException { Mongo mongo = null;// ww w. j a v a 2s . c o m try { mongo = new Mongo(config.getDbHost(), config.getDbPort()); } catch (UnknownHostException e) { throw new PhrescoException(EX_PHEX00002); } catch (MongoException e) { throw new PhrescoException(EX_PHEX00003); } return mongo; }
From source file:com.photon.phresco.service.impl.DbService.java
License:Apache License
private GridFS getGridFs() throws PhrescoException { if (isDebugEnabled) { LOGGER.debug("DbService.getGridFs:Entry"); }//from ww w .j av a 2s . c om try { Mongo mongo = new Mongo(serverConfig.getDbHost(), serverConfig.getDbPort()); DB db = mongo.getDB(serverConfig.getDbName()); GridFS gfsPhoto = new GridFS(db, "icons"); if (isDebugEnabled) { LOGGER.debug("DbService.getGridFs:Exit"); } return gfsPhoto; } catch (UnknownHostException e) { if (isDebugEnabled) { LOGGER.error("DbService.getGridFs", STATUS_FAILURE, MESSAGE_EQUALS + "\"" + e.getLocalizedMessage() + "\""); } throw new PhrescoException(e); } catch (MongoException e) { if (isDebugEnabled) { LOGGER.error("DbService.getGridFs", STATUS_FAILURE, MESSAGE_EQUALS + "\"" + e.getLocalizedMessage() + "\""); } throw new PhrescoException(e); } }
From source file:com.sample.MyGroceryListServlet.java
License:Open Source License
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//*from w w w . j ava2 s . c o m*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Reference: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver String envVars = System.getenv("VCAP_SERVICES"); DBObject dbO = (DBObject) JSON.parse(envVars); String parsedString = dbO.get("mongodb").toString(); // Remove trailing and starting array brackets (otherwise it won't be valid JSON) parsedString = parsedString.replaceFirst("\\[ ", ""); parsedString = parsedString.replaceFirst("\\]$", ""); // Get the credentials dbO = (DBObject) JSON.parse(parsedString); parsedString = dbO.get("credentials").toString(); // For debugging only // System.out.println(parsedString); dbO = (DBObject) JSON.parse(parsedString); System.out.println("Host name : " + dbO.get("hostname")); String hostName = dbO.get("hostname").toString(); int port = Integer.parseInt(dbO.get("port").toString()); String dbName = dbO.get("db").toString(); String userName = dbO.get("username").toString(); String password = dbO.get("password").toString(); Mongo mongoClient = new Mongo(hostName, port); DB db = mongoClient.getDB(dbName); db.authenticate(userName, password.toCharArray()); // Clean up old entries DBCollection coll = db.getCollection("testCollection"); coll.drop(); BasicDBObject lastAddedObject = null; for (String curItem : myGroceryList) { lastAddedObject = new BasicDBObject("i", curItem); coll.insert(lastAddedObject); } response.getWriter().println("<b>My grocery list is:</b>"); coll.remove(lastAddedObject); DBCollection loadedCollection = db.getCollection("testCollection"); DBCursor cursor = loadedCollection.find(); try { response.getWriter().println("<ul>"); while (cursor.hasNext()) { response.getWriter().println("<li>" + cursor.next().get("i") + "</li>"); } response.getWriter().println("</ul>"); } finally { cursor.close(); } }