Search in sources :

Example 56 with BSONObject

use of org.bson.BSONObject in project mongo-java-driver by mongodb.

the class DefaultDBCallback method objectDone.

@Override
public Object objectDone() {
    String name = curName();
    BSONObject document = (BSONObject) super.objectDone();
    if (!(document instanceof BasicBSONList)) {
        Iterator<String> iterator = document.keySet().iterator();
        if (iterator.hasNext() && iterator.next().equals("$ref") && iterator.hasNext() && iterator.next().equals("$id")) {
            _put(name, new DBRef((String) document.get("$db"), (String) document.get("$ref"), document.get("$id")));
        }
    }
    return document;
}
Also used : BasicBSONList(org.bson.types.BasicBSONList) BSONObject(org.bson.BSONObject)

Example 57 with BSONObject

use of org.bson.BSONObject in project immutables by immutables.

the class BsonEncoding method unwrapBsonable.

/**
   * Although it may seem that re-parsing is bizarre, but it is one [of not so many] ways to do
   * proper marshaling. This kind of inefficiency will only hit query constraints that have many
   * object with custom marshaling, which considered to be a rare case.
   * @param adapted adapted value that know how to write itself to {@link JsonWriter}
   * @return object converted to MongoDB driver's {@link BSONObject}.
   */
public static Object unwrapBsonable(Support.Adapted<?> adapted) {
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        BsonGenerator generator = BSON_FACTORY.createGenerator(outputStream);
        BsonWriter writer = new BsonWriter(generator);
        writer.beginObject().name(PREENCODED_VALUE_WRAPPER_FIELD_NAME);
        adapted.write(writer);
        writer.endObject();
        writer.close();
        BSONObject object = new BasicBSONDecoder().readObject(outputStream.toByteArray());
        return object.get(PREENCODED_VALUE_WRAPPER_FIELD_NAME);
    } catch (IOException ex) {
        throw Throwables.propagate(ex);
    }
}
Also used : BSONObject(org.bson.BSONObject) BsonGenerator(de.undercouch.bson4jackson.BsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) BasicBSONDecoder(org.bson.BasicBSONDecoder)

Example 58 with BSONObject

use of org.bson.BSONObject in project graylog2-server by Graylog2.

the class BsonReader method readBsonFile.

protected List<DBObject> readBsonFile(String filename) {
    Path filePath = Paths.get(filename);
    List<DBObject> dataset = new ArrayList<>();
    try {
        ByteArrayInputStream fileBytes = new ByteArrayInputStream(Files.readAllBytes(filePath));
        BSONDecoder decoder = new BasicBSONDecoder();
        BSONObject obj;
        while ((obj = decoder.readObject(fileBytes)) != null) {
            final DBObject mongoDocument = new BasicDBObject(obj.toMap());
            dataset.add(mongoDocument);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new RuntimeException("Can not open BSON input file.", e);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        throw new RuntimeException("Can not parse BSON data.", e);
    } catch (IOException e) {
    //EOF
    }
    return dataset;
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) BSONObject(org.bson.BSONObject) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) BasicBSONDecoder(org.bson.BasicBSONDecoder) BSONDecoder(org.bson.BSONDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) BasicBSONDecoder(org.bson.BasicBSONDecoder)

Example 59 with BSONObject

use of org.bson.BSONObject in project mongo-java-driver by mongodb.

the class JSONCallback method objectDone.

@Override
public Object objectDone() {
    String name = curName();
    Object o = super.objectDone();
    if (_lastArray) {
        return o;
    }
    BSONObject b = (BSONObject) o;
    // override the object if it's a special type
    if (b.containsField("$oid")) {
        o = new ObjectId((String) b.get("$oid"));
    } else if (b.containsField("$date")) {
        if (b.get("$date") instanceof Number) {
            o = new Date(((Number) b.get("$date")).longValue());
        } else {
            SimpleDateFormat format = new SimpleDateFormat(_msDateFormat);
            format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
            o = format.parse(b.get("$date").toString(), new ParsePosition(0));
            if (o == null) {
                // try older format with no ms
                format = new SimpleDateFormat(_secDateFormat);
                format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
                o = format.parse(b.get("$date").toString(), new ParsePosition(0));
            }
        }
    } else if (b.containsField("$regex")) {
        o = Pattern.compile((String) b.get("$regex"), BSON.regexFlags((String) b.get("$options")));
    } else if (b.containsField("$ts")) {
        //Legacy timestamp format
        Integer ts = ((Number) b.get("$ts")).intValue();
        Integer inc = ((Number) b.get("$inc")).intValue();
        o = new BSONTimestamp(ts, inc);
    } else if (b.containsField("$timestamp")) {
        BSONObject tsObject = (BSONObject) b.get("$timestamp");
        Integer ts = ((Number) tsObject.get("t")).intValue();
        Integer inc = ((Number) tsObject.get("i")).intValue();
        o = new BSONTimestamp(ts, inc);
    } else if (b.containsField("$code")) {
        if (b.containsField("$scope")) {
            o = new CodeWScope((String) b.get("$code"), (DBObject) b.get("$scope"));
        } else {
            o = new Code((String) b.get("$code"));
        }
    } else if (b.containsField("$ref")) {
        o = new DBRef((String) b.get("$ref"), b.get("$id"));
    } else if (b.containsField("$minKey")) {
        o = new MinKey();
    } else if (b.containsField("$maxKey")) {
        o = new MaxKey();
    } else if (b.containsField("$uuid")) {
        o = UUID.fromString((String) b.get("$uuid"));
    } else if (b.containsField("$binary")) {
        int type = (b.get("$type") instanceof String) ? Integer.valueOf((String) b.get("$type"), 16) : (Integer) b.get("$type");
        byte[] bytes = DatatypeConverter.parseBase64Binary((String) b.get("$binary"));
        o = new Binary((byte) type, bytes);
    } else if (b.containsField("$undefined") && b.get("$undefined").equals(true)) {
        o = new BsonUndefined();
    } else if (b.containsField("$numberLong")) {
        o = Long.valueOf((String) b.get("$numberLong"));
    } else if (b.containsField("$numberDecimal")) {
        o = Decimal128.parse((String) b.get("$numberDecimal"));
    }
    if (!isStackEmpty()) {
        _put(name, o);
    } else {
        o = !BSON.hasDecodeHooks() ? o : BSON.applyDecodingHooks(o);
        setRoot(o);
    }
    return o;
}
Also used : ObjectId(org.bson.types.ObjectId) BSONObject(org.bson.BSONObject) GregorianCalendar(java.util.GregorianCalendar) DBRef(com.mongodb.DBRef) MaxKey(org.bson.types.MaxKey) BSONTimestamp(org.bson.types.BSONTimestamp) Code(org.bson.types.Code) Date(java.util.Date) CodeWScope(org.bson.types.CodeWScope) MinKey(org.bson.types.MinKey) SimpleTimeZone(java.util.SimpleTimeZone) BasicDBObject(com.mongodb.BasicDBObject) BSONObject(org.bson.BSONObject) DBObject(com.mongodb.DBObject) Binary(org.bson.types.Binary) SimpleDateFormat(java.text.SimpleDateFormat) BsonUndefined(org.bson.BsonUndefined) ParsePosition(java.text.ParsePosition)

Example 60 with BSONObject

use of org.bson.BSONObject in project querydsl by querydsl.

the class MongodbSerializer method visit.

@SuppressWarnings("unchecked")
@Override
public Object visit(Operation<?> expr, Void context) {
    Operator op = expr.getOperator();
    if (op == Ops.EQ) {
        if (expr.getArg(0) instanceof Operation) {
            Operation<?> lhs = (Operation<?>) expr.getArg(0);
            if (lhs.getOperator() == Ops.COL_SIZE || lhs.getOperator() == Ops.ARRAY_SIZE) {
                return asDBObject(asDBKey(lhs, 0), asDBObject("$size", asDBValue(expr, 1)));
            } else {
                throw new UnsupportedOperationException("Illegal operation " + expr);
            }
        } else if (expr.getArg(0) instanceof Path) {
            Path<?> path = (Path<?>) expr.getArg(0);
            Constant<?> constant = (Constant<?>) expr.getArg(1);
            return asDBObject(asDBKey(expr, 0), convert(path, constant));
        }
    } else if (op == Ops.STRING_IS_EMPTY) {
        return asDBObject(asDBKey(expr, 0), "");
    } else if (op == Ops.AND) {
        BSONObject lhs = (BSONObject) handle(expr.getArg(0));
        BSONObject rhs = (BSONObject) handle(expr.getArg(1));
        if (lhs.keySet().stream().noneMatch(rhs.keySet()::contains)) {
            lhs.putAll(rhs);
            return lhs;
        } else {
            BasicDBList list = new BasicDBList();
            list.add(handle(expr.getArg(0)));
            list.add(handle(expr.getArg(1)));
            return asDBObject("$and", list);
        }
    } else if (op == Ops.NOT) {
        // Handle the not's child
        Operation<?> subOperation = (Operation<?>) expr.getArg(0);
        Operator subOp = subOperation.getOperator();
        if (subOp == Ops.IN) {
            return visit(ExpressionUtils.operation(Boolean.class, Ops.NOT_IN, subOperation.getArg(0), subOperation.getArg(1)), context);
        } else {
            BasicDBObject arg = (BasicDBObject) handle(expr.getArg(0));
            return negate(arg);
        }
    } else if (op == Ops.OR) {
        BasicDBList list = new BasicDBList();
        list.add(handle(expr.getArg(0)));
        list.add(handle(expr.getArg(1)));
        return asDBObject("$or", list);
    } else if (op == Ops.NE) {
        Path<?> path = (Path<?>) expr.getArg(0);
        Constant<?> constant = (Constant<?>) expr.getArg(1);
        return asDBObject(asDBKey(expr, 0), asDBObject("$ne", convert(path, constant)));
    } else if (op == Ops.STARTS_WITH) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1)));
    } else if (op == Ops.STARTS_WITH_IC) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1), Pattern.CASE_INSENSITIVE));
    } else if (op == Ops.ENDS_WITH) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$"));
    } else if (op == Ops.ENDS_WITH_IC) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE));
    } else if (op == Ops.EQ_IGNORE_CASE) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE));
    } else if (op == Ops.STRING_CONTAINS) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*"));
    } else if (op == Ops.STRING_CONTAINS_IC) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*", Pattern.CASE_INSENSITIVE));
    } else if (op == Ops.MATCHES) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString()));
    } else if (op == Ops.MATCHES_IC) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString(), Pattern.CASE_INSENSITIVE));
    } else if (op == Ops.LIKE) {
        String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString();
        return asDBObject(asDBKey(expr, 0), Pattern.compile(regex));
    } else if (op == Ops.LIKE_IC) {
        String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString();
        return asDBObject(asDBKey(expr, 0), Pattern.compile(regex, Pattern.CASE_INSENSITIVE));
    } else if (op == Ops.BETWEEN) {
        BasicDBObject value = new BasicDBObject("$gte", asDBValue(expr, 1));
        value.append("$lte", asDBValue(expr, 2));
        return asDBObject(asDBKey(expr, 0), value);
    } else if (op == Ops.IN) {
        int constIndex = 0;
        int exprIndex = 1;
        if (expr.getArg(1) instanceof Constant<?>) {
            constIndex = 1;
            exprIndex = 0;
        }
        if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
            // guarded by previous check
            @SuppressWarnings("unchecked") Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
            return asDBObject(asDBKey(expr, exprIndex), asDBObject("$in", values.toArray()));
        } else {
            Path<?> path = (Path<?>) expr.getArg(exprIndex);
            Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
            return asDBObject(asDBKey(expr, exprIndex), convert(path, constant));
        }
    } else if (op == Ops.NOT_IN) {
        int constIndex = 0;
        int exprIndex = 1;
        if (expr.getArg(1) instanceof Constant<?>) {
            constIndex = 1;
            exprIndex = 0;
        }
        if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
            // guarded by previous check
            @SuppressWarnings("unchecked") Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
            return asDBObject(asDBKey(expr, exprIndex), asDBObject("$nin", values.toArray()));
        } else {
            Path<?> path = (Path<?>) expr.getArg(exprIndex);
            Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
            return asDBObject(asDBKey(expr, exprIndex), asDBObject("$ne", convert(path, constant)));
        }
    } else if (op == Ops.COL_IS_EMPTY) {
        BasicDBList list = new BasicDBList();
        list.add(asDBObject(asDBKey(expr, 0), new BasicDBList()));
        list.add(asDBObject(asDBKey(expr, 0), asDBObject("$exists", false)));
        return asDBObject("$or", list);
    } else if (op == Ops.LT) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$lt", asDBValue(expr, 1)));
    } else if (op == Ops.GT) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$gt", asDBValue(expr, 1)));
    } else if (op == Ops.LOE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$lte", asDBValue(expr, 1)));
    } else if (op == Ops.GOE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$gte", asDBValue(expr, 1)));
    } else if (op == Ops.IS_NULL) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$exists", false));
    } else if (op == Ops.IS_NOT_NULL) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$exists", true));
    } else if (op == Ops.CONTAINS_KEY) {
        Path<?> path = (Path<?>) expr.getArg(0);
        Expression<?> key = expr.getArg(1);
        return asDBObject(visit(path, context) + "." + key.toString(), asDBObject("$exists", true));
    } else if (op == MongodbOps.NEAR) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$near", asDBValue(expr, 1)));
    } else if (op == MongodbOps.GEO_WITHIN_BOX) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$geoWithin", asDBObject("$box", Arrays.asList(asDBValue(expr, 1), asDBValue(expr, 2)))));
    } else if (op == MongodbOps.NEAR_SPHERE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$nearSphere", asDBValue(expr, 1)));
    } else if (op == MongodbOps.ELEM_MATCH) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$elemMatch", asDBValue(expr, 1)));
    }
    throw new UnsupportedOperationException("Illegal operation " + expr);
}
Also used : BSONObject(org.bson.BSONObject) BasicDBList(com.mongodb.BasicDBList) BasicDBObject(com.mongodb.BasicDBObject) Collection(java.util.Collection)

Aggregations

BSONObject (org.bson.BSONObject)101 BasicBSONObject (org.bson.BasicBSONObject)49 Test (org.junit.Test)34 BasicDBObject (com.mongodb.BasicDBObject)19 SerializableString (com.fasterxml.jackson.core.SerializableString)14 SerializedString (com.fasterxml.jackson.core.io.SerializedString)14 LinkedHashMap (java.util.LinkedHashMap)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 IOException (java.io.IOException)11 DBObject (com.mongodb.DBObject)10 ArrayList (java.util.ArrayList)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)7 Map (java.util.Map)6 BasicBSONDecoder (org.bson.BasicBSONDecoder)6 BSONDecoder (org.bson.BSONDecoder)5 BSONEncoder (org.bson.BSONEncoder)5 BasicBSONEncoder (org.bson.BasicBSONEncoder)5 LazyBSONObject (org.bson.LazyBSONObject)5 SQLExpr (com.alibaba.druid.sql.ast.SQLExpr)4 BSONFileSplit (com.mongodb.hadoop.input.BSONFileSplit)4