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

The following examples show how to use com.mongodb.DBCollection#findAndModify() . 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: Recents.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/feature/{product}/{major}.{minor}.{servicePack}/{build}/{id:.+}")
@Produces(MediaType.APPLICATION_JSON)
public Response addFeatureToRecents(@QueryParam("name") final String featureName,
		@BeanParam final Coordinates coordinates,
		@PathParam("id") final String featureID) {

	final BasicDBObject featureDetails = new BasicDBObject("name", featureName);
	featureDetails.put("product", coordinates.getProduct());
	featureDetails.put("version", coordinates.getVersionString());
	featureDetails.put("build", coordinates.getBuild());
	featureDetails.put("id", featureID);

	final DBCollection collection = this.mongoLegacyDb.getCollection("users");

	final BasicDBObject user = new BasicDBObject();
	user.put("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());

	final DBObject blank = new BasicDBObject();
	final DBObject doc = collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true, true);

	if (doc.containsField("recentFeatures")) {
		final BasicDBList featureArray = (BasicDBList) doc.get("recentFeatures");
		if (featureArray.contains(featureDetails)) {
			featureArray.remove(featureDetails);
			featureArray.add(featureDetails);
			collection.update(user, new BasicDBObject("$set", new BasicDBObject("recentFeatures", featureArray)));
		} else {
			if (featureArray.size() >= 5) {
				collection.update(user, new BasicDBObject("$pop", new BasicDBObject("recentFeatures", "-1")));
			}
			collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentFeatures", featureDetails)));
		}
	} else {
		collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentFeatures", featureDetails)));
	}

	return Response.ok().build();
}
 
Example 2
Source File: Recents.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/build/{product}/{major}.{minor}.{servicePack}/{build}")
@Produces(MediaType.APPLICATION_JSON)
public Response addBuildToRecents(@BeanParam final Coordinates coordinates) {

	final DBObject buildCoords = coordinates.getReportCoordinates();

	final DBCollection collection = this.mongoLegacyDb.getCollection("users");

	final BasicDBObject user = new BasicDBObject();
	user.put("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());

	final DBObject blank = new BasicDBObject();
	final DBObject doc = collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true, true);

	if (doc.containsField("recentBuilds")) {
		final BasicDBList buildArray = (BasicDBList) doc.get("recentBuilds");
		if (buildArray.contains(buildCoords)) {
			// BasicDBObject toMove = (BasicDBObject) featureArray.get(featureArray.indexOf(featureDetails));
			buildArray.remove(buildCoords);
			buildArray.add(buildCoords);
			collection.update(user, new BasicDBObject("$set", new BasicDBObject("recentBuilds", buildArray)));
		} else {
			if (buildArray.size() >= 5) {
				collection.update(user, new BasicDBObject("$pop", new BasicDBObject("recentBuilds", "-1")));
			}
			collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentBuilds", buildCoords)));
		}
	} else {
		collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentBuilds", buildCoords)));
	}

	return Response.ok().build();
}
 
Example 3
Source File: Favourites.java    From XBDD with Apache License 2.0 5 votes vote down vote up
public void setFavouriteStateOfProduct(final String product, final boolean state) {

		final DBCollection collection = this.mongoLegacyDb.getCollection("users");

		final BasicDBObject user = new BasicDBObject();
		user.put("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());

		final DBObject blank = new BasicDBObject();
		collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true, true);

		// User exists
		final DBObject favourites = new BasicDBObject("favourites." + product, state);
		final DBObject update = new BasicDBObject("$set", favourites);
		collection.update(user, update);
	}
 
Example 4
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();
}