Java Code Examples for com.mongodb.DB

The following are top voted examples for showing how to use com.mongodb.DB. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: geeCommerce-Java-Shop-Software-and-PIM   File: SynonymsGenerator.java   View source code 7 votes vote down vote up
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);
    }
}
 
Example 2
Project: spring-boot-completablefuture   File: InitialSetupMigration.java   View source code 6 votes vote down vote up
@ChangeSet(order = "01",
           author = "developer",
           id = "01-addUsers")
public void addUsers(final DB db) {
    final DBCollection userCollection = db.getCollection(User.COLLECTION_NAME);

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c3f"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "One")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c40"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "Two")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());
}
 
Example 3
Project: mongodb-broker   File: MongoAdminService.java   View source code 6 votes vote down vote up
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);
		}
	}
 
Example 4
Project: mongodb-broker   File: MongoServiceInstanceService.java   View source code 6 votes vote down vote up
@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();
}
 
Example 5
Project: sentry   File: InitialSetupMigration.java   View source code 6 votes vote down vote up
@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);
}
 
Example 6
Project: crauler_ISI   File: MongoFunctions.java   View source code 6 votes vote down vote up
/**
 * 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());
	}
}
 
Example 7
Project: biomedicus   File: MongoDbXmiWriter.java   View source code 6 votes vote down vote up
@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);
}
 
Example 8
Project: cloud-meter   File: MongoDB.java   View source code 6 votes vote down vote up
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;
    }
 
Example 9
Project: cloud-meter   File: MongoScriptRunner.java   View source code 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 10
Project: Trivial5b   File: Mongo.java   View source code 6 votes vote down vote up
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();
		}
}
 
Example 11
Project: gravity   File: MongoRepositoryFactory.java   View source code 6 votes vote down vote up
@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();	
}
 
Example 12
Project: log-dropwizard-eureka-mongo-sample   File: LogWriterApp.java   View source code 6 votes vote down vote up
@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);

}
 
Example 13
Project: XBDD   File: Favourites.java   View source code 6 votes vote down vote up
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));
}
 
Example 14
Project: Trivial_i1a   File: Connection.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 15
Project: teiid   File: TestMongoDBDirectQueryExecution.java   View source code 6 votes vote down vote up
@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());
}
 
Example 16
Project: hadoop-mini-clusters   File: MongodbLocalServerIntegrationTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 17
Project: Trivial4b   File: TrivialAPI.java   View source code 6 votes vote down vote up
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;
}
 
Example 18
Project: kurve-server   File: MongoAccountServiceTests.java   View source code 6 votes vote down vote up
@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);
}
 
Example 19
Project: peak-forecast   File: Monitor.java   View source code 6 votes vote down vote up
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());
   	   }
}
 
Example 20
Project: XBDD   File: AutomationStatistics.java   View source code 6 votes vote down vote up
@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;
}
 
Example 21
Project: XBDD   File: Feature.java   View source code 6 votes vote down vote up
@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();
		}
	}
}
 
Example 22
Project: XBDD   File: Presence.java   View source code 6 votes vote down vote up
@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;
	}
}
 
Example 23
Project: nitrite-database   File: NitriteDataGate.java   View source code 5 votes vote down vote up
@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);
}
 
Example 24
Project: elastest-instrumentation-manager   File: AgentConfigurationRepository.java   View source code 5 votes vote down vote up
public AgentConfigurationRepository(){
	MongoClient mongoClient = new MongoClient( 
			Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 
			27017);
	DB db = mongoClient.getDB("eim");
	collection = db.getCollection("agentConfiguration");
}
 
Example 25
Project: elastest-instrumentation-manager   File: AgentRepository.java   View source code 5 votes vote down vote up
public AgentRepository(){
	MongoClient mongoClient = new MongoClient( 
			Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 
			27017);
	DB db = mongoClient.getDB("eim");
	collection = db.getCollection("agent");
}
 
Example 26
Project: mycat-src-1.6.1-RELEASE   File: MongoConnection.java   View source code 5 votes vote down vote up
public DB getDB()  {
	if (this._schema!=null) {
      return this.mc.getDB(this._schema);
	}
	else {
		return null;
	}
}
 
Example 27
Project: sentry   File: InitialSetupMigration.java   View source code 5 votes vote down vote up
@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());
}
 
Example 28
Project: sentry   File: InitialSetupMigration.java   View source code 5 votes vote down vote up
@ChangeSet(order = "02", author = "initiator", id = "02-addUsers")
public void addUsers(DB db) {
    DBCollection usersCollection = db.getCollection("jhi_user");
    usersCollection.createIndex("login");
    usersCollection.createIndex("email");
    usersCollection.insert(BasicDBObjectBuilder.start()
        .add("_id", "user-0")
        .add("login", "system")
        .add("password", "*************")
        .add("first_name", "")
        .add("last_name", "System")
        .add("email", "[email protected]")
        .add("activated", "true")
        .add("lang_key", "en")
        .add("created_by", "system")
        .add("created_date", new Date())
        .add("authorities", authoritiesAdminAndUser)
        .get()
    );
    usersCollection.insert(BasicDBObjectBuilder.start()
        .add("_id", "user-1")
        .add("login", "anonymousUser")
        .add("password", "*************")
        .add("first_name", "Anonymous")
        .add("last_name", "User")
        .add("email", "[email protected]")
        .add("activated", "true")
        .add("lang_key", "en")
        .add("created_by", "system")
        .add("created_date", new Date())
        .add("authorities", new Map[]{})
        .get()
    );
}
 
Example 29
Project: sentry   File: InitialSetupMigration.java   View source code 5 votes vote down vote up
@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);
}
 
Example 30
Project: sentry   File: InitialSetupMigration.java   View source code 5 votes vote down vote up
@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());
}
 
Example 31
Project: sentry   File: InitialSetupMigration.java   View source code 5 votes vote down vote up
@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());
}
 
Example 32
Project: core-data   File: MongoDBConnectivityTest.java   View source code 5 votes vote down vote up
@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");
  }
}
 
Example 33
Project: KernelHive   File: DataManager.java   View source code 5 votes vote down vote up
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);
}
 
Example 34
Project: sample-acmegifts   File: MongoAccess.java   View source code 5 votes vote down vote up
/** 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;
}
 
Example 35
Project: sample-acmegifts   File: UserResource.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 36
Project: sample-acmegifts   File: UserResource.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 37
Project: sample-acmegifts   File: UserResource.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 38
Project: sample-acmegifts   File: MongoAccess.java   View source code 5 votes vote down vote up
/** 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;
}
 
Example 39
Project: sample-acmegifts   File: MongoAccess.java   View source code 5 votes vote down vote up
/** 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;
}
 
Example 40
Project: QDrill   File: MongoPStoreProvider.java   View source code 5 votes vote down vote up
@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);
}