Java Code Examples for com.mongodb.DBCollection#findOne()

The following examples show how to use com.mongodb.DBCollection#findOne() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Feature.java    From XBDD with Apache License 2.0 6 votes vote down vote up
/**
 * Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id
 *
 * @param featureId String The featureId to make changes to
 * @return DBObjet Returns the the features new state if changes were made and returns null if bad JSON was sent
 */
@PUT
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response putFeature(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
		final BasicDBObject feature) {
	feature.put("calculatedStatus", StatusHelper.getFeatureStatus(feature));
	final DBCollection collection = this.mongoLegacyDb.getCollection("features");
	final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
	final DBObject report = collection.findOne(example);

	// get the differences/new edits

	// Detect if the edits caused a change
	feature.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
	feature.put("lastEditOn", new Date());
	final BasicDBList edits = updateEdits(feature, report);
	feature.put("edits", edits);

	updateTestingTips(this.mongoLegacyDb, coordinates, featureId, feature); // save testing tips / strip them out of the document.
	updateEnvironmentDetails(this.mongoLegacyDb, coordinates, feature);
	collection.save(feature);
	Feature.embedTestingTips(feature, coordinates, this.mongoLegacyDb); // rembed testing tips.
	return Response.ok(SerializerUtil.serialise(feature))
			.build();// pull back feature - will re-include tips that were extracted prior to saving
}
 
Example 2
Source File: MarcMongodbClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
public void testFindOne() throws UnknownHostException {
  MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
  DBCollection collection = client.getCollection("marc");
  BasicDBObject doc = createTestObject();
  collection.insert(doc);
  assertEquals(1, collection.count());
  DBObject myDoc = collection.findOne();
  assertEquals("MongoDB", myDoc.get("name"));
  assertEquals("database", myDoc.get("type"));
  assertEquals(1, myDoc.get("count"));
  assertEquals(BasicDBObject.class, myDoc.get("info").getClass());
  assertEquals(new BasicDBObject("x", 203).append("y", 102), myDoc.get("info"));
  assertEquals(203, ((BasicDBObject)myDoc.get("info")).get("x"));
  assertEquals(Integer.class, ((BasicDBObject)myDoc.get("info")).get("x").getClass());
  System.out.println(myDoc);
  collection.remove(new BasicDBObject("name", "MongoDB"));
}
 
Example 3
Source File: SelectVo.java    From tangyuan2 with GNU General Public License v3.0 6 votes vote down vote up
public DBObject selectOne(DBCollection collection) {
	DBObject fields = getFields();
	DBObject query = getQuery();
	DBObject orderByObject = getOrderByObject();

	// 日志
	log(fields, query, orderByObject);

	if (null == fields && null == orderByObject) {
		return collection.findOne(query);
	} else if (null != fields && null == orderByObject) {
		return collection.findOne(query, fields);
	} else {
		return collection.findOne(query, fields, orderByObject);
	}
}
 
Example 4
Source File: PrivateStorageRepository.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public PrivateStorage update(String collectionName,  Map<String, Object> content) throws JsonProcessingException {
    DBObject queryById = new BasicDBObject().append(ID, content.get(ID));

    DBCollection collectionFor = mongoPrivateStorageTemplate.getCollection(collectionName);
    DBObject dbObject = collectionFor.findOne(queryById);

    if (!Optional.ofNullable(dbObject).isPresent()) {
        return null;
    }

    content.remove("_id");
    dbObject.putAll(content);

 DBObject query = new BasicDBObject().append(ID, dbObject.get(ID));

    DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
    collection.update(query, dbObject);

    return PrivateStorage.builder()
            .collectionName(collectionName)
            .collectionContent(jsonParsingService.toJsonString(dbObject.toMap()))
            .build();
}
 
Example 5
Source File: PrivateStorageRepository.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public PrivateStorage findById(String collectionName, String id) throws JsonProcessingException {
    DBObject query = new BasicDBObject();
    query.put(ID, id);

    DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
    DBObject object = collection.findOne(query);

    if (!Optional.ofNullable(object).isPresent()) {
        return null;
    }

    return PrivateStorage.builder()
            .collectionName(collectionName)
            .collectionContent(jsonParsingService.toJsonString(object.toMap()))
            .build();
}
 
Example 6
Source File: MongoDBUtil.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Find a DBObject from database using the query. If the ‘fields' argument is null, 
 * then return the whole document. Otherwise, only returns given fields.
 * 
 * This method uses reflection to convert the result DBObject into given Object.
 * 
 * @param query The query condition
 * @param databaseName The database name
 * @param namespace The collection namespace
 * @param collection The collection name
 * @param filterFields The fields that will be returned.
 * @return
 */
public static final Object queryObjectFromMongo(DBObject query, String databaseName,
		String namespace, String collection, DBObject filterFields) {
	
	DBCollection coll = getDBCollection(databaseName, namespace, collection);
	DBObject dbObject = null;
	if ( filterFields != null ) {
		dbObject = coll.findOne(query, filterFields);
	} else {
		dbObject = coll.findOne(query);
	}
	if ( dbObject != null ) {
		return constructObject(dbObject);
	} else {
		return null;
	}
}
 
Example 7
Source File: UserResource.java    From sample-acmegifts with Eclipse Public License 1.0 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 8
Source File: Feature.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/step/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateStepWithPatch(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
		final BasicDBObject patch) {
	try {
		final DBCollection collection = this.mongoLegacyDb.getCollection("features");
		final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
		final BasicDBObject storedFeature = (BasicDBObject) collection.findOne(example);

		final int stepLine = (int) patch.get("line");
		final String status = (String) patch.get("status");
		final String scenarioId = (String) patch.get("scenarioId");

		final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
		final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);

		boolean found = false;

		if (scenarioToUpdate.get("background") != null) {
			final BasicDBObject backgroundToUpdate = (BasicDBObject) (scenarioToUpdate.get("background"));
			final BasicDBList backgroundStepsToUpdate = (BasicDBList) (backgroundToUpdate.get("steps"));
			found = updateSteps(backgroundStepsToUpdate, stepLine, status);
		}
		if (!found) {
			final BasicDBList stepsToUpdate = (BasicDBList) (scenarioToUpdate.get("steps"));
			updateSteps(stepsToUpdate, stepLine, status);
		}
		featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
		featureToUpdate.put("lastEditOn", new Date());
		featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
		collection.save(featureToUpdate);
		return Response.ok().build();
	} catch (final Throwable th) {
		th.printStackTrace();
		return Response.serverError().build();
	}
}
 
Example 9
Source File: Feature.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/comments/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateCommentWithPatch(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
		final BasicDBObject patch) {
	try {
		final DBCollection collection = this.mongoLegacyDb.getCollection("features");
		final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
		final BasicDBObject storedFeature = (BasicDBObject) collection.findOne(example);

		final String scenarioId = (String) patch.get("scenarioId");
		final String label = (String) patch.get("label");
		final String content = (String) patch.get("content");

		final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
		final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);
		scenarioToUpdate.put(label, content);

		if (label.equals("testing-tips")) {
			final DBCollection tips = this.mongoLegacyDb.getCollection("testingTips");
			updateTestingTipsForScenario(tips, scenarioToUpdate, coordinates, featureId);
		}
		featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
		featureToUpdate.put("lastEditOn", new Date());
		featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
		collection.save(featureToUpdate);
		if (label.equals("testing-tips")) {
			Feature.embedTestingTips(featureToUpdate, coordinates, this.mongoLegacyDb);
		}
		return Response.ok().build();
	} catch (final Throwable th) {
		th.printStackTrace();
		return Response.serverError().build();
	}

}
 
Example 10
Source File: MongoDBTestHelper.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/** @return The {@link DBObject} representing the object with the given id */
public static DBObject getById(AbstractMongoDBServer entity, String id) {
    LOG.info("Getting {} from {}", new Object[]{id, entity});
    MongoClient mongoClient = clientForServer(entity);
    // Secondary preferred means the driver will let us read from secondaries too.
    mongoClient.setReadPreference(ReadPreference.secondaryPreferred());
    try {
        DB db = mongoClient.getDB(TEST_DB);
        DBCollection testCollection = db.getCollection(TEST_COLLECTION);
        return testCollection.findOne(new BasicDBObject("_id", new ObjectId(id)));
    } finally {
        mongoClient.close();
    }
}
 
Example 11
Source File: Environment.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{product}")
public Response getEnvironmentsForProduct(@PathParam("product") final String product) {
	final DBCollection collection = this.mongoLegacyDb.getCollection("environments");
	final DBObject rtn = collection.findOne(new BasicDBObject("coordinates.product", product));

	return Response.ok(SerializerUtil.serialise(rtn)).build();
}
 
Example 12
Source File: Presence.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPresence(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId) {
	final DBCollection collection = this.mongoLegacyDb.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 DBObject newPresence = collection.findOne(query);
	newPresence.put("currentUser", LoggedInUserUtil.getLoggedInUser().getDisplay());
	return Response.ok(SerializerUtil.serialise(newPresence)).build();

}
 
Example 13
Source File: Favourites.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{product}")
@Produces(MediaType.APPLICATION_JSON)
public Response getFavouriteStateOfProduct(@PathParam("product") final String product) {
	final DBCollection collection = this.mongoLegacyDb.getCollection("users");

	final BasicDBObject query = new BasicDBObject("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());
	query.put("favourites." + product, true);

	final DBObject favState = collection.findOne(query);

	return Response.ok(favState != null).build();
}
 
Example 14
Source File: EntityDataController.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/api/{projectId}/entities/{name}/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
   public @ResponseBody
   String getEntityDataById(@PathVariable("projectId") String projectId, @PathVariable("name") String entityName,
    @PathVariable("id") String entityDataId,
    @RequestHeader(value = "authToken", required = false) String authToken) {

JSONObject authRes = authService.authorize(projectId,authToken,"USER");
if(!authRes.getBoolean(SUCCESS)){
    return authRes.toString(4);
}

DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_"+entityName);

BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(entityDataId));

DBObject resultObject = dbCollection.findOne(queryObject);

if(resultObject == null){
    return "Not Found";
}

if(entityName.equals("User")){
    resultObject.removeField(PASSWORD);
}

dbRefToRelation(resultObject);
String json = resultObject.toString();

// Indentation
JSONObject jsonObject = new JSONObject(json);
return jsonObject.toString(4);
   }
 
Example 15
Source File: UserResource.java    From sample-acmegifts with Eclipse Public License 1.0 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 16
Source File: DefaultChannelService.java    From hvdf with Apache License 2.0 4 votes vote down vote up
@Override
public DBObject getChannelConfiguration(String feedName, String channelName) {
	
	DBCollection configColl = getChannelConfigCollection(feedName);
	return configColl.findOne(new BasicDBObject("_id", channelName));
}
 
Example 17
Source File: Feature.java    From XBDD with Apache License 2.0 4 votes vote down vote up
/**
 * Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id
 *
 * @param featureId String 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:.+}")
@Produces(MediaType.APPLICATION_JSON)
public Response getFeatureRollup(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId) {
	final List<BasicDBObject> features = new ArrayList<>();
	final DBCollection collection = this.mongoLegacyDb.getCollection("features");
	final DBCollection summary = this.mongoLegacyDb.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<>();

	for (final String build : buildArray) {
		for (final BasicDBObject feature : features) {
			if (feature.get("build").equals(build)) {
				orderedFeatures.add(feature);
				break;
			}
		}
	}

	returns.append("rollup", orderedFeatures);

	return Response.ok(SerializerUtil.serialise(returns)).build();
}
 
Example 18
Source File: UserResource.java    From sample-acmegifts with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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 19
Source File: MongoDBUtil.java    From gameserver with Apache License 2.0 3 votes vote down vote up
/**
 * Find a DBObject from database using the query. If the ‘fields' argument is null, 
 * then return the whole document. Otherwise, only returns given fields.
 * 
 * @param query The query condition
 * @param databaseName The database name
 * @param namespace The collection namespace
 * @param collection The collection name
 * @param fields The fields that will be returned.
 * @return
 */
public static final DBObject queryFromMongo(DBObject query, String databaseName,
		String namespace, String collection, DBObject fields) {
	
	DBCollection coll = getDBCollection(databaseName, namespace, collection);
	if ( fields != null ) {
		return coll.findOne(query, fields);
	} else {
		return coll.findOne(query);
	}
}
 
Example 20
Source File: MongoUtil.java    From gameserver with Apache License 2.0 3 votes vote down vote up
/**
 * Find a DBObject from database using the query. If the ‘fields' argument is null, 
 * then return the whole document. Otherwise, only returns given fields.
 * 
 * @param query The query condition
 * @param databaseName The database name
 * @param namespace The collection namespace
 * @param collection The collection name
 * @param fields The fields that will be returned.
 * @return
 */
public static final DBObject queryFromMongo(DBObject query, String databaseName,
		String namespace, String collection, DBObject fields) {
	
	DBCollection coll = getDBCollection(databaseName, namespace, collection);
	if ( fields != null ) {
		return coll.findOne(query, fields);
	} else {
		return coll.findOne(query);
	}
}