Java Code Examples for org.bson.BSONObject#get()

The following examples show how to use org.bson.BSONObject#get() . 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: BasicTranslator.java    From zerowing with MIT License 6 votes vote down vote up
@Override
public byte[] createRowKey(BSONObject object) {
  Object id = object.get("_id");

  byte[] raw;
  if (id instanceof ObjectId) {
    raw = ((ObjectId) id).toByteArray();
  } else if (id instanceof String) {
    raw = ((String) id).getBytes();
  } else if (id instanceof BSONObject) {
    raw = bsonEncoder.encode(((BSONObject) id));
  } else {
    throw new RuntimeException("Don't know how to serialize _id: " + id.toString());
  }

  return DigestUtils.md5(raw);
}
 
Example 2
Source File: TenantAndIdEmittableKeyTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testToBSON() {
    TenantAndIdEmittableKey key =
        new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field");
    key.setTenantId(new Text("Midgar"));
    key.setId(new Text("1234"));

    BSONObject bson = key.toBSON();
    assertNotNull(bson);
    assertTrue(bson.containsField("meta.data.tenantId"));

    Object obj = bson.get("meta.data.tenantId");
    assertNotNull(obj);
    assertTrue(obj instanceof String);
    String val = (String) obj;
    assertEquals(val, "Midgar");

    assertTrue(bson.containsField("test.id.key.field"));
    obj = bson.get("test.id.key.field");
    assertNotNull(obj);
    assertTrue(obj instanceof String);
    val = (String) obj;
    assertEquals(val, "1234");
}
 
Example 3
Source File: ReplicaSetConfig.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a configuration from an existing configuration.
 * <p/>
 * Automatically increments the replica set's version number.
 */
public static ReplicaSetConfig fromExistingConfig(BSONObject config) {
    checkNotNull(config);
    checkArgument(config.containsField("_id"), "_id missing from replica set config");
    checkArgument(config.containsField("version"), "version missing from replica set config");
    checkArgument(config.containsField("members"), "members missing from replica set config");

    String name = (String) config.get("_id");
    Integer version = (Integer) config.get("version");
    BasicBSONList members = (BasicBSONList) config.get("members");

    return new ReplicaSetConfig(name, members).version(++version);
}
 
Example 4
Source File: MapReduceExercise.java    From mongodb-hadoop-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void map(final Object key, final BSONObject doc, final Context context)
  throws IOException, InterruptedException {
    final int movieId = (Integer)doc.get("movieid");
    final Number movieRating = (Number)doc.get("rating");

    context.write(new IntWritable(movieId), new DoubleWritable(movieRating.doubleValue()));
}
 
Example 5
Source File: OpInsert.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public OpReply doOp( MongoChannelHandler handler, ChannelHandlerContext ctx, MessageEvent messageEvent ) {

    ApplicationInfo application = SubjectUtils.getApplication( Identifier.from( getDatabaseName() ) );

    if ( application == null ) {
        ctx.setAttachment( new IllegalArgumentException(
                String.format( "Could not find application with name '%s' ", getDatabaseName() ) ) );
        return null;
    }


    EntityManager em = handler.getEmf().getEntityManager( application.getId() );


    for ( BSONObject document : documents ) {
        try {
            //special case to serialize mongo ObjectId if required
            Object id = document.get( "_id" );

            if ( id instanceof ObjectId ) {
                document.put( "_id", ( ( ObjectId ) id ).toStringMongod() );
            }

            em.create( getCollectionName(), document.toMap() );
        }
        catch ( Exception e ) {
            logger.error( "Unable to insert mongo document {}", document, e );
            ctx.setAttachment( e );
        }
    }

    //insert never returns a response in mongo
    return null;
}
 
Example 6
Source File: BSONValueLookupTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetValue() {

    BSONObject root = BSONUtilities.setValue("body.profile.name.first", "George");
    assertNotNull(root);
    BSONObject body = (BSONObject) root.get("body");
    assertNotNull(body);
    BSONObject profile = (BSONObject) body.get("profile");
    assertNotNull(profile);
    BSONObject name = (BSONObject) profile.get("name");
    assertNotNull(name);
    assertNotNull(name.get("first"));
    assertEquals(name.get("first"), "George");
}
 
Example 7
Source File: IdFieldEmittableKeyTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testToBSON() {
    IdFieldEmittableKey key = new IdFieldEmittableKey("test.id.key.field");
    key.setId(new Text("1234"));

    BSONObject bson = key.toBSON();
    assertNotNull(bson);
    assertTrue(bson.containsField("test.id.key.field"));

    Object obj = bson.get("test.id.key.field");
    assertNotNull(obj);
    assertTrue(obj instanceof String);
    String val = (String) obj;
    assertEquals(val, "1234");
}
 
Example 8
Source File: UtilMongoDB.java    From deep-spark with Apache License 2.0 4 votes vote down vote up
/**
 * converts from BsonObject to an entity class with deep's anotations
 *
 * @param classEntity the entity name.
 * @param bsonObject  the instance of the BSONObjet to convert.
 * @return the provided bsonObject converted to an instance of T.
 * @throws IllegalAccessException the illegal access exception
 * @throws IllegalAccessException the instantiation exception
 * @throws IllegalAccessException the invocation target exception
 */
public static <T> T getObjectFromBson(Class<T> classEntity, BSONObject bsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    T t = classEntity.newInstance();

    Field[] fields = AnnotationUtils.filterDeepFields(classEntity);

    Object insert = null;

    for (Field field : fields) {
        Object currentBson = null;
        Method method = null;
        try {
            method = Utils.findSetter(field.getName(), classEntity, field.getType());

            Class<?> classField = field.getType();

            currentBson = bsonObject.get(AnnotationUtils.deepFieldName(field));
            if (currentBson != null) {

                if (Iterable.class.isAssignableFrom(classField)) {
                    Type type = field.getGenericType();

                    insert = subDocumentListCase(type, (List) bsonObject.get(AnnotationUtils.deepFieldName(field)));

                } else if (IDeepType.class.isAssignableFrom(classField)) {
                    insert = getObjectFromBson(classField, (BSONObject) bsonObject.get(AnnotationUtils.deepFieldName
                            (field)));
                } else {
                    insert = currentBson;
                }
                method.invoke(t, insert);
            }
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException | IllegalArgumentException e) {
            LOG.error("impossible to create a java object from Bson field:" + field.getName() + " and type:" + field
                    .getType() + " and value:" + t + "; bsonReceived:" + currentBson + ", bsonClassReceived:"
                    + currentBson.getClass());

            method.invoke(t, Utils.castNumberType(insert, t.getClass()));
        }

    }

    return t;
}
 
Example 9
Source File: MongoQueryParser.java    From usergrid with Apache License 2.0 4 votes vote down vote up
/** Handle an operand */
private static Operand handleOperand( String sourceField, BSONObject exp ) {

    Operand current = null;
    Object value = null;

    for ( String field : exp.keySet() ) {
        if ( field.startsWith( "$" ) ) {
            if ( "$gt".equals( field ) ) {
                value = exp.get( field );

                GreaterThan gt = new GreaterThan();
                gt.setProperty( sourceField );
                gt.setLiteral( value );

                current = gt;
            }
            else if ( "$gte".equals( field ) ) {
                value = exp.get( field );

                GreaterThanEqual gte = new GreaterThanEqual();
                gte.setProperty( sourceField );
                gte.setLiteral( exp.get( field ) );

                current = gte;
                // http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%3C%2C%3C%3D%2C%3E%2C%3E%3D
                // greater than equals
                // { "field" : { $gte: value } }
            }
            else if ( "$lt".equals( field ) ) {
                value = exp.get( field );

                LessThan lt = new LessThan();
                lt.setProperty( sourceField );
                lt.setLiteral( value );

                current = lt;
            }
            else if ( "$lte".equals( field ) ) {
                value = exp.get( field );

                LessThanEqual lte = new LessThanEqual();
                lte.setProperty( sourceField );
                lte.setLiteral( value );

                current = lte;
            }
            else if ( "$in".equals( field ) ) {
                value = exp.get( field );

                BasicBSONList values = ( BasicBSONList ) value;

                int size = values.size();

                Stack<Operand> expressions = new Stack<Operand>();

                for (Object value1 : values) {
                    Equal equal = new Equal();
                    equal.setProperty(sourceField);
                    equal.setLiteral(value1);

                    expressions.push(equal);
                }

                // we need to build a tree of expressions
                while ( expressions.size() > 1 ) {
                    OrOperand or = new OrOperand();
                    or.addChild( expressions.pop() );
                    or.addChild( expressions.pop() );
                    expressions.push( or );
                }

                current = expressions.pop();
            }
        }
    }

    return current;
}
 
Example 10
Source File: UtilMongoDBTest.java    From deep-spark with Apache License 2.0 2 votes vote down vote up
@Test
public void testGetBsonFromObject()
        throws UnknownHostException, NoSuchFieldException, IllegalAccessException, InvocationTargetException,
        InstantiationException {

    MetadataEntity metadataEntity = new MetadataEntity();
    metadataEntity.setAuthor(AUTHOR);
    metadataEntity.setTitle(TITLE);
    metadataEntity.setSource(SOURCE);

    List<CantoEntity> CantoEntities = new ArrayList<>();

    CantoEntity cantoI = new CantoEntity();
    cantoI.setNumber(CANTO_I);
    cantoI.setText(TEXT_I);

    CantoEntities.add(cantoI);

    CantoEntity cantoII = new CantoEntity();
    cantoII.setNumber(CANTO_II);
    cantoII.setText(TEXT_II);

    CantoEntities.add(cantoII);

    BookEntity bookEntity = new BookEntity();

    bookEntity.setCantoEntities(CantoEntities);

    bookEntity.setMetadataEntity(metadataEntity);

    BSONObject bson = UtilMongoDB.getBsonFromObject(bookEntity);

    BSONObject metadataFromBson = (BSONObject) bson.get("metadata");

    assertEquals(metadataFromBson.get("author"), AUTHOR);

    assertEquals(metadataFromBson.get("title"), TITLE);

    assertEquals(metadataFromBson.get("source"), SOURCE);

    List<BSONObject> cantoEntityListFromBson = (List<BSONObject>) bson.get("cantos");

    assertEquals(cantoEntityListFromBson.get(0).get("canto"), CANTO_I);

    assertEquals(cantoEntityListFromBson.get(0).get("text"), TEXT_I);

    assertEquals(cantoEntityListFromBson.get(1).get("canto"), CANTO_II);

    assertEquals(cantoEntityListFromBson.get(1).get("text"), TEXT_II);

}