List of usage examples for com.mongodb BasicDBObject toString
@SuppressWarnings("deprecation") public String toString()
Returns a JSON serialization of this object
The output will look like: {"a":1, "b":["x","y","z"]} }
From source file:com.owly.srv.RemoteServerMongoDAOImpl.java
License:Apache License
public void updateStatus(boolean status, RemoteServer remoteServer) { logger.info("MONGODB : Updating remote server status with value " + status); BasicDBObject query = new BasicDBObject("Name", remoteServer.getName()) .append("NodeIPAddress", remoteServer.getNodeIPAddress()) .append("SrvType", remoteServer.getSrvType()); logger.info("MONGODB : Updating remote server status for this query " + query.toString()); if (status) { remoteSrvCfgCollection.update(query, new BasicDBObject("$set", new BasicDBObject("ServerStatus", true))); } else {/*from w ww .j a va2 s. co m*/ remoteSrvCfgCollection.update(query, new BasicDBObject("$set", new BasicDBObject("ServerStatus", false))); } logger.info("MONGODB : Remote server status updated "); }
From source file:com.owly.srv.RemoteServerMongoDAOImpl.java
License:Apache License
public void addUniqueIndex(String Field1, String Field2) { BasicDBObject index = new BasicDBObject(Field1, 1).append(Field2, 1); BasicDBObject unique = new BasicDBObject("unique", "true"); logger.info("MONGODB :Add index for " + index.toString() + " , " + unique.toString()); remoteSrvCfgCollection.ensureIndex(index, unique); logger.info("MONGODB : Index added "); }
From source file:com.owly.srv.RemoteServerMongoDAOImpl.java
License:Apache License
public RemoteServer getRemoteServerbyName_IP(String NameSrv, String IP) { RemoteServer remoteServer = new RemoteServer(); BasicDBObject query = new BasicDBObject("NodeIPAddress", IP).append("Name", NameSrv); logger.info("MONGODB : findOne for : " + query.toString()); DBObject res = remoteSrvCfgCollection.findOne(query); remoteServer.setName((String) res.get("Name")); remoteServer.setNodeIPAddress((String) res.get("NodeIPAddress")); remoteServer.setSrvType((String) res.get("SrvType")); remoteServer.setClientPort((Integer) res.get("ClientPort")); remoteServer.setListTypeOfStats((ArrayList<String>) res.get("ListTypeOfStats")); remoteServer.setServerStatus((Boolean) res.get("ServerStatus")); remoteServer.setEnabled((Boolean) res.get("Enabled")); return remoteServer; }
From source file:com.owly.srv.RemoteServerMongoDAOImpl.java
License:Apache License
public Integer numberRemoteServer(String NameSrv, String IP) { logger.debug("Get the nubers remote servers in the database with name=" + NameSrv + " and ip=" + IP); BasicDBObject query = new BasicDBObject("NodeIPAddress", IP).append("Name", NameSrv); logger.info("MONGODB : Get number of all objects in the database"); logger.info("MONGODB : Get number of all objects in the database for this clause" + query.toString()); Integer num = remoteSrvCfgCollection.find(query).count(); logger.info("MONGODB : Number of all objects in the database obtained"); return num;//w w w. ja v a 2 s . c o m }
From source file:com.owly.srv.RemoteServerMongoDAOImpl.java
License:Apache License
public Integer numberRemoteServer(ArrayList<ShortRemoteServerId> listShortRemoteServerId) { logger.debug("Array received" + listShortRemoteServerId.toString()); BasicDBObject query = new BasicDBObject(); BasicDBList or = new BasicDBList(); Iterator<ShortRemoteServerId> iterator = listShortRemoteServerId.iterator(); while (iterator.hasNext()) { ShortRemoteServerId shortRmt = iterator.next(); BasicDBObject clause = new BasicDBObject("NodeIPAddress", shortRmt.getNodeIPAddress()).append("Name", shortRmt.getName());/* ww w . j a va 2s . c o m*/ or.add(clause); } query = new BasicDBObject("$or", or); logger.info("MONGODB : Get number of all objects in the database for this clause" + query.toString()); Integer num = remoteSrvCfgCollection.find(query).count(); logger.info("MONGODB : Number of all objects in the database obtained"); return num; }
From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java
License:Apache License
/** * Inserts or updates all objects that correspond to the given filter. Note, * however, that if the object or the passed filter is null, nothing will * happen. Note, also that the updated document is not replaced but $set is * used on the changed fields. This implies that the caller has to make sure, * the passed object has only the fields that will be updated. All other * fields should be null or empty.//from w w w. j a v a 2s . c o m * * @param object the object to update. * @param Filter the filter to apply in order to select the objects that will be * updated. */ @Override public <T extends Model> void update(T object, Filter f) { DBObject filter = this.getCachedFilter(f); String filterString = filter.toString(); // if (filter.keySet().isEmpty()) { /// LOG.warn("Cannot update an object without a filter"); // return; // } if (object == null) { LOG.warn("Cannot update a null object"); return; } DBCollection dbCollection = this.getCollection(object.getClass()); MongoModelSerializer serializer = this.getSerializer(object.getClass()); DBObject objectToUpdate = serializer.serialize(object); BasicDBObject set = new BasicDBObject("$set", objectToUpdate); String setString = set.toString(); WriteResult update = dbCollection.update(filter, set, false, true); setResult(update); }
From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java
License:Open Source License
/** * Inserts a new document with given resolution in the given aggregated collection within the given database * (row-like mode)./*from w ww . j a va 2 s . c o m*/ * @param dbName * @param collectionName * @param recvTimeTs * @param entityId * @param entityType * @param attrName * @param attrType * @param attrValue * @param resolution */ private void insertContextDataAggregatedForResoultion(String dbName, String collectionName, GregorianCalendar calendar, String entityId, String entityType, String attrName, String attrType, double attrValue, Resolution resolution) { // get database and collection MongoDatabase db = getDatabase(dbName); MongoCollection collection = db.getCollection(collectionName); // build the query BasicDBObject query = buildQueryForInsertAggregated(calendar, entityId, entityType, attrName, resolution); // prepopulate if needed BasicDBObject insert = buildInsertForPrepopulate(attrType, resolution); UpdateResult res = collection.updateOne(query, insert, new UpdateOptions().upsert(true)); if (res.getMatchedCount() == 0) { LOGGER.debug("Prepopulating data, database=" + dbName + ", collection=" + collectionName + ", query=" + query.toString() + ", insert=" + insert.toString()); } // if // do the update BasicDBObject update = buildUpdateForUpdate(attrType, attrValue); LOGGER.debug("Updating data, database=" + dbName + ", collection=" + collectionName + ", query=" + query.toString() + ", update=" + update.toString()); collection.updateOne(query, update); }
From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java
License:Open Source License
/** * Stores in per-service/database "collection_names" collection the matching between a hash and the fields used to * build it./*from w w w . ja v a 2 s .c o m*/ * FIXME: destination is under study * @param dbName * @param hash * @param isAggregated * @param fiwareService * @param fiwareServicePath * @param entityId * @param entityType * @param attrName * @param destination * @throws java.lang.Exception */ public void storeCollectionHash(String dbName, String hash, boolean isAggregated, String fiwareService, String fiwareServicePath, String entityId, String entityType, String attrName, String destination) throws Exception { // get the database and the collection; the collection is created if not existing MongoDatabase db = getDatabase(dbName); MongoCollection collection; try { LOGGER.debug("Creating Mongo collection=collection_names at database=" + dbName); db.createCollection("collection_names"); } catch (Exception e) { if (e.getMessage().contains("collection already exists")) { LOGGER.debug("Collection already exists, nothing to create"); } else { throw e; } // if else } finally { collection = db.getCollection("collection_names"); } // try catch finally // Two updates operations are needed since MongoDB currently does not support the possibility to address the // same field in a $set operation as a $setOnInsert operation. More details: // http://stackoverflow.com/questions/23992723/ \ // findandmodify-fails-with-error-cannot-update-field1-and-field1-at-the-same // build the query BasicDBObject query = new BasicDBObject().append("_id", hash + (isAggregated ? ".aggr" : "")); // do the first update BasicDBObject update = buildUpdateForCollectionHash("$setOnInsert", isAggregated, fiwareService, fiwareServicePath, entityId, entityType, attrName, destination); LOGGER.debug("Updating data, database=" + dbName + ", collection=collection_names, query=" + query.toString() + ", update=" + update.toString()); UpdateResult res = collection.updateOne(query, update, new UpdateOptions().upsert(true)); /* TECHDEBT: https://github.com/telefonicaid/fiware-cygnus/issues/428 https://github.com/telefonicaid/fiware-cygnus/issues/429 if (res.getMatchedCount() == 0) { LOGGER.error("There was an error when storing the collecion hash, database=" + dbName + ", collection=collection_names, query=" + query.toString() + ", update=" + update.toString()); return; } // if // do the second update update = buildUpdateForCollectionHash("$set", isAggregated, fiwareService, fiwareServicePath, entityId, entityType, attrName, destination); LOGGER.debug("Updating data, database=" + dbName + ", collection=collection_names, query=" + query.toString() + ", update=" + update.toString()); res = collection.updateOne(query, update); if (res.getMatchedCount() == 0) { LOGGER.error("There was an error when storing the collecion hash, database=" + dbName + ", collection=collection_names, query=" + query.toString() + ", update=" + update.toString()); } // if */ }
From source file:com.zjy.mongo.splitter.MongoCollectionSplitter.java
License:Apache License
/** * Create an instance of MongoInputSplit that represents a view of this splitter's input URI between the given lower/upper bounds. If * this splitter has range queries enabled, it will attempt to use $gt/$lte clauses in the query construct to create the split, * otherwise it will use min/max index boundaries (default behavior) * * @param lowerBound the lower bound of the collection * @param upperBound the upper bound of the collection * @return a MongoInputSplit in the given bounds * @throws SplitFailedException if the split could not be created *///w w w .j ava2 s . co m public MongoInputSplit createSplitFromBounds(final BasicDBObject lowerBound, final BasicDBObject upperBound) throws SplitFailedException { LOG.info("Created split: min=" + (lowerBound != null ? lowerBound.toString() : "null") + ", max= " + (upperBound != null ? upperBound.toString() : "null")); //Objects to contain upper/lower bounds for each split DBObject splitMin = new BasicDBObject(); DBObject splitMax = new BasicDBObject(); if (lowerBound != null) { for (Entry<String, Object> entry : lowerBound.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); if (!val.equals(MIN_KEY_TYPE)) { splitMin.put(key, val); } } } if (upperBound != null) { for (Entry<String, Object> entry : upperBound.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); if (!val.equals(MAX_KEY_TYPE)) { splitMax.put(key, val); } } } MongoInputSplit split = null; //If enabled, attempt to build the split using $gt/$lte DBObject query = MongoConfigUtil.getQuery(getConfiguration()); if (MongoConfigUtil.isRangeQueryEnabled(getConfiguration())) { try { query = MongoConfigUtil.getQuery(getConfiguration()); split = createRangeQuerySplit(lowerBound, upperBound, query); } catch (Exception e) { throw new SplitFailedException("Couldn't use range query to create split: " + e.getMessage()); } } if (split == null) { split = new MongoInputSplit(); BasicDBObject splitQuery = new BasicDBObject(); if (query != null) { splitQuery.putAll(query); } split.setQuery(splitQuery); split.setMin(splitMin); split.setMax(splitMax); } split.setInputURI(MongoConfigUtil.getInputURI(getConfiguration())); split.setAuthURI(MongoConfigUtil.getAuthURI(getConfiguration())); split.setNoTimeout(MongoConfigUtil.isNoTimeout(getConfiguration())); split.setFields(MongoConfigUtil.getFields(getConfiguration())); split.setSort(MongoConfigUtil.getSort(getConfiguration())); split.setKeyField(MongoConfigUtil.getInputKey(getConfiguration())); return split; }
From source file:DashboardServices.LoginServiceResource.java
/** * Retrieves representation of an instance of DashboardServices.LoginServiceResource * @return an instance of java.lang.String *//*w w w . j av a 2s . c o m*/ @GET @Produces(MediaType.TEXT_PLAIN) public Response getUsers(@Context UriInfo info) { String username = info.getQueryParameters().getFirst("username"); String password = info.getQueryParameters().getFirst("password"); MongoClient mongoClient; String finalOutput = "HELLO"; try { mongoClient = new MongoClient(); // Now connect to your databases DB db = mongoClient.getDB("SSKDatabase"); System.out.println("Connect to database successfully"); DBCollection coll = db.getCollection("UserCollection"); System.out.println("Collection mycol selected successfully"); BasicDBObject andQuery = new BasicDBObject(); List<BasicDBObject> obj = new ArrayList<BasicDBObject>(); obj.add(new BasicDBObject("_id", username)); obj.add(new BasicDBObject("password", password)); andQuery.put("$and", obj); System.out.println(andQuery.toString()); DBCursor cursor = coll.find(andQuery); if (cursor != null) { System.out.println("hai"); } while (cursor.hasNext()) { System.out.println("Entered Loop"); finalOutput += cursor.next(); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (finalOutput.equals("HELLO")) { System.out.println("abshah"); return Response.status(200).entity("failure").build(); } else { return Response.status(200).entity("sucess").build(); } }