@Override public void store(StoreRequest request, StreamObserver<StoreResponse> responseObserver) { try { responseObserver.onNext(indexManger.storeDocument(request)); responseObserver.onCompleted(); } catch (Exception e) { log.error("Failed to store: <" + request.getUniqueId() + "> in index <" + request.getIndexName() + ">: " + e.getClass().getSimpleName() + ": ", e); Metadata m = new Metadata(); m.put(MetaKeys.ERROR_KEY, e.getMessage()); responseObserver.onError(new StatusRuntimeException(Status.UNKNOWN, m)); if (request.hasResultDocument()) { try { if (request.getResultDocument().hasDocument()) { BasicBSONObject document = (BasicBSONObject) BSON.decode(request.getResultDocument().getDocument().toByteArray()); log.error(document.toString()); } } catch (Exception e2) { } } } }
public static BasicDBList toDBList(MultiNameValues multiNameValues) { String[] names = multiNameValues.getNames(); BasicDBList basicDBList = new BasicDBList(); for (int i = 0; i < multiNameValues.count(); i++) { Object[] values = multiNameValues.values(i); BasicBSONObject bsonObject = new BasicBSONObject(values.length); for (int j = 0; j < names.length; j++) { bsonObject.append(names[j], values[j]); } basicDBList.add(bsonObject); } return basicDBList; }
private int InsertData(SQLInsertStatement state) { if (state.getValues().getValues().size() ==0 ){ throw new RuntimeException("number of columns error"); } if (state.getValues().getValues().size() != state.getColumns().size()){ throw new RuntimeException("number of values and columns have to match"); } SQLTableSource table=state.getTableSource(); BSONObject o = new BasicBSONObject(); int i=0; for(SQLExpr col : state.getColumns()) { o.put(getFieldName2(col), getExpValue(state.getValues().getValues().get(i))); i++; } DBCollection coll =this._db.getCollection(table.toString()); //coll.insert(new DBObject[] { o }); coll.insert(o); return 1; }
private int UpData(SQLUpdateStatement state) { SQLTableSource table=state.getTableSource(); DBCollection coll =this._db.getCollection(table.toString()); SQLExpr expr=state.getWhere(); BSONObject query = parserWhere(expr); BasicBSONObject set = new BasicBSONObject(); for(SQLUpdateSetItem col : state.getItems()){ set.put(getFieldName2(col.getColumn()), getExpValue(col.getValue())); } BSONObject mod = new BasicBSONObject("$set", set); //coll.updateMulti(query, mod); coll.update(query, mod, null); //System.out.println("changs count:"+coll.getStats().size()); return 1; }
private void parserDBObject(BasicBSONObject ob,String akey, String aop,Object aval){ boolean isok=false; if (!(ob.keySet().isEmpty())) { for (String field : ob.keySet()) { if (akey.equals(field)){ Object val = ob.get(field); if (val instanceof BasicBSONObject) { ((BasicBSONObject) val).put(aop, aval); ob.put(field, (BasicBSONObject) val); isok=true; break; } else if (val instanceof BasicBSONList) { // newobj.put(field, ((BasicDBList)val).copy()); } } } } if (isok==false) { BasicBSONObject xo = new BasicBSONObject(); xo.put(aop, aval); ob.put(akey,xo); } }
public synchronized void generateId(T obj) { String id = null; while (true) { BSONObject matcher = new BasicBSONObject(); id = CommEncode.generateId(); matcher.put(this.primaryKey, id); BSONObject bson = queryOne(matcher, null, null); if (bson == null) { break; } } try { Class cls = obj.getClass(); Method method = cls.getMethod(this.getGenerateIdKeySetMethodName(), String.class); method.invoke(obj, id); } catch (Exception e) { e.printStackTrace(); } }
public List<T> search(String key, String value, BSONObject order) { BSONObject arg = new BasicBSONObject(); BSONObject regex = new BasicBSONObject(); regex.put(MatchConst._REGEX, value); arg.put(key, regex); List<BSONObject> record = query(arg, null, null); List<T> result1 = new ArrayList<T>(); for (BSONObject bsonObject : record) { try { result1.add(bsonObject.as(entityClass)); } catch (Exception e) { e.printStackTrace(); } } return result1; }
public <V> List<V> search(String key, String value, BSONObject order,Class<V> clazz) { BSONObject arg = new BasicBSONObject(); BSONObject regex = new BasicBSONObject(); regex.put(MatchConst._REGEX, value); arg.put(key, regex); List<BSONObject> record = query(arg, null, null); List<V> result1 = new ArrayList<V>(); for (BSONObject bsonObject : record) { try { result1.add(bsonObject.as(clazz)); } catch (Exception e) { e.printStackTrace(); } } return result1; }
/** * 更新一个数组的字段 * * @param primaryKeyValue * @param field * @param value * @return */ public <T> boolean pushAllByPk(String primaryKeyValue, String field, List<T> value) { BSONObject query = new BasicBSONObject(); query.put(this.primaryKey, primaryKeyValue); BSONObject update = new BasicBSONObject(); update.put(field, value); update.put(field, value); BSONObject modifier = new BasicBSONObject(); modifier.put("$push_all", update); try { super.updateWithUserDefine(query, modifier); return true; } catch (Exception e) { e.printStackTrace(); } return false; }
/** * 取出来的值要按照主键ID的顺序 * * @param primaryKeyValues * @param cls * @return */ public List<T> findListByPkArray(List<String> primaryKeyValues) { BSONObject selector = null; BSONObject query = new BasicBSONObject(); BSONObject matcher = new BasicBSONObject(); matcher.put(MatchConst._IN, primaryKeyValues); query.put(this.primaryKey, matcher); try { List<BSONObject> result = query(query, selector, null); if (result != null && result.size() > 0) { return this.caseBsonsToList(result, entityClass); } } catch (Exception e) { e.printStackTrace(); } return new ArrayList<>(); }
/** * 取出来的值要按照主键ID的顺序 * * @param primaryKeyValues * @param cls * @return */ public List<T> findListByPkArray(String[] primaryKeyValues) { BSONObject selector = null; BSONObject query = new BasicBSONObject(); BSONObject matcher = new BasicBSONObject(); matcher.put(MatchConst._IN, primaryKeyValues); query.put(this.primaryKey, matcher); try { List<BSONObject> result = query(query, selector, null); if (result != null && result.size() > 0) { return this.caseBsonsToList(result, entityClass); } } catch (Exception e) { e.printStackTrace(); } return null; }
public <V> List<V> findListByPkArray(List<String> primaryKeyValues, Class<V> clazz) { BSONObject query = new BasicBSONObject(); BSONObject matcher = new BasicBSONObject(); matcher.put(MatchConst._IN, primaryKeyValues); query.put(this.primaryKey, matcher); try { BSONObject selector = BasicBSONObject.typeToBson(clazz.newInstance()); List<BSONObject> result = query(query, selector, null); if (result != null && result.size() > 0) { return this.caseBsonsToList(result, clazz); } } catch (Exception e) { e.printStackTrace(); } return null; }
public <V> V findAttributeByPk(String primaryKeyValue, Class<V> clazz) { BSONObject query = new BasicBSONObject(); query.put(this.primaryKey, primaryKeyValue); BSONObject selector; try { selector = BasicBSONObject.typeToBson(clazz.newInstance()); BSONObject bsonObejct = queryOne(query, selector, null); if (bsonObejct != null) { return bsonObejct.as(clazz); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
/** * 删除某个对象 * * @param object * @return */ public boolean delete(T object) { BSONObject matcher = null; try { matcher = BasicBSONObject.typeToBson(object); if (matcher != null) { beforeDelete(object); delete(matcher); afterDelete(object); return true; } return false; } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | IntrospectionException e) { e.printStackTrace(); } return false; }
/** * Translates compatible predicates to MongoDB queries * @param predicate * @return */ private static BSONObject translatePredicate(Predicate predicate) { if(predicate == null) return new BasicBSONObject(); if(predicate instanceof LogicalOperationPredicate) return translateLogicalOperationPredicate((LogicalOperationPredicate) predicate); if(predicate instanceof NegatedPredicate) return translateNegatedPredicate((NegatedPredicate) predicate); if(predicate instanceof PathExistencePredicate) return translatePathExistencePredicate((PathExistencePredicate) predicate); if(predicate instanceof RelationalPredicate) return translateRelationalPredicate((RelationalPredicate) predicate); throw new EvaluationException("Unknown predicate: " + predicate.toString()); }
private static BSONObject translateLogicalOperationPredicate(LogicalOperationPredicate predicate) { final BasicBSONList opList = new BasicBSONList(); opList.add(translatePredicate(predicate.getLeft())); opList.add(translatePredicate(predicate.getRight())); final String op; if(predicate.getOperator().equals(LogicalOperationPredicate.Operator.AND)) op = "$and"; else if(predicate.getOperator().equals(LogicalOperationPredicate.Operator.OR)) op = "$or"; else throw new EvaluationException("Unexpected operator: " + predicate.getOperator()); return new BasicBSONObject(op, opList); }
public BSONObject getUpdater( Object[] row, RowMetaInterface rowMeta ) throws KettleValueException { BSONObject updater = new BasicBSONObject() ; for(Map.Entry<String, List<SequoiaDBUpdateFieldInfo>> entry:m_updateFields.entrySet()) { BSONObject fieldsObj = new BasicBSONObject() ; int fieldNum = entry.getValue().size() ; for( int i = 0 ; i < fieldNum ; i++ ) { SequoiaDBUpdateFieldInfo fieldTmp = entry.getValue().get(i) ; int index = rowMeta.indexOfValue( fieldTmp.getName() ) ; ValueMetaInterface vmi = rowMeta.getValueMeta( index ) ; try{ fieldsObj.put(fieldTmp.getPath(), fieldTmp.getBsonValue(row[index], vmi)) ; } catch( KettleValueException e ){ throw new KettleValueException( BaseMessages.getString( PKG, "SequoiaDBOutput.Msg.Err.FailedToGetTheFieldVal" + "(" + entry.getKey() + ":" + row[index].toString() + ")" ) ); } } updater.put( entry.getKey(), fieldsObj ) ; } if ( updater.isEmpty()) { return null ; } return updater ; }
public BSONObject getUpdateCond( Object[] row, RowMetaInterface rowMeta ) throws KettleValueException { BSONObject condition = new BasicBSONObject() ; int fieldNum = m_condFields.size() ; for( int i = 0 ; i < fieldNum ; i++ ) { SequoiaDBUpdateFieldInfo fieldTmp = m_condFields.get(i) ; int index = rowMeta.indexOfValue( fieldTmp.getName() ) ; ValueMetaInterface vmi = rowMeta.getValueMeta( index ) ; try{ condition.put(fieldTmp.getPath(), fieldTmp.getBsonValue(row[index], vmi)) ; } catch( KettleValueException e ){ throw new KettleValueException( BaseMessages.getString( PKG, "SequoiaDBOutput.Msg.Err.FailedToGetTheFieldVal" + "(" + fieldTmp.getName() + ":" + row[index].toString() + ")" ) ); } } if ( condition.isEmpty() ) { return null ; } return condition ; }
public void reduce(Text entityId, Iterator<Text> fragments, OutputCollector<NullWritable, MongoUpdateWritable> framedEntities, Reporter arg3) throws IOException { while (fragments.hasNext()) { String triple = fragments.next().toString(); Map<String, Object> jsonData = (Map<String, Object>) JsonUtils.fromString(triple); Map<String, Object> framedEntity; try { framedEntity = JsonLdProcessor.frame(jsonData, entityFrame.getFrame(), options); List<Object> entities = (List<Object>)framedEntity.get("@graph"); BasicBSONObject bsonQuery = new BasicBSONObject("_id", entityId.toString()); BasicBSONObject bsonObject = new BasicBSONObject(); bsonObject.putAll((Map<String, Object>)entities.get(0)); BasicBSONObject bsonUpdate = new BasicBSONObject(); bsonUpdate.put("$set", bsonObject); framedEntities.collect(null, new MongoUpdateWritable(bsonQuery, bsonUpdate, true, false)); } catch (JsonLdError e) { e.printStackTrace(); } } }
private List<String> getConfigServersFromMongos( final String host, final int port ) throws Exception { final List<String> cfgServers = new ArrayList<String>(); final BasicBSONObject parsed = getParsedCmdLineOpts(host, port); final BasicBSONObject sharding = (BasicBSONObject) parsed.get("sharding"); String cfgServerString; if (sharding != null) cfgServerString = sharding.getString("configDB"); else cfgServerString = (String) parsed.get("configDB"); addCommaSeparatedHosts(cfgServers, cfgServerString); return cfgServers; }
@Override public void reduce(final IntWritable key, final Iterable<DoubleWritable> values, final Context context) throws IOException, InterruptedException { DescriptiveStatistics stats = new DescriptiveStatistics(); for(DoubleWritable rating : values) { stats.addValue(rating.get()); } BasicBSONObject query = new BasicBSONObject("movieid", key.get()); DBObject statValues = new BasicDBObjectBuilder().start() .add("mean", stats.getMean()) .add("median", stats.getPercentile(50)) .add("std", stats.getStandardDeviation()) .add("count", stats.getN()) .add("total", stats.getSum()) .get(); BasicBSONObject movieStats = new BasicBSONObject("stats", statValues); BasicBSONObject update = new BasicBSONObject("$set", movieStats); context.write(NullWritable.get(), new MongoUpdateWritable(query, update)); }
@Test public void testGetValue() { // root.body.profile.name.first = George BSONObject root = new BasicBSONObject(); BSONObject body = new BasicBSONObject(); BSONObject profile = new BasicBSONObject(); BSONObject name = new BasicBSONObject(); BSONObject first = new BasicBSONObject(); first.put("first", "George"); name.put("name", first); profile.put("profile", name); body.put("body", profile); root.put("root", body); assertEquals(BSONUtilities.getValue(root, "root.body.profile.name.first"), "George"); }
@Test public void testGetValues() { // root.body.profile.name.first = George BSONObject root = new BasicBSONObject(); BSONObject body = new BasicBSONObject(); BasicBSONList list = new BasicBSONList(); list.add("hello"); list.add("goodbye"); list.add("have a nice day"); body.put("body", list); root.put("root", body); String[] values = BSONUtilities.getValues(root, "root.body"); assertNotNull(values); assertEquals(values.length, 3); }
/** * Writes large documents to a {@link BasicBSONEncoder}. * * @param levels * The number of levels to create in the tree. * @return The time to write each document in microseconds. * @see #testLargeDocumentCreateAndWritePerformance() */ protected double doLegacyLargeDocCreateAndWrite(final int levels) { final BasicBSONEncoder encoder = new BasicBSONEncoder(); final int iterations = ITERATIONS / (levels << 1); final long startTime = System.nanoTime(); for (int i = 0; i < iterations; ++i) { final BasicBSONObject obj = new BasicBSONObject("_id", Integer.valueOf(myRandom.nextInt())); addLegacyLevel(obj, 1, levels); encoder.encode(obj); } final long endTime = System.nanoTime(); final double delta = ((double) (endTime - startTime)) / TimeUnit.MICROSECONDS.toNanos(1); return (delta / iterations); }
/** * Writes large documents to a {@link BasicBSONEncoder}. * * @param levels * The number of levels to create in the tree. * @return The time to write each document in microseconds. * @see #testLargeDocumentWritePerformance() */ protected double doLegacyLargeDocWrite(final int levels) { final BasicBSONEncoder encoder = new BasicBSONEncoder(); final int iterations = ITERATIONS / (levels << 1); // Create the tree once. final BasicBSONObject obj = new BasicBSONObject("_id", Integer.valueOf(myRandom.nextInt())); addLegacyLevel(obj, 1, levels); final long startTime = System.nanoTime(); for (int i = 0; i < iterations; ++i) { encoder.encode(obj); } final long endTime = System.nanoTime(); final double delta = ((double) (endTime - startTime)) / TimeUnit.MICROSECONDS.toNanos(1); return (delta / iterations); }
/** * Writes micro documents to a {@link BasicBSONEncoder}. * * @return The time to write each document in microseconds. * @see #testMicroDocumentWritePerformance() */ protected double doLegacyMicroDocWrite() { final BasicBSONEncoder encoder = new BasicBSONEncoder(); final long startTime = System.nanoTime(); for (int i = 0; i < ITERATIONS; ++i) { final BasicBSONObject obj = new BasicBSONObject("_id", Integer.valueOf(myRandom.nextInt())); encoder.encode(obj); } final long endTime = System.nanoTime(); final double delta = ((double) (endTime - startTime)) / TimeUnit.MICROSECONDS.toNanos(1); return (delta / ITERATIONS); }
/** * Writes small documents to a {@link BasicBSONEncoder}. * * @return The time to write each document in microseconds. * @see #testSmallDocumentWritePerformance() */ protected double doLegacySmallDocWrite() { final BasicBSONEncoder encoder = new BasicBSONEncoder(); final long startTime = System.nanoTime(); for (int i = 0; i < ITERATIONS; ++i) { final BasicBSONObject obj = new BasicBSONObject("_id", Integer.valueOf(myRandom.nextInt())); obj.put("v", SMALL_VALUE); encoder.encode(obj); } final long endTime = System.nanoTime(); final double delta = ((double) (endTime - startTime)) / TimeUnit.MICROSECONDS.toNanos(1); return (delta / ITERATIONS); }
/** * extract datas from a GET REQUEST (query string params) * @param request * @return request datas as a BSONObject */ private static BasicBSONObject extractGetRequestData(HttpServletRequest request){ try{ String query; if(useBSON) query = ServletUtils.decryptBSON(request.getQueryString()); else query = request.getQueryString(); if(query!=null){ query = query.replaceAll("(%22|%27)", "\""); query = query.replaceAll("%20", " "); BasicBSONObject params = (BasicBSONObject) JSON.parse(query); return params; } else return new BasicBSONObject(); } catch (JSONParseException e){ return new BasicBSONObject(); } }
/** * decrypt a BSON string * @param datas : BSON formated String * @return JSON formated String */ private static String decryptBSON(String datas){ String[] tab = datas.split("[a-zA-Z]"); byte[] array = new byte[tab.length]; for(int i =0; i<tab.length; i++){ array[i] = Byte.valueOf(tab[i]); } BSONDecoder decoder = new BasicBSONDecoder(); BasicBSONObject obj = (BasicBSONObject) decoder.readObject(array); System.out.println(obj); return obj.toString(); }
@Override public BSONObject findByKey(String key, String value) { BSONObject map = new BasicBSONObject(); String query = "SELECT * FROM "+this.table+" WHERE "+key+"=?"; try { this.statement = connexion.prepareStatement(query); this.statement.setString(1, value); ResultSet result = this.statement.executeQuery(); if(result.first()) for(int i=1; i<= result.getMetaData().getColumnCount(); i++){ map.put(result.getMetaData().getColumnLabel(i), result.getString(i)); } else return null; } catch (SQLException e) { e.printStackTrace(); } return map; }
@Override public Object call(BasicBSONObject bsonResponse) { //si on vient de cr�er une transaction if(bsonResponse.getString(RESQUEST_TAG) == POST_TRANSACTION_TAG){ //on met � jour le solde de l'utilisateur dans la session en cours User.setAccountBalance(Integer.parseInt(bsonResponse.getString(ServerHelper.SERVER_BALANCE_KEY))); } //si on vient de "fetch" le wallet if(bsonResponse.getString(RESQUEST_TAG) == GET_WALLET_TAG){ //on met � jour le solde de l'utilisateur dans la session en cours User.setAccountBalance(Integer.parseInt(bsonResponse.getString(ServerHelper.SERVER_BALANCE_KEY))); } //si on vient de "fetch" les transactions if(bsonResponse.getString(RESQUEST_TAG) == GET_TRANSACTION_TAG){ //... //la il faudrait mettre les transactions en cache (dans TransactionList.java par exemple) } return null; }
@Override public Object call(BasicBSONObject bsonResponse) { if(bsonResponse.getString(ServerHelper.RESQUEST_TAG) == ServerHelper.GET_TRANSACTION_TAG){ //Log.i("ADAPTER", "getting result : "+bsonResponse.get(ServerHelper.SERVER_TRANSACTIONS_KEY).toString()); BasicBSONList bsonList = (BasicBSONList) bsonResponse.get(ServerHelper.SERVER_TRANSACTIONS_KEY); this.items.clear(); for(int i = 0; i < bsonList.size(); i++){ BasicBSONObject bsonData = (BasicBSONObject) bsonList.get(i); if(!bsonData.getString(ServerHelper.SERVER_SENDER_KEY).equals(ServerHelper.SYSTEM_USER_TAG)){ int transactionAmount = Integer.parseInt(bsonData.getString(ServerHelper.SERVER_TRANSACTION_AMOUNT_KEY)); Transaction tmpTransaction = new Transaction( bsonData.getString(ServerHelper.SERVER_ID_KEY), bsonData.getString(ServerHelper.SERVER_RECEIVER_KEY), bsonData.getString(ServerHelper.SERVER_SENDER_KEY), transactionAmount); this.add(tmpTransaction); } } } //Log.i("TransactionListAdapter", this.items.toString()); this.notifyDataSetChanged(); return null; }
@Override protected BasicBSONObject doInBackground(String... args){ Log.i("REQUEST", "PREPARING with method = " + method+" and url = "+url); //Log.i("REQUEST", "MedthodClass : " + ServerHelper.REQUEST_MAP.get(method).toString()); try { this.request = ServerHelper.REQUEST_MAP.get(this.method).getConstructor(String.class).newInstance(url); this.loadParams(); Log.i("REQUEST", "bsonParams = "+this.bsonParams.toString()); Log.i("REQUEST", "httpParams = "+this.request.getParams()); Log.i("REQUEST", "EXECUTING"); this.response = client.execute(request); //Log.i("REQUEST", "READING"); return BsonHandler.readResponse(this.response.getEntity().getContent()); }catch (Exception e) { e.printStackTrace(); this.error = true; this.errorObject = ErrorHelper.getErrorObject(e); } return null; }
@Override public Object call(BasicBSONObject bsonResponse) { this.connexionBtnFragment.hideLoader(); //Log.i("REQUEST", bsonResponse.toString()); //si la r�ponse ne contient le token de login if(bsonResponse.containsField(ServerHelper.SERVER_TOKEN_KEY) && bsonResponse.containsField(ServerHelper.SERVER_EMAIL_KEY)){ //on d�marre l'activity WalletActivity Intent loadWallet = new Intent(getApplicationContext(), WalletActivity.class); Bundle session = new Bundle(); session.putString(ServerHelper.SERVER_TOKEN_KEY, bsonResponse.getString(ServerHelper.SERVER_TOKEN_KEY)); session.putString(ServerHelper.SERVER_EMAIL_KEY, bsonResponse.getString(ServerHelper.SERVER_EMAIL_KEY)); session.putString(ServerHelper.SERVER_TAG_KEY, bsonResponse.getString(ServerHelper.SERVER_TAG_KEY)); loadWallet.putExtra("session", session); startActivity(loadWallet); } return null; }
public static BasicBSONObject readResponse(InputStream stream) throws CustomServerException, JSONException, IOException{ BasicBSONObject bsonResponse; String lineRead = ""; StringBuilder stringResponse = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { while((lineRead = reader.readLine())!=null){ stringResponse.append(lineRead); } } catch (IOException e) { throw e; } bsonResponse = decodeResponseBody(stringResponse.toString()); if(bsonResponse.containsField("error")){ throw ErrorHelper.getCustomServerException(bsonResponse.getString("error")); } return bsonResponse; }
@SuppressWarnings("unused") private void opSQLExpr(SQLBinaryOpExpr expr,BasicBSONObject o) { SQLExpr exprL=expr.getLeft(); if (!(exprL instanceof SQLBinaryOpExpr)) { if (expr.getOperator().getName().equals("=")) { o.put(exprL.toString(), getExpValue(expr.getRight())); } else { //BasicBSONObject xo = new BasicBSONObject(); String op=""; if (expr.getOperator().getName().equals("<")) { op="$lt"; } if (expr.getOperator().getName().equals("<=")) { op = "$lte"; } if (expr.getOperator().getName().equals(">")) { op = "$gt"; } if (expr.getOperator().getName().equals(">=")) { op = "$gte"; } if (expr.getOperator().getName().equals("!=")) { op = "$ne"; } if (expr.getOperator().getName().equals("<>")) { op = "$ne"; } //xo.put(op, getExpValue(expr.getRight())); // o.put(exprL.toString(),xo); parserDBObject(o,exprL.toString(),op, getExpValue(expr.getRight())); } } }
private void orWhere(SQLExpr exprL,SQLExpr exprR ,BasicBSONObject ob){ BasicBSONObject xo = new BasicBSONObject(); BasicBSONObject yo = new BasicBSONObject(); parserWhere(exprL,xo); parserWhere(exprR,yo); ob.put("$or",new Object[]{xo,yo}); }
/** * * @param obj an array of pairs of property name and value/Map<String, Object> or an entity with getter/setter methods. * @return */ public static BasicBSONObject toBSONObject(final Object obj) { final BasicBSONObject result = new BasicBSONObject(); if (obj instanceof Map) { result.putAll((Map<String, Object>) obj); } else if (N.isEntity(obj.getClass())) { Maps.deepEntity2Map(result, obj); } else if (obj instanceof Object[]) { final Object[] a = (Object[]) obj; if (0 != (a.length % 2)) { throw new IllegalArgumentException( "The parameters must be the pairs of property name and value, or Map, or an entity class with getter/setter methods."); } for (int i = 0; i < a.length; i++) { result.put((String) a[i], a[++i]); } } else { throw new IllegalArgumentException("The parameters must be a Map, or an entity class with getter/setter methods"); } resetObjectId(obj, result); return result; }
@SafeVarargs public static BasicBSONObject toBSONObject(final Object... a) { if (N.isNullOrEmpty(a)) { return new BasicBSONObject(); } return a.length == 1 ? toBSONObject(a[0]) : toBSONObject((Object) a); }
/** * * @param matcher * @param obj */ public void updateUsingSetOpreator(BSONObject matcher, Object obj) { BSONObject modifier = new BasicBSONObject(); Sequoiadb sdb = DbConnectionPool.getConnection(); try { modifier.put("$set", BasicBSONObject.typeToBson(obj)); getDbCollection(sdb).update(matcher, modifier, null); } catch (Exception e) { e.printStackTrace(); } finally { DbConnectionPool.free(sdb); } }