org.bson.BsonRegularExpression Java Examples

The following examples show how to use org.bson.BsonRegularExpression. 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: RemoteMongoCollectionExamples.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void RemoteMongoCollection_count_Bson_RemoteCountOptions() {
    // Get the Atlas client.
    RemoteMongoClient mongoClient = appClient.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas");
    RemoteMongoDatabase db = mongoClient.getDatabase("video");
    RemoteMongoCollection<Document> movieDetails = db.getCollection("movieDetails");

    // Count all documents where title matches a regex up to a limit
    movieDetails.count(
            new Document().append("title", new BsonRegularExpression("^A")),
            new RemoteCountOptions().limit(25)).addOnCompleteListener(new OnCompleteListener<Long>() {
        @Override
        public void onComplete(@android.support.annotation.NonNull Task<Long> task) {
            if (!task.isSuccessful()) {
                Log.e(TAG, "Count failed", task.getException());
                return;
            }
            Log.i(TAG, "Count is " + task.getResult());
        }
    });

}
 
Example #2
Source File: BsonTypeMap.java    From morphia with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the map
 */
public BsonTypeMap() {
    map.put(List.class, BsonType.ARRAY);
    map.put(Binary.class, BsonType.BINARY);
    map.put(Boolean.class, BsonType.BOOLEAN);
    map.put(Date.class, BsonType.DATE_TIME);
    map.put(BsonDbPointer.class, BsonType.DB_POINTER);
    map.put(Document.class, BsonType.DOCUMENT);
    map.put(Double.class, BsonType.DOUBLE);
    map.put(Integer.class, BsonType.INT32);
    map.put(Long.class, BsonType.INT64);
    map.put(Decimal128.class, BsonType.DECIMAL128);
    map.put(MaxKey.class, BsonType.MAX_KEY);
    map.put(MinKey.class, BsonType.MIN_KEY);
    map.put(Code.class, BsonType.JAVASCRIPT);
    map.put(CodeWithScope.class, BsonType.JAVASCRIPT_WITH_SCOPE);
    map.put(ObjectId.class, BsonType.OBJECT_ID);
    map.put(BsonRegularExpression.class, BsonType.REGULAR_EXPRESSION);
    map.put(String.class, BsonType.STRING);
    map.put(Symbol.class, BsonType.SYMBOL);
    map.put(BsonTimestamp.class, BsonType.TIMESTAMP);
    map.put(BsonUndefined.class, BsonType.UNDEFINED);
}
 
Example #3
Source File: RegexExpression.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeStartDocument(getOperation());
    ExpressionCodec.writeNamedExpression(mapper, writer, "input", input, encoderContext);
    ExpressionCodec.writeNamedValue(mapper, writer, "regex", new BsonRegularExpression(regex), encoderContext);
    ExpressionCodec.writeNamedValue(mapper, writer, "options", options, encoderContext);
    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #4
Source File: TodoListActivity.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
private Task<List<TodoItem>> getItemsWithRegexFilter(final String regex) {
  return items.sync().find(
      new Document(
          TodoItem.Fields.TASK,
          new Document().append("$regex",
              new BsonRegularExpression(regex)).append("$options", "i")))
      .into(new ArrayList<>());
}
 
Example #5
Source File: RegexFilter.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext context) {
    writer.writeStartDocument(field(mapper));
    if (isNot()) {
        writer.writeStartDocument("$not");
    }
    ExpressionCodec.writeNamedValue(mapper, writer, "$regex", new BsonRegularExpression(regex), context);
    ExpressionCodec.writeNamedValue(mapper, writer, "$options", options, context);
    if (isNot()) {
        writer.writeEndDocument();
    }
    writer.writeEndDocument();
}
 
Example #6
Source File: JacksonCodecsTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Test that regular expression is correctly encoded
 */
@Test
public void regex() {
  final ObjectMapper mapper = new ObjectMapper().registerModule(new BsonModule());
  final CodecRegistry registry = JacksonCodecs.registryFromMapper(mapper);

  Consumer<Bson> validate = bson -> {
    BsonDocument doc = bson.toBsonDocument(BsonDocument.class, registry);
    check(doc.get("a")).is(new BsonRegularExpression("a.*b"));
  };

  validate.accept(Filters.eq("a", Pattern.compile("a.*b")));
  validate.accept(Filters.regex("a", Pattern.compile("a.*b")));
  validate.accept(Filters.regex("a", "a.*b"));
}
 
Example #7
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
public void regexpPattern() throws IOException {
  BsonRegularExpression value = new BsonRegularExpression("abc");
  check(Jsons.readerAt(value).peek()).is(JsonToken.STRING);
  check(Jsons.readerAt(value).nextString()).is("abc");
  check(Jsons.readerAt(new BsonRegularExpression(".*")).nextString()).is(".*");
}
 
Example #8
Source File: TypeAdapters.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, Pattern value) throws IOException {
  if (value == null) {
    out.nullValue();
  } else if (out instanceof BsonWriter) {
    ((BsonWriter) out).unwrap()
            .writeRegularExpression(new BsonRegularExpression(value.pattern()));
  } else {
    out.value(value.toString());
  }
}
 
Example #9
Source File: MongoQueryUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static BsonDocument getQueryObject(String[] fieldArr, BsonArray paramArray) {

		BsonArray orQueries = new BsonArray();
		for (String field : fieldArr) {
			Iterator<BsonValue> paramIterator = paramArray.iterator();
			BsonArray pureStringParamArray = new BsonArray();
			while (paramIterator.hasNext()) {
				BsonValue param = paramIterator.next();
				if (param instanceof BsonRegularExpression) {
					BsonDocument regexQuery = new BsonDocument(field, new BsonDocument("$regex", param));
					orQueries.add(regexQuery);
				} else {
					pureStringParamArray.add(param);
				}
			}
			if (pureStringParamArray.size() != 0) {
				BsonDocument stringInQueries = new BsonDocument(field, new BsonDocument("$in", pureStringParamArray));
				orQueries.add(stringInQueries);
			}
		}
		if (orQueries.size() != 0) {
			BsonDocument queryObject = new BsonDocument();
			queryObject.put("$or", orQueries);
			return queryObject;
		} else {
			return null;
		}
	}
 
Example #10
Source File: MongoQueryUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static BsonValue converseType(String value) {
	String[] valArr = value.split("\\^");
	if (valArr.length != 2) {
		return new BsonString(value);
	}
	try {
		String type = valArr[1].trim();
		if (type.equals("int")) {
			return new BsonInt32(Integer.parseInt(valArr[0]));
		} else if (type.equals("long")) {
			return new BsonInt64(Long.parseLong(valArr[0]));
		} else if (type.equals("double")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("boolean")) {
			return new BsonBoolean(Boolean.parseBoolean(valArr[0]));
		} else if (type.equals("regex")) {
			return new BsonRegularExpression("^" + valArr[0] + "$");
		} else if (type.equals("float")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("dateTime")) {
			BsonDateTime time = MongoQueryService.getTimeMillis(valArr[0]);
			if (time != null)
				return time;
			return new BsonString(value);
		} else {
			return new BsonString(value);
		}
	} catch (NumberFormatException e) {
		return new BsonString(value);
	}
}
 
Example #11
Source File: MongoQueryUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static BsonDocument getQueryObject(String[] fieldArr, BsonArray paramArray) {

		BsonArray orQueries = new BsonArray();
		for (String field : fieldArr) {
			Iterator<BsonValue> paramIterator = paramArray.iterator();
			BsonArray pureStringParamArray = new BsonArray();
			while (paramIterator.hasNext()) {
				BsonValue param = paramIterator.next();
				if (param instanceof BsonRegularExpression) {
					BsonDocument regexQuery = new BsonDocument(field, new BsonDocument("$regex", param));
					orQueries.add(regexQuery);
				} else {
					pureStringParamArray.add(param);
				}
			}
			if (pureStringParamArray.size() != 0) {
				BsonDocument stringInQueries = new BsonDocument(field, new BsonDocument("$in", pureStringParamArray));
				orQueries.add(stringInQueries);
			}
		}
		if (orQueries.size() != 0) {
			BsonDocument queryObject = new BsonDocument();
			queryObject.put("$or", orQueries);
			return queryObject;
		} else {
			return null;
		}
	}
 
Example #12
Source File: MongoQueryUtil.java    From epcis with Apache License 2.0 5 votes vote down vote up
static BsonValue converseType(String value) {
	String[] valArr = value.split("\\^");
	if (valArr.length != 2) {
		return new BsonString(value);
	}
	try {
		String type = valArr[1].trim();
		if (type.equals("int")) {
			return new BsonInt32(Integer.parseInt(valArr[0]));
		} else if (type.equals("long")) {
			return new BsonInt64(Long.parseLong(valArr[0]));
		} else if (type.equals("double")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("boolean")) {
			return new BsonBoolean(Boolean.parseBoolean(valArr[0]));
		} else if (type.equals("regex")) {
			return new BsonRegularExpression("^" + valArr[0] + "$");
		} else if (type.equals("float")) {
			return new BsonDouble(Double.parseDouble(valArr[0]));
		} else if (type.equals("dateTime")) {
			BsonDateTime time = MongoQueryService.getTimeMillis(valArr[0]);
			if (time != null)
				return time;
			return new BsonString(value);
		} else {
			return new BsonString(value);
		}
	} catch (NumberFormatException e) {
		return new BsonString(value);
	}
}
 
Example #13
Source File: WritecontextTest.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Test
public void parseBsonArrayWithValues() throws IOException {

    BsonValue a = new BsonString("stest");
    BsonValue b = new BsonDouble(111);
    BsonValue c = new BsonBoolean(true);

    BsonDocument document = new BsonDocument()
            .append("int32", new BsonInt32(12))
            .append("int64", new BsonInt64(77L))
            .append("bo\"olean", new BsonBoolean(true))
            .append("date", new BsonDateTime(new Date().getTime()))
            .append("double", new BsonDouble(12.3))
            .append("string", new BsonString("pinpoint"))
            .append("objectId", new BsonObjectId(new ObjectId()))
            .append("code", new BsonJavaScript("int i = 10;"))
            .append("codeWithScope", new BsonJavaScriptWithScope("int x = y", new BsonDocument("y", new BsonInt32(1))))
            .append("regex", new BsonRegularExpression("^test.*regex.*xyz$", "big"))
            .append("symbol", new BsonSymbol("wow"))
            .append("timestamp", new BsonTimestamp(0x12345678, 5))
            .append("undefined", new BsonUndefined())
            .append("binary1", new BsonBinary(new byte[]{(byte) 0xe0, 0x4f, (byte) 0xd0, 0x20}))
            .append("oldBinary", new BsonBinary(BsonBinarySubType.OLD_BINARY, new byte[]{1, 1, 1, 1, 1}))
            .append("arrayInt", new BsonArray(Arrays.asList(a, b, c, new BsonInt32(7))))
            .append("document", new BsonDocument("a", new BsonInt32(77)))
            .append("dbPointer", new BsonDbPointer("db.coll", new ObjectId()))
            .append("null", new BsonNull())
            .append("decimal128", new BsonDecimal128(new Decimal128(55)));

    BasicDBObject query = new BasicDBObject();
    query.put("ComplexBson", document);

    logger.debug("document:{}", document);

    NormalizedBson stringStringValue = MongoUtil.parseBson(new Object[]{query}, true);
    logger.debug("val:{}", stringStringValue);

    List list = objectMapper.readValue("[" + stringStringValue.getNormalizedBson() + "]", List.class);
    Assert.assertEquals(list.size(), 1);
    Map<String, ?> query1Map = (Map<String, ?>) list.get(0);

    checkValue(query1Map);
}
 
Example #14
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 4 votes vote down vote up
@Test
void regexpPattern() throws IOException {
  check(Parsers.parserAt(new BsonRegularExpression("abc")).getText()).is("abc");
  check(Parsers.parserAt(new BsonRegularExpression(".*")).getText()).is(".*");
}
 
Example #15
Source File: DocumentReader.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public BsonRegularExpression readRegularExpression() {
    return (BsonRegularExpression) stage().value();
}
 
Example #16
Source File: DocumentReader.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public BsonRegularExpression readRegularExpression(final String name) {
    verifyName(name);
    return readRegularExpression();
}
 
Example #17
Source File: DocumentWriter.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public void writeRegularExpression(final BsonRegularExpression regularExpression) {
    state.value(regularExpression);
}
 
Example #18
Source File: DocumentWriter.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public void writeRegularExpression(final String name, final BsonRegularExpression regularExpression) {
    state.name(name).value(regularExpression);
}
 
Example #19
Source File: MongoPersistenceOperationsSelectionProvider.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private Document filterByPidPrefix(final CharSequence namespace) {
    final String pidRegex = String.format("^%s%s:", settings.getPersistenceIdPrefix(), namespace);
    return new Document(PID, new BsonRegularExpression(pidRegex));
}