Java Code Examples for com.mongodb.DB.getCollection()

The following are Jave code examples for showing how to use getCollection() of the com.mongodb.DB class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: geeCommerce-Java-Shop-Software-and-PIM   File: SynonymsGenerator.java   View Source Code Vote up 7 votes
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 Vote up 6 votes
@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: sentry   File: InitialSetupMigration.java   View Source Code Vote up 6 votes
@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 4
Project: crauler_ISI   File: MongoFunctions.java   View Source Code Vote up 6 votes
/**
 * 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 5
Project: Trivial5b   File: Mongo.java   View Source Code Vote up 6 votes
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 6
Project: XBDD   File: Presence.java   View Source Code Vote up 6 votes
@DELETE
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId}")
public DBObject deletePresence(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
		@Context final HttpServletRequest req) {
	try {
		final DB db = this.client.getDB("bdd");
		final DBCollection collection = db.getCollection("presence");
		final BasicDBObject query = new BasicDBObject("coordinates", coordinates.getObject(Field.PRODUCT, Field.VERSION, Field.BUILD).append(
				"featureId", featureId))
				.append("_id", coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates.getBuild() + "/" + featureId);
		collection.update(query, new BasicDBObject("$unset", new BasicDBObject("users." + req.getRemoteUser(), 1)), true, false);
		final DBObject newPresence = collection.findOne(query);
		newPresence.put("currentUser", req.getRemoteUser());
		return newPresence;
	} catch (final Throwable th) {
		th.printStackTrace();
		return null;
	}
}
 
Example 7
Project: tianma   File: SimpleTest.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws IOException {
	BASE64Decoder de = new BASE64Decoder();
	byte[] result = de.decodeBuffer(data);
	
	InputStream in = new ByteArrayInputStream(result);
	ZipInputStream zip = new ZipInputStream(in);
	ZipEntry entry = zip.getNextEntry();
	BufferedReader reader = new BufferedReader(new InputStreamReader(zip));
	while(reader.ready()) {
		System.out.println(reader.readLine());
	}
	
	MongoClient mongoClient = new MongoClient();
	DB db = mongoClient.getDB("mydb");
	DBCollection coll = db.getCollection("goods");
	
	BasicDBObject doc = new BasicDBObject("name", "MongoDB")
							.append("type", "database")
							.append("count", 1)
							.append("info", new BasicDBObject("x", 203).append("y", 102));
	coll.insert(doc);

	System.out.println(coll.findOne());
	
}
 
Example 8
Project: XBDD   File: Presence.java   View Source Code Vote up 6 votes
@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 9
Project: XBDD   File: TagView.java   View Source Code Vote up 6 votes
@GET
@Produces("application/json")
@Path("/featureTagIndex/{product}/{major}.{minor}.{servicePack}/{build}")
public BasicDBList getFeatureTagIndexForReport(@BeanParam final Coordinates coordinates,
		@QueryParam("searchText") final String searchText, @QueryParam("viewPassed") final Integer viewPassed,
		@QueryParam("viewFailed") final Integer viewFailed,
		@QueryParam("viewUndefined") final Integer viewUndefined, @QueryParam("viewSkipped") final Integer viewSkipped,
		@QueryParam("start") final String start) {

	final DB db = this.client.getDB("bdd");
	final DBCollection featuresCollection = db.getCollection("features");

	final BasicDBObject query = QueryBuilder.getInstance().buildFilterQuery(coordinates, searchText, viewPassed,
			viewFailed, viewUndefined, viewSkipped, start);

	query.append("$and", QueryBuilder.getInstance().buildHasTagsQuery());

	final DBCursor results = featuresCollection.find(query,
			new BasicDBObject("tags", 1).append("elements.tags", 1).append("name", 1).append("calculatedStatus", 1)
					.append("id", 1).append("elements.steps", 1).append("elements.name", 1).append("elements.id", 1));

	return getTagList(results);
}
 
Example 10
Project: XBDD   File: Presence.java   View Source Code Vote up 6 votes
@POST
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId}")
public DBObject addPresence(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
		@Context final HttpServletRequest req) {
	try {
		final DB db = this.client.getDB("bdd");
		final DBCollection collection = db.getCollection("presence");
		final BasicDBObject query = new BasicDBObject("coordinates", coordinates.getObject(Field.PRODUCT, Field.VERSION, Field.BUILD).append(
				"featureId", featureId))
				.append("_id", coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates.getBuild() + "/" + featureId);
		final Date now = Calendar.getInstance().getTime();
		collection.update(query,
				new BasicDBObject("$set", new BasicDBObject("users." + req.getRemoteUser(), now).append("lastUpdated", now)), true,
				false);
		final DBObject newPresence = collection.findOne(query);
		newPresence.put("currentUser", req.getRemoteUser());
		return newPresence;
	} catch (final Throwable th) {
		th.printStackTrace();
		return null;
	}
}
 
Example 11
Project: elastest-instrumentation-manager   File: AgentConfigurationRepository.java   View Source Code Vote up 5 votes
public AgentConfigurationRepository(){
	MongoClient mongoClient = new MongoClient( 
			Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 
			27017);
	DB db = mongoClient.getDB("eim");
	collection = db.getCollection("agentConfiguration");
}
 
Example 12
Project: elastest-instrumentation-manager   File: AgentRepository.java   View Source Code Vote up 5 votes
public AgentRepository(){
	MongoClient mongoClient = new MongoClient( 
			Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 
			27017);
	DB db = mongoClient.getDB("eim");
	collection = db.getCollection("agent");
}
 
Example 13
Project: sentry   File: InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 14
Project: sentry   File: InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 15
Project: sentry   File: InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 16
Project: sentry   File: InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 17
Project: sentry   File: InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 18
Project: core-data   File: MongoDBConnectivityTest.java   View Source Code Vote up 5 votes
@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 19
Project: sample-acmegifts   File: UserResource.java   View Source Code Vote up 5 votes
/**
 * 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 20
Project: sample-acmegifts   File: UserResource.java   View Source Code Vote up 5 votes
/**
 * 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 21
Project: sample-acmegifts   File: UserResource.java   View Source Code Vote up 5 votes
/**
 * 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 22
Project: QDrill   File: MongoPStoreProvider.java   View Source Code Vote up 5 votes
@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);
}
 
Example 23
Project: STEM   File: MongoDBDataSource.java   View Source Code Vote up 5 votes
public RecordIterator getRecords() {
  verifyProperty(dbname, "database");
  verifyProperty(collectionName, "collection");
  
  try {
    final MongoClient mongo;
    final DB database;
    final DBCollection collection;
    final DBCursor result;
    
    final DBObject queryDocument;
    final DBObject projectionDocument;
    
 // authentication mecanism via MONGODB-CR authentication http://docs.mongodb.org/manual/core/authentication/#authentication-mongodb-cr
    if(auth.equals(AUTH_ON_DB)){
      verifyProperty(username, "user-name");
      verifyProperty(password, "password");
      
      mongo = new MongoClient(
        new ServerAddress(mongouri, port), 
        Arrays.asList(MongoCredential.createMongoCRCredential(username, dbname, password.toCharArray()))
      );
    }
    else if(auth.equals(AUTH_ON_ADMIN)){
      verifyProperty(username, "user-name");
      verifyProperty(password, "password");
      
		mongo = new MongoClient(
        new ServerAddress(mongouri, port), 
        Arrays.asList(MongoCredential.createMongoCRCredential(username, AUTH_ON_ADMIN, password.toCharArray()))
      );
    }
    else{
      mongo = new MongoClient(new ServerAddress(mongouri, port));
    }
    
    // get db, collection
    database = mongo.getDB(dbname);
    collection = database.getCollection(collectionName);
    
    // execute query
    queryDocument = (DBObject)JSON.parse(query);
    if(projection==null){
      result = collection.find(queryDocument);
    }
    else{
        projectionDocument = (DBObject)JSON.parse(projection);
        result = collection.find(queryDocument, projectionDocument);
    }
    
    // See: http://api.mongodb.org/java/current/com/mongodb/DBCursor.html#addOption(int)
    // and http://api.mongodb.org/java/current/com/mongodb/Bytes.html#QUERYOPTION_NOTIMEOUT
    if(noTimeOut){
      result.addOption(Bytes.QUERYOPTION_NOTIMEOUT);
    }
 
    return new MongoDBIterator(result, mongo);
  
  } catch (UnknownHostException e) {
    throw new RuntimeException(e);
  } catch (Exception ex){
 throw new DukeException(ex);
  }
}
 
Example 24
Project: PhET   File: MongoLog.java   View Source Code Vote up 5 votes
public MongoLog( String sessionID, String dbName ) throws UnknownHostException {
    mongo = new Mongo( HOST_IP_ADDRESS, PORT );

    // All sessions are stored in the same DB.  Having a separate DB for
    // each uses an excessive amount of disk space.
    DB database = mongo.getDB( dbName );

    // Authenticate.
    try {
        boolean auth = database.authenticate( "phetsimclient", ( MER + SimSharingManager.MONGO_PASSWORD + "" + ( 2 * 2 * 2 ) + "ss0O88723otbubaoue" ).toCharArray() );
        if ( !auth ) {
            new RuntimeException( "Authentication failed" ).printStackTrace();
        }
    }

    //A MongoException.Network indicates a failure to reach mongo for the authentication attempt, and hence there is probably no internet connection.  See #3304
    catch ( MongoException.Network exception ) {
        LOGGER.warning( "Failed to connect to mongo during authentication.  Perhaps there is no internet connection." );
    }

    //One collection per session, lets us easily iterate and add messages per session.
    collection = database.getCollection( sessionID );

    /*
     * Mongo logs entire stack traces when failure occur, which is incredibly annoying.
     * Turn off Mongo logging here by interrogating the LogManager.
     * Do this at the end of the constructor, so that Mongo loggers have been instantiated.
     */
    LOGGER.info( "turning off MongoDB loggers" );
    Enumeration<String> names = LogManager.getLogManager().getLoggerNames();
    while ( names.hasMoreElements() ) {
        String name = names.nextElement();
        if ( name.startsWith( "com.mongodb" ) ) {
            LogManager.getLogManager().getLogger( name ).setLevel( Level.OFF );
        }
    }
}
 
Example 25
Project: cqrs-sample   File: ShoppingCartQueryManager.java   View Source Code Vote up 5 votes
private void init(){
	// For Annotation
	ApplicationContext ctx = 
             new AnnotationConfigApplicationContext(MongoConfiguration.class);
	db = (DB) ctx.getBean("mongoDb");

	coll = db.getCollection("plants");
}
 
Example 26
Project: sentry   File: InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 27
Project: jhipster-rethinkdb-app   File: InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 Vote up 5 votes
@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 29
Project: xxl-incubator   File: MongoDBUtil.java   View Source Code Vote up 5 votes
/**
 * 获取DBCollection对象 = 表
 * 
 * @param collName
 * @return
 */
public static DBCollection getCollection(String dbName, String collName) {
	DB db = getDB(dbName);
	if (db != null) {
		DBCollection collection = db.getCollection(collName);
		return collection;
	}
    return null;
}
 
Example 30
Project: readthisstuff.com   File: InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 31
Project: Thesis-JHipster   File: _InitialSetupMigration.java   View Source Code Vote up 5 votes
@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 32
Project: Thesis-JHipster   File: _InitialSetupMigration.java   View Source Code Vote up 5 votes
@ChangeSet(author = "initiator", id = "03-addSocialUserConnection", order = "03")
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 33
Project: geeCommerce-Java-Shop-Software-and-PIM   File: MongoHelper.java   View Source Code Vote up 5 votes
public static void removeFromArrayFiled(DB db, String collectionName, DBObject query, String field, Object value) {
    DBCollection col = db.getCollection(collectionName);
    DBObject fieldClause = new BasicDBObject();
    fieldClause.put(field, value);
    DBObject pullClause = new BasicDBObject();
    pullClause.put("$pull", fieldClause);
    col.update(query, pullClause, false, true);
}
 
Example 34
Project: Trivial4b   File: TrivialAPI.java   View Source Code Vote up 5 votes
private static DBCursor ejecutarConsulta(BasicDBObject consulta,
		String coleccion) {
	DB db = conectar();
	DBCollection colPreguntas = db.getCollection(coleccion);

	DBCursor cursor = null;
	if (consulta != null)
		cursor = colPreguntas.find(consulta);
	else
		cursor = colPreguntas.find();

	return cursor;
}
 
Example 35
Project: XBDD   File: Stats.java   View Source Code Vote up 5 votes
@GET
@Path("/build/{product}/{major}.{minor}.{servicePack}/{build}")
@Produces("application/json")
public BasicDBObject getBuildStats(@BeanParam final Coordinates coordinates) {

	final DB db = this.client.getDB("bdd");
	final DBCollection collection = db.getCollection("features");
	final String manualTag = "undefined";

	final BasicDBObject query = coordinates.getQueryObject();
	final BasicDBList manual = new BasicDBList();
	manual.add(new BasicDBObject("originalAutomatedStatus", manualTag));
	manual.add(new BasicDBObject("calculatedStatus", manualTag));
	query.put("$or", manual);

	final DBObject m = getNumberOfAllStates(collection, query);

	query.remove("$or");
	query.put("$nor", manual);

	final DBObject a = getNumberOfAllStates(collection, query);

	final BasicDBObject ret = new BasicDBObject();
	ret.put("automated", a);
	ret.put("manual", m);
	return ret;
}
 
Example 36
Project: Kvantum   File: MongoAccountManager.java   View Source Code Vote up 5 votes
@Override
public void setup() throws Exception
{
    DB database = applicationStructure.getMongoClient().getDB( CoreConfig.MongoDB.dbMorphia );
    this.counters = database.getCollection( "counters" );
    if ( !this.counters.find( new BasicDBObject( "_id", "userId" ) ).hasNext() )
    {
        this.counters.insert( new BasicDBObject( "_id", "userId" ).append( "seq", 0 ) );
    }

    this.checkAdmin();
}
 
Example 37
Project: Trivial_i1a   File: Connection.java   View Source Code Vote up 5 votes
public static void connection(String contentToTransform) {
try {
Mongo conn = new Mongo();

DB db = conn.getDB("Questions");
	
DBCollection coll = db.getCollection("Questions");

BasicDBObject query = new BasicDBObject();

query.put("question", 1);

coll.createIndex(query, "question", true);

DBCursor cursor = coll.find(query);

BasicDBList list= (BasicDBList) JSON.parse(contentToTransform);

for(Object obj:list){
	coll.insert((DBObject)obj);
}

while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} catch (MongoException  e) {
e.printStackTrace();
}
}
 
Example 38
Project: XBDD   File: Favourites.java   View Source Code Vote up 5 votes
@GET
@Path("/{product}")
@Produces("application/json")
public boolean getFavouriteStateOfProduct(@PathParam("product") final String product,
		@Context final HttpServletRequest req) {
	final DB db = this.client.getDB("bdd");
	final DBCollection collection = db.getCollection("users");
	
	final BasicDBObject query = new BasicDBObject("user_id", req.getRemoteUser());
	query.put("favourites."+product, true);
	
	final DBObject favState = collection.findOne(query);
	
	return (favState != null);
}
 
Example 39
Project: XBDD   File: QueryBuilderTagQueryTest.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
@Test
public void testTagQuery() {
	final DB db = this.mongo.getDB(this.dbName);
	final DBCollection col = db.getCollection(this.collection);

	final BasicDBObject query = new BasicDBObject();
	final List<DBObject> tagQuery = QueryBuilder.getInstance().buildHasTagsQuery();
	query.append("$and", tagQuery);

	final DBCursor cursor = col.find(query);

	Assert.assertThat(cursor.count(), equalTo(3));

	while (cursor.hasNext()) {
		final DBObject next = cursor.next();
		List<DBObject> elements;

		boolean tags = next.containsField("tags");

		if (next.containsField("elements")) {
			elements = (List<DBObject>) next.get("elements");
			for (final DBObject element : elements) {
				if (element.containsField("tags")) {
					tags = true;
				}
			}
		}

		Assert.assertTrue(tags);
	}
}
 
Example 40
Project: XBDD   File: Search.java   View Source Code Vote up 5 votes
@GET
@Path("/{product}/{major}.{minor}.{servicePack}/{build}")
@Produces("application/json")
public BasicDBList getSearchResults(@BeanParam final Coordinates coordinates, @QueryParam("keywords") final String keyword) {
	final String[] searchCategories = { "name", "description", "tags.name", "elements.name", "elements.description",
			"elements.steps.name", "elements.tags.name" };
	final List<String> searchWords = Arrays.asList(keyword.split("\\s+"));
	final DB db = this.client.getDB("bdd");
	final DBCollection collection = db.getCollection("features");
	final List<DBObject> searchResults = new ArrayList<DBObject>();

	final QueryBuilder queryBuilder = QueryBuilder.getInstance();
	final DBCursor results = collection.find(queryBuilder.getSearchQuery(searchWords, coordinates, searchCategories));

	while (results.hasNext()) {
		final DBObject doc = results.next();
		searchResults.add(doc);
	}

	Collections.sort(searchResults, new DBObjectComparator(searchWords));

	while (searchResults.size() > SEARCH_LIMIT) {
		searchResults.remove(searchResults.size() - 1);
	}

	final BasicDBList basicDBList = new BasicDBList();
	basicDBList.addAll(searchResults);
	return basicDBList;
}
 
Example 41
Project: XBDD   File: Report.java   View Source Code Vote up 5 votes
@GET
@Produces("application/json")
@Path("/featureIndex/{product}/{major}.{minor}.{servicePack}/{build}")
public DBObject getFeatureIndexForReport(@BeanParam final Coordinates coordinates,
		@QueryParam("searchText") final String searchText, @QueryParam("viewPassed") final Integer viewPassed,
		@QueryParam("viewFailed") final Integer viewFailed,
		@QueryParam("viewUndefined") final Integer viewUndefined, @QueryParam("viewSkipped") final Integer viewSkipped,
		@QueryParam("start") final String start) {

	final BasicDBObject example = QueryBuilder.getInstance().buildFilterQuery(coordinates, searchText, viewPassed,
			viewFailed, viewUndefined, viewSkipped, start);
	final DB db = this.client.getDB("bdd");
	final DBCollection featuresCollection = db.getCollection("features");
	final DBCursor features = featuresCollection.find(example,
			new BasicDBObject("id", 1).append("name", 1).append("calculatedStatus", 1)
					.append("originalAutomatedStatus", 1).append("tags", 1).append("uri", 1))
			.sort(Coordinates.getFeatureSortingObject());
	final BasicDBList featureIndex = new BasicDBList();
	try {
		for (final Object o : features) {
			featureIndex.add(o);
		}
	} finally {
		features.close();
	}
	return featureIndex;
}
 
Example 42
Project: XBDD   File: AdminUtils.java   View Source Code Vote up 5 votes
@DELETE
@Path("/delete/{product}")
@Produces("application/json")
public Response softDeleteEntireProduct(@PathParam("product") final String product,
		@Context final HttpServletRequest req,
		@Context final HttpServletResponse response) throws IOException {
	
	final DB db = this.client.getDB("bdd");
	final DBCollection collection = db.getCollection("summary");
	final DBCollection targetCollection = db.getCollection("deletedSummary");
	
	final BasicDBObject query = new BasicDBObject("coordinates.product",product);
	
	final DBCursor cursor = collection.find(query);
	DBObject doc;
	
	while(cursor.hasNext()) {
		doc = cursor.next();
		//kill the old id
		doc.removeField("_id");
		try {
			targetCollection.insert(doc);
		} catch (Throwable e) {
			return Response.status(500).build();
		}
	}
	
	collection.remove(query);
	
	return Response.ok().build();
}
 
Example 43
Project: XBDD   File: AutomationStatistics.java   View Source Code Vote up 5 votes
/**
 * Go through the prior versions of this product; for each version, find the latest build and contribute the stats for that to the
 * returned list.
 *
 * @param coordinates
 * @param limit
 * @return A list of report stats in reverse version order.
 * @throws UnknownHostException
 */
@GET
@Path("/recent-versions/{product}")
public DBObject getRecentVersionStatsForProduct(@BeanParam final Coordinates coordinates, @QueryParam("limit") final Integer limit) {
	final BasicDBList returns = new BasicDBList();

	final DB db = this.client.getDB("bdd");
	final DBCollection summaryCollection = db.getCollection("summary");
	final DBCollection reportStatsCollection = db.getCollection("reportStats");
	final DBCursor versions = summaryCollection.find(coordinates.getQueryObject(Field.PRODUCT)).sort(Coordinates.getFeatureSortingObject());
	if (limit != null) {
		versions.limit(limit);
	}
	try {
		while (versions.hasNext()) { // go through each summary document
			final DBObject version = versions.next(); // each represents the coordinates for a given version
			final Coordinates c = new Coordinates((DBObject) version.get("coordinates"));
			final BasicDBList builds = (BasicDBList) version.get("builds");
			c.setBuild((String) builds.get(builds.size() - 1)); // we need to specify which build (the latest is last in the list)
			final DBObject query = c.getQueryObject();
			returns.add(reportStatsCollection.findOne(query));
		}
	} finally {
		versions.close();
	}

	return returns;
}
 
Example 44
Project: sample-acmegifts   File: UserResource.java   View Source Code Vote up 4 votes
/**
 * Update an existing user.
 *
 * @param id The ID of the user to update.
 * @param payload The fields of the user that should be updated.
 * @return Nothing.
 */
@PUT
@Path("/{id}")
@Consumes("application/json")
public Response updateUser(@PathParam("id") String id, JsonObject payload) {

  // Validate the JWT. The JWT should be in the 'users' group. We do not
  // check to see if the user is modifying 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);
  DBObject oldDbUser = dbCollection.findOne(new ObjectId(id));

  if (oldDbUser == null) {
    return Response.status(Status.BAD_REQUEST).entity("The user was not Found.").build();
  }

  // If the input object contains a new password, need to hash it for use in the database.
  User newUser = null;
  if (payload.containsKey("password")) {
    try {
      String rawPassword = payload.getString("password");
      String saltString = (String) (oldDbUser.get(User.JSON_KEY_USER_PASSWORD_SALT));
      PasswordUtility pwUtil = new PasswordUtility(rawPassword, saltString);
      JsonObject newJson =
          createJsonBuilder(payload)
              .add(User.JSON_KEY_USER_PASSWORD_HASH, pwUtil.getHashedPassword())
              .add(User.JSON_KEY_USER_PASSWORD_SALT, pwUtil.getSalt())
              .build();
      newUser = new User(newJson);
    } catch (Throwable t) {
      return Response.serverError().entity("Error updating password").build();
    }
  } else {
    newUser = new User(payload);
  }

  // Create the updated user object.  Only apply the fields that we want the
  // client to change (skip the internal fields).
  DBObject updateObject = new BasicDBObject("$set", newUser.getDBObjectForModify());
  dbCollection.findAndModify(oldDbUser, updateObject);

  return Response.ok().build();
}
 
Example 45
Project: sample-acmegifts   File: OccasionResource.java   View Source Code Vote up 4 votes
private DBCollection getCollection() {
  DB occasions = mongo.getMongoDB();
  return occasions.getCollection("occasions");
}
 
Example 46
Project: sample-acmegifts   File: GroupResource.java   View Source Code Vote up 4 votes
public DBCollection getGroupCollection() {
  DB groupsDB = mongo.getMongoDB();
  return groupsDB.getCollection(Group.DB_COLLECTION_NAME);
}
 
Example 47
Project: JerseyRestBoilerplate   File: MongoUtil.java   View Source Code Vote up 4 votes
public static DBCollection getCollection(String dbname,
		String collectionName) {
	DB database = getDatabase(dbname);
	DBCollection collection = database.getCollection(collectionName);
	return collection;
}
 
Example 48
Project: jhipster-rethinkdb-app   File: InitialSetupMigration.java   View Source Code Vote up 4 votes
@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", "$2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG")
        .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", "$2a$10$j8S5d7Sr7.8VTOYNviDPOeWX8KcYILUVJBsYV83Y5NtECayypx9lO")
        .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()
    );
    usersCollection.insert(BasicDBObjectBuilder.start()
        .add("_id", "user-2")
        .add("login", "admin")
        .add("password", "$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC")
        .add("first_name", "admin")
        .add("last_name", "Administrator")
        .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-3")
        .add("login", "user")
        .add("password", "$2a$10$VEjxo0jq2YG9Rbk2HmX9S.k1uZBGYUHdUcid3g/vfiEl7lwWgOH/K")
        .add("first_name", "")
        .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", authoritiesUser)
        .get()
    );
}
 
Example 49
Project: readthisstuff.com   File: InitialSetupMigration.java   View Source Code Vote up 4 votes
@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", "$2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG")
        .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", "$2a$10$j8S5d7Sr7.8VTOYNviDPOeWX8KcYILUVJBsYV83Y5NtECayypx9lO")
        .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()
    );
    usersCollection.insert(BasicDBObjectBuilder.start()
        .add("_id", "user-2")
        .add("login", "admin")
        .add("password", "$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC")
        .add("first_name", "admin")
        .add("last_name", "Administrator")
        .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-3")
        .add("login", "user")
        .add("password", "$2a$10$VEjxo0jq2YG9Rbk2HmX9S.k1uZBGYUHdUcid3g/vfiEl7lwWgOH/K")
        .add("first_name", "")
        .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", authoritiesUser)
        .get()
    );
}
 
Example 50
Project: Thesis-JHipster   File: InitialSetupMigration.java   View Source Code Vote up 4 votes
@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", "$2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG")
        .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", "$2a$10$j8S5d7Sr7.8VTOYNviDPOeWX8KcYILUVJBsYV83Y5NtECayypx9lO")
        .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()
    );
    usersCollection.insert(BasicDBObjectBuilder.start()
        .add("_id", "user-2")
        .add("login", "admin")
        .add("password", "$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC")
        .add("first_name", "admin")
        .add("last_name", "Administrator")
        .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-3")
        .add("login", "user")
        .add("password", "$2a$10$VEjxo0jq2YG9Rbk2HmX9S.k1uZBGYUHdUcid3g/vfiEl7lwWgOH/K")
        .add("first_name", "")
        .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", authoritiesUser)
        .get()
    );
}
 
Example 51
Project: XBDD   File: Feature.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
/**
 * Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id
 *
 * @param String featureId The featureId to get the history for
 * @return DBObjet Returns the past feature status for the given featureId
 */
@GET
@Path("/rollup/{product}/{major}.{minor}.{servicePack}/{featureId:.+}")
public DBObject getFeatureRollup(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId) {
	final List<BasicDBObject> features = new ArrayList<BasicDBObject>();
	final DB db = this.client.getDB("bdd");
	final DBCollection collection = db.getCollection("features");
	final DBCollection summary = db.getCollection("summary");
	final BasicDBObject example = coordinates.getRollupQueryObject(featureId);
	final DBCursor cursor = collection.find(example,
			new BasicDBObject("id", 1).append("coordinates.build", 1).append("calculatedStatus", 1)
					.append("originalAutomatedStatus", 1).append("statusLastEditedBy", 1));
	try {
		while (cursor.hasNext()) {
			final DBObject doc = cursor.next();
			final BasicDBObject rollup = new BasicDBObject()
					.append("build", ((DBObject) doc.get("coordinates")).get("build"))
					.append("calculatedStatus", doc.get("calculatedStatus"))
					.append("originalAutomatedStatus", doc.get("originalAutomatedStatus"))
					.append("statusLastEditedBy", doc.get("statusLastEditedBy"));
			features.add(rollup);
		}
	} finally {
		cursor.close();
	}
	final BasicDBObject returns = new BasicDBObject()
			.append("coordinates", coordinates.getRollupCoordinates().append("featureId", featureId).append("version", coordinates.getVersionString()));
	
	final DBObject buildOrder = summary.findOne(coordinates.getQueryObject());
	final List<String> buildArray = (List<String>) buildOrder.get("builds");
	final List<BasicDBObject> orderedFeatures = new ArrayList<BasicDBObject>();
	
	for (String build : buildArray) {
		for (BasicDBObject feature : features) {
			if (feature.get("build").equals(build)) {
				orderedFeatures.add(feature);
				break;
			}
		}
	}
	
	returns.append("rollup", orderedFeatures);
	
	return returns;
}
 
Example 52
Project: mongodm   File: MDB.java   View Source Code Vote up 4 votes
public MDB(DB database) {
	this.mapper = new Mapper();
	this.database = database;
	_cmd = database.getCollection("$cmd");
	_cmd.setDBDecoderFactory(MDecoder.FACTORY);
}
 
Example 53
Project: storm-topology-examples   File: KafkaMongodbTopologyTest.java   View Source Code Vote up 4 votes
public DBCollection getMongoCollection(DB mongoDatabase, String mongoCollection) {
    return mongoDatabase.getCollection(mongoCollection);
}
 
Example 54
Project: xDrip   File: MongoWrapper.java   View Source Code Vote up 3 votes
public DBCollection openMongoDb() throws UnknownHostException {

    	MongoClientURI dbUri = new MongoClientURI(dbUriStr_+"?socketTimeoutMS=180000");
	    mongoClient_ = new MongoClient(dbUri);

	    DB db = mongoClient_.getDB( dbName_ );
	    DBCollection coll = db.getCollection(collection_);
	    coll.createIndex(new BasicDBObject(index_, 1));  // create index on "i", ascending

	    return coll;

    }
 
Example 55
Project: xDrip-plus   File: MongoWrapper.java   View Source Code Vote up 3 votes
public DBCollection openMongoDb() throws UnknownHostException {

    	MongoClientURI dbUri = new MongoClientURI(dbUriStr_+"?socketTimeoutMS=180000");
	    mongoClient_ = new MongoClient(dbUri);

	    DB db = mongoClient_.getDB( dbName_ );
	    DBCollection coll = db.getCollection(collection_);
	    coll.createIndex(new BasicDBObject(index_, 1));  // create index on "i", ascending

	    return coll;

    }
 
Example 56
Project: datacafe   File: MongoCollection.java   View Source Code Vote up 2 votes
/**
 * Gets the Mongo Collection
 *
 * @return the DBCollection object.
 */
public DBCollection getCollection() {
    DB db = mongoClient.getDB(database);
    return db.getCollection(collection);
}