public void generateFile(String filename) { DB db = MongoHelper.mongoMerchantDB(); DBCollection col = db.getCollection(COLLECTION_SYNONYMS); DBCursor cursor = col.find(); try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)))) { while (cursor.hasNext()) { DBObject doc = cursor.next(); String word = doc.get(FIELD_KEY_WORLD) != null ? doc.get(FIELD_KEY_WORLD).toString() : null; String synonyms = doc.get(FIELD_KEY_WORLD) != null ? StringUtils.join((BasicDBList) doc.get(FIELD_KEY_SYNONYMS), ",") : null; if (word != null && synonyms != null) { out.println(createLine(word, synonyms)); } } } catch (IOException e) { throw new RuntimeException("IOException: Current db cursor with id: " + cursor.curr().get("_id"), e); } }
public DB createDatabase(String databaseName) throws MongoServiceException { try { DB db = client.getDB(databaseName); // save into a collection to force DB creation. DBCollection col = db.createCollection("foo", null); BasicDBObject obj = new BasicDBObject(); obj.put("foo", "bar"); col.insert(obj); // drop the collection so the db is empty // col.drop(); return db; } catch (MongoException e) { // try to clean up and fail try { deleteDatabase(databaseName); } catch (MongoServiceException ignore) {} throw handleException(e); } }
@Override public CreateServiceInstanceResponse createServiceInstance(CreateServiceInstanceRequest request) { // TODO MongoDB dashboard ServiceInstance instance = repository.findOne(request.getServiceInstanceId()); if (instance != null) { throw new ServiceInstanceExistsException(request.getServiceInstanceId(), request.getServiceDefinitionId()); } instance = new ServiceInstance(request); if (mongo.databaseExists(instance.getServiceInstanceId())) { // ensure the instance is empty mongo.deleteDatabase(instance.getServiceInstanceId()); } DB db = mongo.createDatabase(instance.getServiceInstanceId()); if (db == null) { throw new ServiceBrokerException("Failed to create new DB instance: " + instance.getServiceInstanceId()); } repository.save(instance); return new CreateServiceInstanceResponse(); }
@ChangeSet(order = "03", author = "initiator", id = "03-addSocialUserConnection") public void addSocialUserConnection(DB db) { DBCollection socialUserConnectionCollection = db.getCollection("jhi_social_user_connection"); socialUserConnectionCollection.createIndex(BasicDBObjectBuilder .start("user_id", 1) .add("provider_id", 1) .add("provider_user_id", 1) .get(), "user-prov-provusr-idx", true); }
/** * Map reduce. * * @param mongoOperation * the mongo operation * @param a * the a * @param b * the b * @param c * the c * @param d * the d * @throws UnknownHostException */ static void calcularLocalizaciones() throws UnknownHostException { String map = "function () { emit(this.localizacion, {count: 1}); }"; String reduce = " function(key, values) { var result = 0; values.forEach(function(value){ result++ }); " + "return result; }"; MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("craulerdb"); DBCollection ofertas = db.getCollection("ofertas"); MapReduceCommand cmd = new MapReduceCommand(ofertas, map, reduce, null, MapReduceCommand.OutputType.INLINE, null); MapReduceOutput out = ofertas.mapReduce(cmd); for (DBObject o : out.results()) { System.out.println(o.toString()); } }
@Override public void initialize(UimaContext aContext) throws ResourceInitializationException { super.initialize(aContext); String mongoServer = (String) aContext.getConfigParameterValue(PARAM_MONGO_SERVER); int mongoPort = (Integer) aContext.getConfigParameterValue(PARAM_MONGO_PORT); String mongoDbName = (String) aContext.getConfigParameterValue(PARAM_MONGO_DB_NAME); try { mongoClient = new MongoClient(mongoServer, mongoPort); } catch (UnknownHostException e) { throw new ResourceInitializationException(e); } DB db = mongoClient.getDB(mongoDbName); gridFS = new GridFS(db); }
public DB getDB(String database, String username, String password) { if(log.isDebugEnabled()) { log.debug("username: " + username+", password: " + password+", database: " + database); } DB db = mongo.getDB(database); boolean authenticated = db.isAuthenticated(); if(!authenticated) { if(username != null && password != null && username.length() > 0 && password.length() > 0) { authenticated = db.authenticate(username, password.toCharArray()); } } if(log.isDebugEnabled()) { log.debug("authenticated: " + authenticated); } return db; }
/** * Evaluate a script on the database * * @param db * database connection to use * @param script * script to evaluate on the database * @return result of evaluation on the database * @throws Exception * when evaluation on the database fails */ public Object evaluate(DB db, String script) throws Exception { if(log.isDebugEnabled()) { log.debug("database: " + db.getName()+", script: " + script); } db.requestStart(); try { db.requestEnsureConnection(); Object result = db.eval(script); if(log.isDebugEnabled()) { log.debug("Result : " + result); } return result; } finally { db.requestDone(); } }
public static void main(String[] args) throws IOException { MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("mydb"); DBCollection coll = db.getCollection("questionsCollection"); mongoClient.setWriteConcern(WriteConcern.JOURNALED); GIFTParser p = new GIFTParser(); BasicDBObject doc = null; for (Question q : p.parserGIFT("Data/questionsGIFT")) { doc = new BasicDBObject("category", q.getCategory()) .append("question", q.getText()) .append("correctanswer", q.getCorrectAnswer()) .append("wrongAnswers",q.getWrongAnswers()); coll.insert(doc); } DBCursor cursor = coll.find(); try { while(cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } }
@Override public Repository getFactoryInstance() throws UnknownHostException { String[] hostArray = this.getHost().split(","); List<String> hostList = Arrays.asList(hostArray); List<ServerAddress> serverList = new ArrayList<ServerAddress>(); for( String hostURL : hostList){ ServerAddress sa = new ServerAddress(hostURL); serverList.add(sa); } MongoClient mc = new MongoClient(serverList); DB db = mc.getDB("gravity"); DocumentNodeStore ns = new DocumentMK.Builder(). setMongoDB(db).getNodeStore(); return new Jcr(new Oak(ns)) .with(new RepositoryIndexInitializer()) .withAsyncIndexing() .createRepository(); }
@Override public void run(LogWriterConfiguration configuration, Environment environment) throws UnknownHostException, NoDBNameException { final MongoClient mongoClient = configuration.getMongoFactory().buildClient(environment); final DB db = configuration.getMongoFactory().buildDB(environment); //Register health checks environment.healthChecks().register("mongo",new MongoHealthCheck(mongoClient)); final LogWriterResource resource = new LogWriterResource( configuration.getTemplate(), configuration.getDefaultName(), db ); environment.jersey().register(resource); final LogWriterHealthCheck healthCheck = new LogWriterHealthCheck(configuration.getTemplate()); environment.healthChecks().register("logwriter", healthCheck); environment.jersey().register(resource); }
private void setPinStateOfBuild(final String product, final String version, final String build, final boolean state) { final DB db = this.client.getDB("bdd"); final DBCollection collection = db.getCollection("summary"); final BasicDBObject query = new BasicDBObject("_id",product+"/"+version); final BasicDBObject toBePinned = new BasicDBObject("pinned",build); final String method; if (state) { method = "$addToSet"; } else { method = "$pull"; } collection.update(query, new BasicDBObject(method,toBePinned)); }
public static void connection() { try { DB db = (new MongoClient("localhost", 27017)).getDB("Questions"); DBCollection coll = db.getCollection("Questions"); BasicDBObject query = new BasicDBObject(); query.put("id", 1001); DBCursor cursor = coll.find(query); while (cursor.hasNext()) { System.out.println(cursor.next()); } } catch (MongoException e) { e.printStackTrace(); } }
@Test public void testShellDirect() throws Exception { Command cmd = this.utility.parseCommand("SELECT * FROM Customers"); MongoDBConnection connection = Mockito.mock(MongoDBConnection.class); ExecutionContext context = Mockito.mock(ExecutionContext.class); DBCollection dbCollection = Mockito.mock(DBCollection.class); DB db = Mockito.mock(DB.class); Mockito.stub(db.getCollection("MyTable")).toReturn(dbCollection); Mockito.stub(db.collectionExists(Mockito.anyString())).toReturn(true); Mockito.stub(connection.getDatabase()).toReturn(db); Argument arg = new Argument(Direction.IN, null, String.class, null); arg.setArgumentValue(new Literal("$ShellCmd;MyTable;remove;{ qty: { $gt: 20 }}", String.class)); ResultSetExecution execution = this.translator.createDirectExecution(Arrays.asList(arg), cmd, context, this.utility.createRuntimeMetadata(), connection); execution.execute(); Mockito.verify(dbCollection).remove(QueryBuilder.start("qty").greaterThan(20).get()); }
@Test public void testMongodbLocalServer() throws Exception { MongoClient mongo = new MongoClient(mongodbLocalServer.getIp(), mongodbLocalServer.getPort()); DB db = mongo.getDB(propertyParser.getProperty(ConfigVars.MONGO_DATABASE_NAME_KEY)); DBCollection col = db.createCollection(propertyParser.getProperty(ConfigVars.MONGO_COLLECTION_NAME_KEY), new BasicDBObject()); col.save(new BasicDBObject("testDoc", new Date())); LOG.info("MONGODB: Number of items in collection: {}", col.count()); assertEquals(1, col.count()); DBCursor cursor = col.find(); while(cursor.hasNext()) { LOG.info("MONGODB: Document output: {}", cursor.next()); } cursor.close(); }
private static DB conectar() { MongoClient mongoClient = null; MongoCredential mongoCredential = MongoCredential .createMongoCRCredential("trivialuser", "trivial", "4btrivialmongouser".toCharArray()); try { mongoClient = new MongoClient(new ServerAddress( "ds062797.mongolab.com", 62797), Arrays.asList(mongoCredential)); } catch (UnknownHostException e) { e.printStackTrace(); } DB db = mongoClient.getDB("trivial"); System.out.println("Conexion creada con la base de datos"); return db; }
@BeforeClass public static void init() throws UnknownHostException { ServerAddress mongoServer = new ServerAddress(dbConfig.host, Integer.valueOf(dbConfig.port)); MongoCredential credential = MongoCredential.createCredential( dbConfig.username, dbConfig.name, dbConfig.password.toCharArray() ); MongoClient mongoClient = new MongoClient(mongoServer, new ArrayList<MongoCredential>() {{ add(credential); }}); DB db = mongoClient.getDB(dbConfig.name); accountService = new MongoAccountService( db); }
public CollectTraceWikipedia(ActorRef analyse, ShellService shell) { this.analyse = analyse; this.sh = shell; try { //nbre de requettes sauvegardé par interval de 30 secondes Mongo m = new Mongo(); DB db = m.getDB( "trace10" ); DBCollection collTime = db.getCollection("thirtyseconde"); DBCursor cursor = collTime.find().sort(new BasicDBObject( "debutdate" , 1 )); this.list = cursor.toArray(); } catch (Exception e) { System.out.println(e.toString()); } }
@GET @Path("/recent-builds/{product}") public DBObject getRecentBuildStatsForProduct(@BeanParam final Coordinates coordinates, @QueryParam("limit") final Integer limit) { final BasicDBList returns = new BasicDBList(); final DB db = this.client.getDB("bdd"); final DBCollection collection = db.getCollection("reportStats"); final BasicDBObject example = coordinates.getQueryObject(Field.PRODUCT); final DBCursor cursor = collection.find(example).sort(Coordinates.getFeatureSortingObject()); if (limit != null) { cursor.limit(limit); } try { while (cursor.hasNext()) { final DBObject doc = cursor.next(); returns.add(doc); } } finally { cursor.close(); } return returns; }
@SuppressWarnings("unchecked") public static void embedTestingTips(final DBObject feature, final Coordinates coordinates, final DB db) { final DBCollection tips = db.getCollection("testingTips"); final List<DBObject> elements = (List<DBObject>) feature.get("elements"); for (final DBObject scenario : elements) { DBObject oldTip = null; final BasicDBObject tipQuery = coordinates.getTestingTipsCoordinatesQueryObject((String) feature.get("id"), (String) scenario.get("id")); // get the most recent tip that is LTE to the current coordinates. i.e. sort in reverse chronological order and take the first // item (if one exists). final DBCursor oldTipCursor = tips.find(tipQuery) .sort(new BasicDBObject("coordinates.major", -1).append("coordinates.minor", -1) .append("coordinates.servicePack", -1).append("coordinates.build", -1)).limit(1); try { if (oldTipCursor.hasNext()) { oldTip = oldTipCursor.next(); scenario.put("testing-tips", oldTip.get("testing-tips")); } } finally { oldTipCursor.close(); } } }
@GET @Path("/{product}/{major}.{minor}.{servicePack}/{build}") public DBObject getPresencesForBuild(@BeanParam final Coordinates coordinates) { try { final DB db = this.client.getDB("bdd"); final DBCollection collection = db.getCollection("presence"); final BasicDBObject query = coordinates.getQueryObject(Field.PRODUCT, Field.VERSION, Field.BUILD); final BasicDBList presencesForBuild = new BasicDBList(); final DBCursor cursor = collection.find(query); while (cursor.hasNext()) { presencesForBuild.add(cursor.next()); } return presencesForBuild; } catch (final Throwable th) { th.printStackTrace(); return null; } }
@Bean public Jongo jongo() { MongoCredential credential = MongoCredential.createCredential(mongoUser, mongoDatabase, mongoPassword.toCharArray()); ServerAddress serverAddress = new ServerAddress(mongoHost, mongoPort); MongoClient mongoClient = new MongoClient(serverAddress, new ArrayList<MongoCredential>() {{ add(credential); }}); DB db = mongoClient.getDB(mongoDatabase); return new Jongo(db); }
public AgentConfigurationRepository(){ MongoClient mongoClient = new MongoClient( Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 27017); DB db = mongoClient.getDB("eim"); collection = db.getCollection("agentConfiguration"); }
public AgentRepository(){ MongoClient mongoClient = new MongoClient( Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 27017); DB db = mongoClient.getDB("eim"); collection = db.getCollection("agent"); }
public DB getDB() { if (this._schema!=null) { return this.mc.getDB(this._schema); } else { return null; } }
@ChangeSet(order = "01", author = "initiator", id = "01-addAuthorities") public void addAuthorities(DB db) { DBCollection authorityCollection = db.getCollection("jhi_authority"); authorityCollection.insert( BasicDBObjectBuilder.start() .add("_id", "ROLE_ADMIN") .get()); authorityCollection.insert( BasicDBObjectBuilder.start() .add("_id", "ROLE_USER") .get()); }
@ChangeSet(order = "04", author = "user", id = "04-addAuthorities-2") public void addAuthorities2(DB db) { DBCollection authorityCollection = db.getCollection("jhi_authority"); authorityCollection.insert( BasicDBObjectBuilder.start() .add("_id", "ROLE_MANAGER") .get()); authorityCollection.insert( BasicDBObjectBuilder.start() .add("_id", "ROLE_SUPPORT") .get()); }
@ChangeSet(order = "05", author = "user", id = "05-addAuthorities-3") public void addAuthorities3(DB db) { DBCollection authorityCollection = db.getCollection("jhi_authority"); authorityCollection.insert( BasicDBObjectBuilder.start() .add("_id", "ROLE_ACTUATOR") .get()); }
@Test public void testMongoDBConnect() throws UnknownHostException { MongoClient mongoClient = new MongoClient(new MongoClientURI(MONGO_URI)); DB database = mongoClient.getDB(DB_NAME); DBCollection events = database.getCollection(EVENT_COLLECTION_NAME); DBCollection readings = database.getCollection(READING_COLLECTION_NAME); try { assertFalse("MongoDB Events collection not accessible", events.isCapped()); assertFalse("MongoDB Readings collection not accessible", readings.isCapped()); } catch (MongoTimeoutException ex) { fail("Mongo DB not available. Check that Mongo DB has been started"); } }
public GridFS connectToDatabase(ServerAddress server) { MongoCredential credential = MongoCredential.createMongoCRCredential("hive-dataserver", "admin", "hive-dataserver".toCharArray()); MongoClient mongoClient = new MongoClient(server, Arrays.asList(credential)); logger.info("got client"); DB db = mongoClient.getDB("hive-dataserver"); logger.info("Got DB"); return new GridFS(db); }
/** Get a connection to Mongo. */ public synchronized DB getMongoDB() { if (database == null) { try { MongoClient client = new MongoClient(mongoHostname, mongoPort); database = client.getDB("gifts-user"); } catch (UnknownHostException uhe) { throw new RuntimeException(uhe); } } return database; }
/** * Delete a user. * * @param id The ID of the user to delete. * @return Nothing. */ @DELETE @Path("/{id}") public Response deleteUser(@PathParam("id") String id) { // Validate the JWT. The JWT must be in the 'users' group. We do not check // to see if the user is deleting their own profile. try { validateJWT(new HashSet<String>(Arrays.asList("users"))); } catch (JWTException jwte) { return Response.status(Status.UNAUTHORIZED) .type(MediaType.TEXT_PLAIN) .entity(jwte.getMessage()) .build(); } // Retrieve the user from the database. DB database = mongo.getMongoDB(); DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME); ObjectId dbId = new ObjectId(id); DBObject dbUser = dbCollection.findOne(dbId); // If the user did not exist, return an error. Otherwise, remove the user. if (dbUser == null) { return Response.status(Status.BAD_REQUEST).entity("The user name was not Found.").build(); } dbCollection.remove(new BasicDBObject(User.DB_ID, dbId)); return Response.ok().build(); }
/** * Retrieve a user's profile. * * @param id The ID of the user. * @return The user's profile, as a JSON object. Private fields such as password and salt are not * returned. */ @GET @Path("/{id}") @Produces("application/json") public Response getUser(@PathParam("id") String id) { // Validate the JWT. The JWT must belong to the 'users' or 'orchestrator' group. // We do not check if the user is retrieving their own profile, or someone else's. try { validateJWT(new HashSet<String>(Arrays.asList("users", "orchestrator"))); } catch (JWTException jwte) { return Response.status(Status.UNAUTHORIZED) .type(MediaType.TEXT_PLAIN) .entity(jwte.getMessage()) .build(); } // Retrieve the user from the database. DB database = mongo.getMongoDB(); DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME); DBObject user = dbCollection.findOne(new ObjectId(id)); // If the user did not exist, return an error. Otherwise, only return the public // fields (exclude things like the password). if (user == null) { return Response.status(Status.BAD_REQUEST).entity("The user not Found.").build(); } JsonObject responsePayload = new User(user).getPublicJsonObject(); return Response.ok(responsePayload, MediaType.APPLICATION_JSON).build(); }
/** * Get all user profiles. * * @return All user profiles (excluding private fields like password). */ @GET @Produces("application/json") public Response getAllUsers() { // Validate the JWT. The JWT must be in the 'users' group. try { validateJWT(new HashSet<String>(Arrays.asList("users"))); } catch (JWTException jwte) { return Response.status(Status.UNAUTHORIZED) .type(MediaType.TEXT_PLAIN) .entity(jwte.getMessage()) .build(); } // Get all the users from the database, and add them to an array. DB database = mongo.getMongoDB(); DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME); DBCursor cursor = dbCollection.find(); JsonArrayBuilder userArray = Json.createArrayBuilder(); while (cursor.hasNext()) { // Exclude all private information from the list. userArray.add((new User(cursor.next()).getPublicJsonObject())); } // Return the user list to the caller. JsonObjectBuilder responseBuilder = Json.createObjectBuilder().add("users", userArray.build()); return Response.ok(responseBuilder.build(), MediaType.APPLICATION_JSON).build(); }
/** Get a connection to Mongo */ public synchronized DB getMongoDB() { if (database == null) { try { MongoClient client = new MongoClient(mongoHostname, mongoPort); database = client.getDB("gifts-occasion"); } catch (UnknownHostException uhe) { throw new RuntimeException(uhe); } } return database; }
/** Get a connection to Mongo */ public synchronized DB getMongoDB() { if (database == null) { try { MongoClient client = new MongoClient(mongoHostname, mongoPort); database = client.getDB("gifts-group"); } catch (UnknownHostException uhe) { throw new RuntimeException(uhe); } } return database; }
@Override public void start() throws IOException { MongoClientURI clientURI = new MongoClientURI(mongoURL); client = new MongoClient(clientURI); DB db = client.getDB(clientURI.getDatabase()); collection = db.getCollection(clientURI.getCollection()); collection.setWriteConcern(WriteConcern.JOURNALED); DBObject index = new BasicDBObject(1).append(pKey, Integer.valueOf(1)); collection.createIndex(index); }