org.bson.BasicBSONObject Java Examples

The following examples show how to use org.bson.BasicBSONObject. 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: ExternalServiceHandler.java    From lumongo with Apache License 2.0 6 votes vote down vote up
@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) {

			}
		}

	}
}
 
Example #2
Source File: BSONValueLookupTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: BSONValueLookupTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #4
Source File: MapReduceExercise.java    From mongodb-hadoop-workshop with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #5
Source File: SequoiaSQLParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: ReplicaSetConfigTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test
public void testFourthServerOfFourIsGivenVoteWhenAnotherServerIsRemoved() {
    BasicBSONObject config = makeSetWithNMembers(4);
    HostAndPort toRemove = votingMembersOfSet(config).iterator().next();

    BasicBSONObject updated = ReplicaSetConfig.fromExistingConfig(config)
            .remove(toRemove)
            .build();

    assertEquals(votingMembersOfSet(updated).size(), 3);
    assertTrue(nonVotingMembersOfSet(updated).isEmpty());

    BasicBSONList newMembers = BasicBSONList.class.cast(updated.get("members"));
    for (Object object : newMembers) {
        BasicBSONObject member = BasicBSONObject.class.cast(object);
        HostAndPort memberHostAndPort = HostAndPort.fromString(member.getString("host"));
        assertNotEquals(memberHostAndPort, toRemove);
    }
}
 
Example #7
Source File: ReplicaSetConfig.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the first entity with the given hostname and port from the list of members
 */
public ReplicaSetConfig remove(String hostname, Integer port) {
    String host = String.format("%s:%s", hostname, port);
    Iterator<Object> it = this.members.iterator();
    while (it.hasNext()) {
        Object next = it.next();
        if (next instanceof BasicBSONObject) {
            BasicBSONObject basicBSONObject = (BasicBSONObject) next;
            if (host.equals(basicBSONObject.getString("host"))) {
                it.remove();
                break;
            }
        }
    }
    return this;
}
 
Example #8
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Reconfigures the replica set that this client is the primary member of to include a new member.
 * <p/>
 * Note that this can cause long downtime (typically 10-20s, even up to a minute).
 *
 * @param secondary New member of the set.
 * @param id The id for the new set member. Must be unique within the set.
 * @return True if successful
 */
public boolean addMemberToReplicaSet(MongoDBServer secondary, Integer id) {
    // We need to:
    // - get the existing configuration
    // - update its version
    // - add the new member to its list of members
    // - run replSetReconfig with the new configuration.
    BSONObject existingConfig = getReplicaSetConfig();
    if (existingConfig == null) {
        LOG.warn("Couldn't load existing config for replica set from {}. Server {} not added.",
                getServerAddress(), secondary);
        return false;
    }

    BasicBSONObject newConfig = ReplicaSetConfig.fromExistingConfig(existingConfig)
            .primary(getServerHostAndPort())
            .member(secondary, id)
            .build();
    return reconfigureReplicaSet(newConfig);
}
 
Example #9
Source File: SequoiaSQLParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
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;		
}
 
Example #10
Source File: SequoiaSQLParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
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);	
	}
    
}
 
Example #11
Source File: SequoiaSQLParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@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()));
		  }
	   }		
}
 
Example #12
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public boolean initializeReplicaSet(String replicaSetName, Integer id) {
    HostAndPort primary = getServerHostAndPort();
    BasicBSONObject config = ReplicaSetConfig.builder(replicaSetName)
            .member(primary, id)
            .build();

    BasicDBObject dbObject = new BasicDBObject("replSetInitiate", config);
    LOG.debug("Initiating replica set with: " + dbObject);

    Optional<CommandResult> result = runDBCommand("admin", dbObject);
    if (result.isPresent() && result.get().ok() && LOG.isDebugEnabled()) {
        LOG.debug("Completed initiating MongoDB replica set {} on entity {}", replicaSetName, this);
    }
    return result.isPresent() && result.get().ok();
}
 
Example #13
Source File: OpReply.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static OpReply errorReply( String message ) {
    OpReply reply = new OpReply();
    // reply.responseFlags = 1;
    BSONObject b = new BasicBSONObject();
    b.put( "$err", message );
    b.put( "ok", 0.0 );
    reply.documents.add( b );
    return reply;
}
 
Example #14
Source File: MongoEntity.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public MongoEntity(String type, String id, Map<String, Object> body, Map<String, Object> metaData,
        CalculatedData<String> calculatedData, CalculatedData<Map<String, Integer>> aggregates) {
    this.type = type;
    this.entityId = id;
    this.body = body == null ? new BasicBSONObject() : body;
    this.metaData = metaData == null ? new BasicBSONObject() : metaData;
    this.calculatedData = calculatedData == null ? new CalculatedData<String>() : calculatedData;
    this.aggregates = aggregates == null ? new CalculatedData<Map<String, Integer>>() : aggregates;
    this.embeddedData = new HashMap<String, List<Entity>>();
    this.denormalizedData = new HashMap<String, List<Map<String, Object>>>();
    this.containerData = new HashMap<String, List<Entity>>();
}
 
Example #15
Source File: MongoEntity.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public MongoEntity(String type, String id, Map<String, Object> body, Map<String, Object> metaData,
        CalculatedData<String> calculatedData, CalculatedData<Map<String, Integer>> aggregates,
        Map<String, List<Entity>> embeddedData, Map<String, List<Map<String, Object>>> denormalizedData) {
    this.type = type;
    this.entityId = id;
    this.body = body == null ? new BasicBSONObject() : body;
    this.metaData = metaData == null ? new BasicBSONObject() : metaData;
    this.calculatedData = calculatedData == null ? new CalculatedData<String>() : calculatedData;
    this.aggregates = aggregates == null ? new CalculatedData<Map<String, Integer>>() : aggregates;
    this.embeddedData = embeddedData == null ? new HashMap<String, List<Entity>>() : embeddedData;
    this.denormalizedData = denormalizedData == null ? new HashMap<String, List<Map<String, Object>>>()
            : denormalizedData;
    this.containerData = new HashMap<String, List<Entity>>();
}
 
Example #16
Source File: MongoEntity.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public MongoEntity(String type, String id, Map<String, Object> body, Map<String, Object> metaData,
        CalculatedData<String> calculatedData, CalculatedData<Map<String, Integer>> aggregates,
        Map<String, List<Entity>> embeddedData, Map<String, List<Map<String, Object>>> denormalizedData,
        Map<String, List<Entity>> containerData) {
    this.type = type;
    this.entityId = id;
    this.body = body == null ? new BasicBSONObject() : body;
    this.metaData = metaData == null ? new BasicBSONObject() : metaData;
    this.calculatedData = calculatedData == null ? new CalculatedData<String>() : calculatedData;
    this.aggregates = aggregates == null ? new CalculatedData<Map<String, Integer>>() : aggregates;
    this.embeddedData = embeddedData == null ? new HashMap<String, List<Entity>>() : embeddedData;
    this.denormalizedData = denormalizedData == null ? new HashMap<String, List<Map<String, Object>>>()
            : denormalizedData;
    this.containerData = containerData == null ? new HashMap<String, List<Entity>>() : containerData;
}
 
Example #17
Source File: TenantAndIdEmittableKey.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public BSONObject toBSON() {
    BSONObject bson = new BasicBSONObject();
    bson.put(getTenantIdField().toString(), getTenantId().toString());
    bson.put(getIdField().toString(), getId().toString());
    return bson;
}
 
Example #18
Source File: StringValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetValue() {
    BSONObject field = new BasicBSONObject("field", "testing123");
    BSONObject entry = new BasicBSONObject("string", field);
    BSONWritable entity = new BSONWritable(entry);

    StringValueMapper mapper = new StringValueMapper("string.field");

    Writable value = mapper.getValue(entity);
    assertFalse(value instanceof NullWritable);
    assertTrue(value instanceof Text);
    assertEquals(value.toString(), "testing123");
}
 
Example #19
Source File: StringValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testValueNotFound() {
    BSONObject field = new BasicBSONObject("field", "testing123");
    BSONObject entry = new BasicBSONObject("string", field);
    BSONWritable entity = new BSONWritable(entry);

    StringValueMapper mapper = new StringValueMapper("string.missing_field");

    Writable value = mapper.getValue(entity);
    assertTrue(value instanceof NullWritable);
}
 
Example #20
Source File: LongValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetValue() {
    BSONObject field = new BasicBSONObject("field", 123L);
    BSONObject entry = new BasicBSONObject("long", field);
    BSONWritable entity = new BSONWritable(entry);

    LongValueMapper mapper = new LongValueMapper("long.field");

    Writable value = mapper.getValue(entity);
    assertFalse(value instanceof NullWritable);
    assertTrue(value instanceof LongWritable);
    assertEquals(((LongWritable) value).get(), 123L);
}
 
Example #21
Source File: LongValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testValueNotFound() {
    BSONObject field = new BasicBSONObject("field", 123L);
    BSONObject entry = new BasicBSONObject("long", field);
    BSONWritable entity = new BSONWritable(entry);

    LongValueMapper mapper = new LongValueMapper("long.missing_field");

    Writable value = mapper.getValue(entity);
    assertTrue(value instanceof NullWritable);
}
 
Example #22
Source File: LongValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testValueNotLong() {
    BSONObject field = new BasicBSONObject("field", true);
    BSONObject entry = new BasicBSONObject("long", field);
    BSONWritable entity = new BSONWritable(entry);

    LongValueMapper mapper = new LongValueMapper("long.field");

    Writable value = mapper.getValue(entity);
    assertTrue(value instanceof NullWritable);
}
 
Example #23
Source File: EnumValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetValue() {

    BSONObject field = new BasicBSONObject("field", "TEST1");
    BSONObject entry = new BasicBSONObject("enum", field);
    BSONWritable entity = new BSONWritable(entry);

    EnumValueMapper<Testing> m = new EnumValueMapper<Testing>("enum.field", Testing.class);

    Writable value = m.getValue(entity);
    assertFalse(value instanceof NullWritable);
    assertTrue(value instanceof Text);
    assertEquals(((Text) value).toString(), Testing.TEST1.toString());
}
 
Example #24
Source File: EnumValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetValueNotFound() {

    BSONObject field = new BasicBSONObject("field", "Unknown");
    BSONObject entry = new BasicBSONObject("enum", field);
    BSONWritable entity = new BSONWritable(entry);

    EnumValueMapper<Testing> m = new EnumValueMapper<Testing>("enum.field", Testing.class);

    Writable value = m.getValue(entity);
    assertTrue(value instanceof NullWritable);
}
 
Example #25
Source File: ValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testMap() throws Exception {
    TenantAndIdEmittableKey key = new TenantAndIdEmittableKey();
    ValueMapper m = new MockValueMapper();
    BSONObject entry = new BasicBSONObject("found", "data");
    BSONWritable entity = new BSONWritable(entry);

    Context context = Mockito.mock(Context.class);
    PowerMockito.when(context, "write", Matchers.any(EmittableKey.class),
        Matchers.any(BSONObject.class)).thenAnswer(new Answer<BSONObject>() {

        @Override
        public BSONObject answer(InvocationOnMock invocation) throws Throwable {

            Object[] args = invocation.getArguments();

            assertNotNull(args);
            assertEquals(args.length, 2);

            assertTrue(args[0] instanceof TenantAndIdEmittableKey);
            assertTrue(args[1] instanceof ContentSummary);

            TenantAndIdEmittableKey id = (TenantAndIdEmittableKey) args[0];
            assertNotNull(id);

            ContentSummary e = (ContentSummary) args[1];
            assertEquals(e.getLength(), 1);
            assertEquals(e.getFileCount(), 2);
            assertEquals(e.getDirectoryCount(), 3);

            return null;
        }
    });

    m.map(key, entity, context);
}
 
Example #26
Source File: ValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testMapValueNotFound() throws Exception {
    TenantAndIdEmittableKey key = new TenantAndIdEmittableKey();
    ValueMapper m = new MockValueMapper();
    BSONObject entry = new BasicBSONObject("not_found", "data");
    BSONWritable entity = new BSONWritable(entry);

    Context context = Mockito.mock(Context.class);
    PowerMockito.when(context, "write", Matchers.any(TenantAndIdEmittableKey.class),
        Matchers.any(BSONObject.class)).thenAnswer(new Answer<BSONObject>() {

        @Override
        public BSONObject answer(InvocationOnMock invocation) throws Throwable {

            Object[] args = invocation.getArguments();

            assertNotNull(args);
            assertEquals(args.length, 2);

            assertTrue(args[0] instanceof TenantAndIdEmittableKey);
            assertTrue(args[1] instanceof NullWritable);

            return null;
        }
    });

    m.map(key, entity, context);
}
 
Example #27
Source File: DoubleValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetValue() {
    BSONObject field = new BasicBSONObject("field", 1.312D);
    BSONObject entry = new BasicBSONObject("double", field);
    BSONWritable entity = new BSONWritable(entry);

    DoubleValueMapper mapper = new DoubleValueMapper("double.field");

    Writable value = mapper.getValue(entity);
    assertFalse(value instanceof NullWritable);
    assertTrue(value instanceof DoubleWritable);
    assertEquals(((DoubleWritable) value).get(), 1.312D, 0.05);
}
 
Example #28
Source File: DoubleValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testValueNotFound() {
    BSONObject field = new BasicBSONObject("field", 1.312D);
    BSONObject entry = new BasicBSONObject("double", field);
    BSONWritable entity = new BSONWritable(entry);

    DoubleValueMapper mapper = new DoubleValueMapper("double.missing_field");

    Writable value = mapper.getValue(entity);
    assertTrue(value instanceof NullWritable);
}
 
Example #29
Source File: DoubleValueMapperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetValueNotDouble() {
    BSONObject field = new BasicBSONObject("field", "Bob");
    BSONObject entry = new BasicBSONObject("double", field);
    BSONWritable entity = new BSONWritable(entry);

    DoubleValueMapper mapper = new DoubleValueMapper("double.field");

    Writable value = mapper.getValue(entity);
    assertTrue(value instanceof NullWritable);
}
 
Example #30
Source File: ReplicaSetConfigTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private Collection<HostAndPort> nonVotingMembersOfSet(BasicBSONObject config) {
    BasicBSONList membersObject = BasicBSONList.class.cast(config.get("members"));
    List<BasicBSONObject> members = Lists.newArrayList();
    for (Object object : membersObject) members.add(BasicBSONObject.class.cast(object));
    return FluentIterable
            .from(members)
            .filter(Predicates.not(IS_VOTING_MEMBER))
            .transform(new Function<BasicBSONObject, HostAndPort>() {
                @Override public HostAndPort apply(BasicBSONObject input) {
                    return HostAndPort.fromString(input.getString("host"));
                }
            })
            .toList();
}