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:models.Bookmark.java
License:Open Source License
public static void delete(String dest, String uid) // -> ObjectId { Cache.delete("bookmark_" + uid); Cache.delete(key(uid, dest));/*from w w w . j a v a 2 s . c om*/ try { BasicDBObject query = new BasicDBObject().append(USERID, uid).append(DEST, dest); Logger.info(query.toString()); MongoDB.getDB().getCollection(MongoDB.CBookmark).remove(query); } catch (Exception ex) { Logger.info("Bookmark.delete"); ex.printStackTrace(); Logger.info(ex.toString()); } }
From source file:net.jimj.automaton.commands.QuoteCommand.java
License:Open Source License
protected BasicDBObject buildQuoteSearch(String arg) { //todo: replace w/ real Network concept. BasicDBObject query = new BasicDBObject(QUOTE_NETWORK, "slashnet"); if (arg != null) { //Regex search int searchStart = arg.indexOf("/"); int searchEnd = arg.lastIndexOf("/"); if (searchStart != -1 && searchStart < searchEnd) { //cut out the included / characters. String quoteSearch = arg.substring(searchStart + 1, searchEnd); if (quoteSearch.length() > 0) { query.append(QUOTE_QUOTE, Pattern.compile(quoteSearch, Pattern.CASE_INSENSITIVE)); }/*w w w . j a va 2 s. com*/ } String nick = arg; if (searchStart != -1) { nick = arg.substring(0, searchStart).trim(); } if (!StringUtils.isBlank(nick)) { query.append(QUOTE_NICK, nick); } } LOGGER.debug(query.toString()); return query; }
From source file:org.apache.whirr.service.mongodb.MongoDBReplSetMemberClusterActionHandler.java
License:Apache License
@Override protected void afterConfigure(ClusterActionEvent event) { ClusterSpec clusterSpec = event.getClusterSpec(); Cluster cluster = event.getCluster(); LOG.info("Configuring replica set members."); //Get all the instances that are marked as replica set members Set<String> replSetRoles = Sets.newHashSet(ROLE, MongoDBArbiterClusterActionHandler.ROLE); Set<Cluster.Instance> replSetInstances = cluster.getInstancesMatching(anyRoleIn(replSetRoles)); //Just grab the first of these instances, use it to send the rs.initiate() Cluster.Instance setLeader = replSetInstances.iterator().next(); try {/*from w w w . j ava 2 s . c om*/ Configuration config = getConfiguration(clusterSpec); this.arbiterPort = config.getInt(MongoDBArbiterClusterActionHandler.CFG_KEY_PORT, MongoDBArbiterClusterActionHandler.PORT); } catch (IOException e) { this.arbiterPort = MongoDBArbiterClusterActionHandler.PORT; } Mongo mongo; DB db; try { // throws IOExc, UnknownHostExc: LOG.info( "Connecting to " + setLeader.getPublicAddress().getHostAddress() + " to initiate replica set."); mongo = new Mongo(setLeader.getPublicAddress().getHostAddress(), PORT); db = mongo.getDB("admin"); if (this.authPassword != null && this.authUsername != null) { db.authenticate(this.authUsername, this.authPassword.toCharArray()); } } catch (Exception e) { LOG.error("Unable to get public host address of replica set leader, " + e.getMessage()); return; } try { BasicDBObject configObject = this.generateReplicaSetConfig(replSetInstances); // throws IOexc LOG.info("config object:" + configObject.toString()); BasicDBObject commandInfo = new BasicDBObject("replSetInitiate", configObject); LOG.info("Sending rs.initiate() command"); CommandResult initiateResult = db.command(commandInfo); LOG.info("Command Result: " + initiateResult.toString()); } catch (IOException e) { LOG.error("Unable to get private host addresses of replica set members, " + e.getMessage()); } finally { //TODO any cleanup? } }
From source file:org.breizhbeans.thrift.tools.thriftmongobridge.example.SimpleApp.java
License:Apache License
public static void main(String[] args) throws Exception { // --------------------------------------------------------------- // NON SECURED GET ALWAYS PASSWORD'S KEYSTORE FROM A SECURED PLACE // get it from a secured console String pwd = args[0];//from w w w . ja v a2s . co m // get it from a console String keyProtectedPassword = args[1]; // NON SECURED GET ALWAYS PASSWORD'S KEYSTORE FROM A SECURED PLACE // --------------------------------------------------------------- // load key from the key store final KeyStore keyStore = KeyStore.getInstance("JCEKS"); keyStore.load(new FileInputStream("./keystore/secretkey.keystore"), pwd.toCharArray()); // Extract the AES key KeyStore.PasswordProtection keyPassword = new KeyStore.PasswordProtection( keyProtectedPassword.toCharArray()); KeyStore.SecretKeyEntry aesKey = (KeyStore.SecretKeyEntry) keyStore.getEntry("aesKey", keyPassword); // AES KEY byte[] key = aesKey.getSecretKey().getEncoded(); // Secured bridge initialisation // First create the wrapper SecuredWrapper securedWrapper = new SecuredWrapper(key); // Set the fields protected securedWrapper.secureThriftFields(People.class, true, People._Fields.FIRST_NAME); securedWrapper.secureThriftFields(People.class, true, People._Fields.LAST_NAME); securedWrapper.secureThriftFields(People.class, false, People._Fields.BIRTHDAY); securedWrapper.secureThriftFields(People.class, true, People._Fields.EMAIL); // Add the wrapper TBSONUnstackedProtocol.addSecuredWrapper(securedWrapper); // setup mongo // and get the collection MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("example-thrift-mongo"); DBCollection peoples = db.getCollection("people"); // write people People people = new People(); people.setFirstName("my secret first name"); people.setLastName("my secret last name"); people.setEmail("me@me"); people.setInceptionDate(System.currentTimeMillis()); people.setBirthday("1970-01-01"); people.setLanguage("en"); // serialize it DBObject dbObject = ThriftMongoHelper.thrift2DBObject(people); System.out.println("save=" + dbObject.toString()); // write the document peoples.save(dbObject); // find document by secured field BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put(People._Fields.FIRST_NAME.getFieldName(), securedWrapper.digest64("my secret first name".getBytes())); System.out.println("query=" + searchQuery.toString()); DBCursor cursor = peoples.find(searchQuery); while (cursor.hasNext()) { // print secured people DBObject dbSecuredObject = cursor.next(); System.out.println("secured=" + dbSecuredObject); // deserialize the secured object People peopleDeserialized = (People) ThriftMongoHelper.DBObject2Thrift(dbSecuredObject, People.class); System.out.println("unwrapped=" + peopleDeserialized.toString()); } // Bye System.out.println("Thrift and mongo rocks :D"); System.out.println("Destroy the collection"); peoples.drop(); }
From source file:org.canedata.provider.mongodb.entity.MongoEntity.java
License:Apache License
/** * Finds the first document in the query and updates it. * @see com.mongodb.DBCollection#findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean, com.mongodb.DBObject, boolean, boolean) * @param expr//from w w w. j a va2s. c o m * @return */ public Fields findAndUpdate(Expression expr) { if (logger.isDebug()) logger.debug("Finding and updating entity, Database is {0}, Collection is {1} ...", getSchema(), getName()); BasicDBObject options = new BasicDBObject(); try { validateState(); final BasicDBObject fields = new BasicDBObject(); MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl(); BasicDBObject projection = new BasicDBObject(); Limiter limiter = new Limiter.Default(); BasicDBObject sorter = new BasicDBObject(); IntentParser.parse(getIntent(), expFactory, fields, projection, limiter, sorter, options); BasicDBObject query = expFactory.parse((MongoExpression) expr); if (logger.isDebug()) logger.debug( "Finding and updating entity, Database is {0}, Collection is {1}, expression is {2}, " + "Projections is {3}, Update is {4}, Sorter is {5}, Options is {6} ...", getSchema(), getName(), query.toString(), projection.toString(), fields.toString(), sorter.toString(), JSON.serialize(options)); DBObject rlt = getCollection().findAndModify(query, projection, sorter, options.getBoolean(Options.FIND_AND_REMOVE, false), fields, options.getBoolean(Options.RETURN_NEW, false), options.getBoolean(Options.UPSERT, false)); if (rlt == null || rlt.keySet().isEmpty()) return null; // alive cache if (null != getCache()) { invalidateCache(query); } return new MongoFields(this, getIntent(), (BasicDBObject) rlt).project(projection.keySet()); } catch (AnalyzeBehaviourException abe) { if (logger.isDebug()) logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage()); throw new RuntimeException(abe); } finally { if (!options.getBoolean(Options.RETAIN, false)) getIntent().reset(); } }
From source file:org.canedata.provider.mongodb.entity.MongoEntity.java
License:Apache License
public int updateRange(Expression expr) { if (logger.isDebug()) logger.debug("Updating entities, Database is {0}, Collection is {1} ...", getSchema(), getName()); try {/*from w w w . j a v a 2 s .c o m*/ validateState(); final BasicDBObject fields = new BasicDBObject(); final BasicDBObject othersFields = new BasicDBObject(); final BasicDBObject options = new BasicDBObject(); getIntent().playback(new Tracer() { public Tracer trace(Step step) throws AnalyzeBehaviourException { switch (step.step()) { case MongoStep.PUT: if (StringUtils.isBlank(step.getPurpose())) break; Object val = (step.getScalar() == null || step.getScalar().length == 0) ? null : step.getScalar()[0]; if (step.getPurpose().matches(internalCmds)) othersFields.append(step.getPurpose(), val); else fields.append(step.getPurpose(), val); break; case MongoStep.OPTION: options.append(step.getPurpose(), step.getScalar()[0]); break; default: logger.warn("Step {0} does not apply to activities create, this step will be ignored.", step.step()); } return this; } }); final MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl(); BasicDBObject query = expFactory.parse((MongoExpression) expr); if (logger.isDebug()) logger.debug("Updating entities, Database is {0}, Collection is {1}, expression is {2} ...", getSchema(), getName(), query.toString()); BasicDBObject fs = new BasicDBObject(); if (!fields.isEmpty()) fs.append("$set", fields); if (!othersFields.isEmpty()) fs.putAll(othersFields.toMap()); if (fs.isEmpty()) return 0; WriteResult wr = getCollection().update(query, fs, options.getBoolean(Options.UPSERT, false), true, getCollection().getWriteConcern()); if (!StringUtils.isBlank(wr.getError())) throw new DataAccessException(wr.getError()); // invalidate cache if (null != getCache()) { invalidateCache(query); } return wr.getN(); } catch (AnalyzeBehaviourException abe) { if (logger.isDebug()) logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage()); throw new RuntimeException(abe); } finally { getIntent().reset(); } }
From source file:org.canedata.provider.mongodb.entity.MongoEntity.java
License:Apache License
public int deleteRange(Expression expr) { if (logger.isDebug()) logger.debug("Deleting entities, Database is {0}, Collection is {1} ...", getSchema(), getName()); try {/*from w w w . java 2 s . c o m*/ validateState(); final MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl(); BasicDBObject query = expFactory.parse((MongoExpression) expr); if (logger.isDebug()) logger.debug("Deleting entities, Database is {0}, Collection is {1}, expression is {2} ...", getSchema(), getName(), query.toString()); // invalidate cache if (null != getCache()) { invalidateCache(query); } WriteResult wr = getCollection().remove(query, getCollection().getWriteConcern()); if (!StringUtils.isBlank(wr.getError())) throw new DataAccessException(wr.getError()); return wr.getN(); } catch (AnalyzeBehaviourException abe) { if (logger.isDebug()) logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage()); throw new RuntimeException(abe); } finally { getIntent().reset(); } }
From source file:org.exist.mongodb.xquery.bson.Parse.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {/* w w w. j a va 2s.c om*/ BasicDBObject data = ConversionTools.convertJSon(args[0]); if (isCalledAs(PARSE)) { return ConversionTools.convertBson(context, data); } else { return new StringValue(data.toString()); } } catch (MongoCommandException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, BSonModule.MONG0005, ex.getMessage()); } catch (JSONParseException ex) { String msg = "Invalid JSON data: " + ex.getMessage(); LOG.error(msg); throw new XPathException(this, BSonModule.MONG0004, msg); } catch (XPathException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, ex.getMessage(), ex); } catch (MongoException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, BSonModule.MONG0002, ex.getMessage()); } catch (Throwable t) { LOG.error(t.getMessage(), t); throw new XPathException(this, BSonModule.MONG0003, t.getMessage()); } }
From source file:org.gsafeproject.audit.dao.QueryBuilder.java
License:Open Source License
@Override public String toString() { BasicDBObject result = new BasicDBObject(queryParam); return result.toString(); }
From source file:org.kiaan.Main.java
public static void getBranchesWithProject() { try {/* w w w .j a v a 2s.co m*/ MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("kiaan"); DBCollection coll = db.getCollection("banks"); // BasicDBObject doc = new BasicDBObject("_id" , false).append("name", true); // BasicDBObject doc1 = new BasicDBObject("name" , ""); // BasicDBObject doc = new BasicDBObject("_id" , false).append("branches.name", true); // DBCursor cursor = coll.find(null, doc); DBObject unwind = new BasicDBObject("$unwind", "$branches"); DBObject field = new BasicDBObject("_id", false); field.put("name", "$name"); field.put("branch_id", "$branches.branch_id"); field.put("branch_name", "$branches.name"); DBObject project = new BasicDBObject("$project", field); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("name", 1)); List<DBObject> pipeline = Arrays.asList(unwind, project, sort); // AggregationOutput output = coll.aggregate(pipeline); // for (DBObject result : output.results()) { // System.out.println(result); // } AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); BasicDBObject dbo = new BasicDBObject(); BasicDBList dbl = new BasicDBList(); Cursor cursor = coll.aggregate(pipeline, aggregationOptions); while (cursor.hasNext()) { dbo = (BasicDBObject) cursor.next(); System.out.println(dbo.toString()); // dbl.add(cursor.next()); } System.out.println(dbl.toString()); // while(cursor.hasNext()) { // DBObject obj = cursor.next(); // System.out.println(obj.get("branches")); //// Double first = (Double)obj.get("id"); //// String last = (String)obj.get("name"); //// ObjectId id = (ObjectId)obj.get("_id"); //// model.addRow(new Object[] { id, first, last }); // } // tbl.setModel(model); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }