/** * if hourlyjob has completed,item will insert to repository db.and partial file will delete, * dailydb will delete. * * @throws UnknownHostException */ @Test public void t2() throws UnknownHostException { MongoClient mongoClient = new MongoClient(AppConstants.MONGODB_HOST, AppConstants.MONGODB_PORT); DB dailyDb = mongoClient.getDB(dailyDbName); DBCollection hourlyCol = dailyDb.getCollection(AppConstants.MongoNames.HOURLY_JOB_COL_NAME); // must drop,or complete status detect will wrong. hourlyCol.drop(); for (int idx = 24; idx > 12; idx--) { DBObject dbo = new BasicDBObject() .append(AppConstants.MongoNames.HOURLY_JOB_NUMBER_KEY, idx + "") .append(AppConstants.MongoNames.HOURLY_JOB_STATUS_KEY, "end"); hourlyCol.insert(dbo); } new DailyCopyWorkVerticle.DailyCopyProcessor( mongoClient, dailyDbName, repositoryDbName, dailyPartialDir, new JsonObject().putNumber("dailydbreadgap", 1000)) .process(); mongoClient = new MongoClient(AppConstants.MONGODB_HOST, AppConstants.MONGODB_PORT); DB db = mongoClient.getDB(repositoryDbName); DBCollection col = db.getCollection(AppConstants.MongoNames.PAGE_VISIT_COL_NAME); Assert.assertEquals(10005, col.count()); Assert.assertFalse(Files.exists(Paths.get(dailyPartialDir, dailyDbName))); }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("DotNotationTest"); lines.drop(); Random rand = new Random(); // insert 10 lines with random start and end points for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)) .append("end", new BasicDBObject("x", rand.nextInt(90) + 10)) .append("y", rand.nextInt(90) + 10)); } // Filter by x coordinate using . notation QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50); // Dot notation is also available for field selection DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
@Override public String IngresarJson(String nombreDB, String json, int clienteId) throws UnknownHostException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); // Ya existe if (ExisteCliente(nombreDB, clienteId)) { // System.out.println("********************\n"); // System.out.println("Ya existe cliente, error no se igresa el Json"); // System.out.println("********************\n"); return "Ya existe cliente, error no se igresa el Json"; } // no existe el cliente DBCollection collection = base.getCollection("Json"); BasicDBObject document = new BasicDBObject(); document.put("id", clienteId); DBObject object = (DBObject) JSON.parse(json); document.put("json", object); // document.put("json",json); collection.insert(document); return "Ok"; }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds019028.mlab.com:19028/asedb"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("UserRecords"); BasicDBObject query = new BasicDBObject(); String firstname = request.getParameter("FirstName"); String lastname = request.getParameter("LastName"); String email = request.getParameter("email"); String password = request.getParameter("EnterPassword"); String confpasswd = request.getParameter("ConfirmPassword"); query.put("First Name", firstname); query.put("Last Name", lastname); query.put("Email", email); System.out.println(email); if (password == confpasswd) { query.put("Password", password); } else { } DBCursor docs = users.find(query); response.getWriter().write(docs.toArray().toString()); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); System.out.println("Insert doget"); }
public static DB createDbMock() { DB db = mock(DB.class); MongoClient mongoClient = mock(MongoClient.class); when(mongoClient.getDB(Mockito.anyString())).thenReturn(db); MongoDBConnection.setMongoClient(mongoClient); return db; }
@Override public void run() { MongoProfile profile = options.getProfile(); MongoClient mongo = null; DBCursor cursor = null; try { mongo = new MongoClient(profile.getAddress(), profile.getCredentials()); DB db = mongo.getDB(options.getDatabase()); DBCollection col = db.getCollection(options.getCollection()); cursor = col.find(); while (cursor.hasNext()) { DBObject doc = cursor.next(); Map<String, Object> m = convert(doc); pushPipe(new Row(m)); } } catch (Throwable t) { slog.error("araqne logdb mongo: cannot run mongo.find", t); } finally { if (cursor != null) cursor.close(); if (mongo != null) mongo.close(); } }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(new ServerAddress("localhost", 27017)); final DB db = client.getDB("course"); Spark.get( new Route("/") { @Override public Object handle(Request request, Response response) { DBCollection users = db.getCollection("user"); DBObject user = users.findOne(); StringWriter writer = new StringWriter(); Configuration configuration = new Configuration(); configuration.setClassForTemplateLoading( HelloWorldMongoDBSparkFreemarkerStyle.class, "/"); try { Template template = configuration.getTemplate("hello.ftl"); template.process(user, writer); } catch (Exception e) { halt(100); e.printStackTrace(); } return writer; } }); }
public ReceiveDataResource() throws UnknownHostException { super("Mongo_URI", "Mongo_DB"); mongoClient = new MongoClient(new MongoClientURI(this.uri)); siteDatabase = mongoClient.getDB(this.db); eventsDAO = new EventsDAO(siteDatabase); formDAO = new FormDAO(siteDatabase); }
/** * @param userName * @param password * @return boolean Checks if provided username and password combination exists in database. If it * does returns true, else returns false */ public boolean userExists(String userName, String password) { boolean found = false; try { openConnection(); DB db = mongoClient.getDB("userData"); DBCollection coll1 = db.getCollection("users"); DBCursor cursor1 = coll1 .find( new BasicDBObject("userName", userName), new BasicDBObject("userPass", password)) .sort(new BasicDBObject("_id", -1)) .limit(1); if (cursor1.hasNext()) { found = true; } close(); } catch (UnknownHostException e) { e.printStackTrace(); } return found; }
public static Double connect(String s) { double score = 0; try { System.out.println("in mongo"); // mongoClient = new MongoClient("localhost", 27017); // @SuppressWarnings("deprecation") DB db = mongoClient.getDB("rank"); coll = db.getCollection("rankTable"); while (true) { // System.out.println("SEARCH"); // Scanner sc = new Scanner(System.in); // String m = sc.nextLine(); BasicDBObject q = new BasicDBObject(); q.put("path", s); DBCursor cursor = coll.find(q); while (cursor.hasNext()) { score = (double) cursor.next().get("score"); } } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } // mongoClient.close(); return score; }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuilder buffer = new StringBuilder(); BufferedReader reader = request.getReader(); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } String data = buffer.toString(); System.out.println(data); JSONObject params = new JSONObject(data); String email = (String) params.get("email"); String password = (String) params.get("password"); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds011459.mlab.com:11459/farmville"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("logindetails"); BasicDBObject newDocument = new BasicDBObject(); newDocument.append("$set", new BasicDBObject().append("password", password)); BasicDBObject searchQuery = new BasicDBObject().append("email", email); WriteResult result = users.update(searchQuery, newDocument); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); response.getWriter().write(result.toString()); }
// Steps: // 1. Install unlimited strength encryption jar files in jre/lib/security // (e.g. http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html) // 2. run kinit // 3. Set system properties, e.g.: // -Djava.security.krb5.realm=10GEN.ME -Djavax.security.auth.useSubjectCredsOnly=false // -Djava.security.krb5.kdc=kdc.10gen.me // auth.login.defaultCallbackHandler=name of class that implements // javax.security.auth.callback.CallbackHandler // You may also need to define realms and domain_realm entries in your krb5.conf file (in /etc by // default) public static void main(String[] args) throws UnknownHostException, InterruptedException { // Set this property to avoid the default behavior where the program prompts on the command line // for username/password Security.setProperty("auth.login.defaultCallbackHandler", "DefaultSecurityCallbackHandler"); String server = args[0]; String user = args[1]; String dbName = args[2]; MongoClient mongo = new MongoClient( new MongoClientAuthority( new ServerAddress(server), new MongoClientCredentials(user, MongoClientCredentials.GSSAPI_MECHANISM)), new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build()); DB testDB = mongo.getDB(dbName); System.out.println("Find one: " + testDB.getCollection("test").findOne()); System.out.println("Count: " + testDB.getCollection("test").count()); WriteResult writeResult = testDB.getCollection("test").insert(new BasicDBObject()); System.out.println("Write result: " + writeResult); System.out.println(); System.out.println("Count: " + testDB.getCollection("test").count()); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds037824.mongolab.com:37824/aseproject"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("users"); BasicDBObject query = new BasicDBObject(); query.put("name", request.getParameter("name")); query.put("password", request.getParameter("password")); DBCursor docs = users.find(); response.getWriter().write(docs.toArray().toString()); /*JSONObject obj=new JSONObject(); obj.put("message", "Hello World"); response.getWriter().write(obj.toString()); */ response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); }
/** Connect the instance. */ public synchronized MongoClient connect() { if (m == null) { Builder options = new MongoClientOptions.Builder(); options.connectionsPerHost(maxConnections); options.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockMultiplier); try { // Connect to replica servers if given. Else the standard way to one server. if (replicaServers != null && replicaServers.size() > 0) { m = new MongoClient(replicaServers, options.build()); } else { ServerAddress address = new ServerAddress(host, port); m = new MongoClient(address, options.build()); } db = m.getDB(database); db.setWriteConcern(WriteConcern.SAFE); // Try to authenticate if configured. if (useAuth) { if (!db.authenticate(username, password.toCharArray())) { throw new RuntimeException( "Could not authenticate to database '" + database + "' with user '" + username + "'."); } } } catch (UnknownHostException e) { throw new RuntimeException("Cannot resolve host name for MongoDB", e); } } return m; }
public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB feederDB = mongo.getDB("feeder"); DBCollection products = feederDB.getCollection("products"); System.out.println(products.find().size()); mongo.close(); }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds047752.mlab.com:47752/ase_lab7"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("users"); BasicDBObject query = new BasicDBObject().append("username", "Ram"); query.put("name", "Ram"); // request.getParameter("name")); query.put("password", "password"); // request.getParameter("password")); BasicDBObject newDocument = new BasicDBObject(); newDocument.put("name", "SreeRam"); users.update(query, newDocument); DBCursor docs = users.find(query); response.getWriter().write(docs.toArray().toString()); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findCriteriaTest"); collection.drop(); for (int i = 0; i < 10; i++) { collection.insert( new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100))); } QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(90); // DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt", // 10).append("$lt", 90)); System.out.println("\nCount:"); long count = collection.count(builder.get()); System.out.println(count); System.out.println("\nFind all:"); DBCursor cursor = collection.find(builder.get()); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
public static void main(String[] args) throws IOException { DB db = null; try { cargarParametros(); MongoClient mongoClient = new MongoClient(); db = mongoClient.getDB(BaseDeDatos); // System.out.println("Connect to database successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } DBCollection documentos = db.getCollection(ColeccionIndice); while (true) { BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); String consulta = lector.readLine().toLowerCase(); BasicDBObject palabra = new BasicDBObject("palabra", consulta); DBCursor cursor; cursor = documentos.find(palabra); if (cursor.count() == 0) { System.out.println("No se encuentra resultado"); } else { int cantidad_respuestas = cursor.count(); BasicDBObject respuesta = (BasicDBObject) cursor.one().get("documentos"); for (int i = 0; i < respuesta.size(); i++) { System.out.println(respuesta.get("Documento-" + Integer.toString(i))); } } } }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("dotNotationTest"); lines.drop(); Random rand = new Random(); for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", rand.nextInt(90) + 10) .append("y", rand.nextInt(90) + 10))); } QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50); DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
public void inicializa() throws Exception { try { log.info("Inicializa el cliente MongoDB"); String host = ApplicationConfiguration.getInstance().getProperty("mongo.host"); if (StringUtils.isEmpty(host)) { throw new DocumentException("No está configurado el host"); } String property = ApplicationConfiguration.getInstance().getProperty("mongo.port"); if (StringUtils.isEmpty(property)) { throw new DocumentException("No está configurado el puerto"); } int port = Integer.parseInt(property); String dbName = ApplicationConfiguration.getInstance().getProperty("mongo.data.base"); if (StringUtils.isEmpty(dbName)) { throw new DocumentException("No está configurada la base de datos"); } mongoClient = new MongoClient(host, port); dataBase = mongoClient.getDB(dbName); } catch (Exception e) { log.error("Error al iniciar el cliente: " + e.getMessage()); e.printStackTrace(); throw new DocumentException(e.getMessage()); } }
public static void main(String[] args) throws Exception { MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("mydb"); DBCollection coll = db.getCollection("collection"); lanciaTest(coll); }
public static void main(String[] args) throws UnknownHostException { System.out.println("Start Testing"); MongoClient client = new MongoClient(new ServerAddress("192.168.0.14", 27017)); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findTestFromJava"); collection.drop(); for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("x", new Random().nextInt(100))); } System.out.println("Find one:"); DBObject one = collection.findOne(); System.out.println("one = " + one); System.out.println("\nFind all:"); DBCursor cursor = collection.find(); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println("cursor = " + cur); } } finally { cursor.close(); } System.out.println("\nFind Count:"); long count = collection.count(); System.out.println("count = " + count); }
public static void main(String[] args) throws IOException { String term = JOptionPane.showInputDialog( "Welcome to our knock-off search engine! \nPlease enter a term to search:"); while (term == null || term.isEmpty()) { term = JOptionPane.showInputDialog( "You didn't input anything! \nPlease enter a term to search: "); } MongoClient mongoClient = new MongoClient("localhost", 27017); System.out.println("Establishing connection..."); // Get the connection. DB db = mongoClient.getDB("crawler"); DBCollection table = db.getCollection("urlpages"); System.out.println("Connected to MongoDB!"); db.getCollection("pagerank").drop(); Ranking ranker = new Ranking(db); ranker.link_analysis(); ranker.TFIDF(term); run(term, db); JOptionPane.showMessageDialog( null, "Search is completed! \nPlease refer to 'C:\\data\\search_results.json' for the result."); }
@Override public boolean save(String collectionName, DBObject queryData, DBObject saveData) { DB db = mongoClient.getDB(mongoDB); DBCollection coll = db.getCollection(collectionName); coll.update(queryData, saveData, true, false); return false; }
public static void main(String[] args) throws Exception { // connect to the local database server MongoClient mongoClient = new MongoClient(); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // get db names for (String s : mongoClient.getDatabaseNames()) { System.out.println(s); } // get a db DB db = mongoClient.getDB("com_mongodb_MongoAdmin"); // do an insert so that the db will really be created. Calling getDB() doesn't really take any // action with the server db.getCollection("testcollection").insert(new BasicDBObject("i", 1)); for (String s : mongoClient.getDatabaseNames()) { System.out.println(s); } // drop a database mongoClient.dropDatabase("com_mongodb_MongoAdmin"); for (String s : mongoClient.getDatabaseNames()) { System.out.println(s); } }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); // JSONObject object = new JSONObject(); // object.put("message", "Hello World"); // response.getWriter().write(object.toString()); response.getWriter().write("Read Users<br /><br />"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds031611.mongolab.com:31611/testbeerdb"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection songs = db.getCollection("users"); DBCursor docs = songs.find(); response.getWriter().write(docs.toArray().toString()); doPost(request, response); }
@Override public String ActualizarJson(String nombreDB, String json, int clienteId) throws UnknownHostException { // TODO Auto-generated method stub if (!ExisteCliente(nombreDB, clienteId)) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede actualizar"); // System.out.println("********************\n"); return "No existe el cliente, no se puede actualizar"; } MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject document = new BasicDBObject(); DBObject object = (DBObject) JSON.parse(json); document.put("id", clienteId); document.put("json", object); BasicDBObject query = new BasicDBObject().append("id", clienteId); collection.findAndModify(query, document); return "Cliente actualizado"; }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB courseDB = client.getDB("course"); DBCollection list = courseDB.getCollection("DotNotationTest"); list.drop(); Random random = new Random(); for (int i = 0; i < 10; i++) { list.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", random.nextInt(2)).append("y", random.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", random.nextInt(2)).append("y", random.nextInt(90) + 10))); } DBCursor cursor = list.find().sort(new BasicDBObject("start.x", 1).append("start.y", -1)).skip(2).limit(10); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
@Override public String Json(String nombreDB, int clienteId) throws UnknownHostException, JSONException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject query = new BasicDBObject(); query.put("id", clienteId); DBCursor cursor = collection.find(query); if (cursor.size() == 0) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede ingresar json"); // System.out.println("********************\n"); return "No existe el cliente, no se puede ingresar json"; } // Existe el cliente DBObject objeto = (DBObject) cursor.next(); DBObject json = (DBObject) objeto.get("json"); // DBObject j = JSON.parse(json.toString()); JSONObject aj = new JSONObject(json.toString()); return aj.toString(); }
public EMSMongoClient() throws IOException { Properties config = new Properties(); InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties"); config.load(in); MongoClient client; List<ServerAddress> serverAddresses = Arrays.asList( new ServerAddress( config.getProperty("mongo_host"), Integer.parseInt(config.getProperty("mongo_port")))); if (config.containsKey("mongo_user") && config.containsKey("mongo_password")) { MongoCredential credential = MongoCredential.createMongoCRCredential( config.getProperty("mongo_user"), config.getProperty("mongo_db"), config.getProperty("mongo_password").toCharArray()); client = new MongoClient(serverAddresses, Arrays.asList(credential)); } else { client = new MongoClient(serverAddresses); } DB db = client.getDB(config.getProperty("mongo_db")); this.collection = db.getCollection("sessions"); }