org.bson.types.Decimal128 Java Examples

The following examples show how to use org.bson.types.Decimal128. 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: MongoPageSource.java    From presto with Apache License 2.0 6 votes vote down vote up
private void writeSlice(BlockBuilder output, Type type, Object value)
{
    if (type instanceof VarcharType) {
        type.writeSlice(output, utf8Slice(toVarcharValue(value)));
    }
    else if (type instanceof CharType) {
        type.writeSlice(output, truncateToLengthAndTrimSpaces(utf8Slice((String) value), ((CharType) type)));
    }
    else if (type.equals(OBJECT_ID)) {
        type.writeSlice(output, wrappedBuffer(((ObjectId) value).toByteArray()));
    }
    else if (type instanceof VarbinaryType) {
        if (value instanceof Binary) {
            type.writeSlice(output, wrappedBuffer(((Binary) value).getData()));
        }
        else {
            output.appendNull();
        }
    }
    else if (type instanceof DecimalType) {
        type.writeSlice(output, encodeScaledValue(((Decimal128) value).bigDecimalValue(), ((DecimalType) type).getScale()));
    }
    else {
        throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unhandled type for Slice: " + type.getTypeSignature());
    }
}
 
Example #2
Source File: BsonDecimal128Test.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Test
public void read() throws Exception {
  BsonDocument doc = new BsonDocument();
  doc.put("int", new BsonDecimal128(Decimal128.parse(Integer.toString(Integer.MAX_VALUE))));
  doc.put("long", new BsonDecimal128(new Decimal128(Long.MAX_VALUE)));
  doc.put("double", new BsonDecimal128(Decimal128.parse("12.111")));

  JsonReader reader =  Jsons.asGsonReader(doc);

  reader.beginObject();
  check(reader.nextName()).is("int");
  check(reader.peek()).is(JsonToken.NUMBER);
  check(reader.nextInt()).is(Integer.MAX_VALUE);

  check(reader.nextName()).is("long");
  check(reader.peek()).is(JsonToken.NUMBER);
  check(reader.nextLong()).is(Long.MAX_VALUE);

  check(reader.nextName()).is("double");
  check(reader.peek()).is(JsonToken.NUMBER);
  check(reader.nextDouble()).is(12.111D);

  reader.endObject();

  reader.close();
}
 
Example #3
Source File: DecimalFieldConverter.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public BsonValue toBson(final Object data) {
  if (data instanceof BigDecimal) {
    if (format.equals(Format.DECIMAL128)) {
      return new BsonDecimal128(new Decimal128((BigDecimal) data));
    }
    if (format.equals(Format.LEGACYDOUBLE)) {
      return new BsonDouble(((BigDecimal) data).doubleValue());
    }
  }

  throw new DataException(
      "Error: decimal conversion not possible when data is of type "
          + data.getClass().getName()
          + " and format is "
          + format);
}
 
Example #4
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 #5
Source File: MongoTypeUtil.java    From syncer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Object convertBsonTypes(Object o) {
	if (o instanceof Map) {
		if (((Map) o).size() == 1 && ((Map) o).containsKey("$numberDecimal")) {
			return new BigDecimal((String) ((Map) o).get("$numberDecimal"));
		}
		for (Map.Entry<String, Object> e : ((Map<String, Object>) o).entrySet()) {
			e.setValue(convertBsonTypes(e.getValue()));
		}
	} else if (o instanceof List) {
		List list = (List) o;
		for (int i = 0; i < list.size(); i++) {
			list.set(i, convertBsonTypes(list.get(i)));
		}
	} else if (o instanceof Binary) {
		return ((Binary) o).getData();
	} else if (o instanceof Decimal128) {
		return ((Decimal128) o).bigDecimalValue();
	} else if (o instanceof BsonTimestamp) {
		return convertBson((BsonValue) o);
	} else if (o instanceof ObjectId) {
		return o.toString();
	}
	return o;
}
 
Example #6
Source File: TypeAdapters.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public Decimal128 read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }
  if (in instanceof BsonReader) {
    return ((BsonReader) in).unwrap().readDecimal128();
  }
  return Decimal128.parse(in.nextString());
}
 
Example #7
Source File: TypeAdapters.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, Decimal128 value) throws IOException {
  if (value == null) {
    out.nullValue();
  } else if (out instanceof BsonWriter) {
    ((BsonWriter) out).unwrap().writeDecimal128(value);
  } else {
    out.value(value.toString());
  }
}
 
Example #8
Source File: BsonGenerator.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public void writeNumber(BigDecimal number) throws IOException {
  try {
    writer.writeDecimal128(new Decimal128(number));
  } catch (NumberFormatException e) {
    writer.writeString(number.toString());
  }
}
 
Example #9
Source File: NumbersTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Serializing big numbers which can't be stored in {@link org.bson.types.Decimal128} format.
 * They should be serialized as strings (or binary) in mongo.
 */
@Test
public void larger_than_decimal128() {
  final AdvancedRepository repo = new AdvancedRepository(context.setup());
  final ObjectId id = ObjectId.get();
  final BigInteger integer = BigInteger.valueOf(Long.MAX_VALUE).pow(4);

  try {
    new Decimal128(new BigDecimal(integer));
    fail("Should fail for " + integer);
  } catch (NumberFormatException ignore) {
    // expected
  }

  final Advanced doc = ImmutableAdvanced.builder()
          .id(id)
          .bigDecimal(new BigDecimal(integer)) // make number big
          .bigInteger(integer) // make it also big
          .atomicBoolean(new AtomicBoolean(false))
          .atomicInteger(new AtomicInteger(1))
          .atomicLong(new AtomicLong(2))
          .build();

  repo.insert(doc).getUnchecked();

  final Advanced doc2 = repo.findById(id).fetchFirst().getUnchecked().get();
  check(doc2.bigDecimal().unscaledValue()).is(integer);
  check(doc2.bigInteger()).is(integer);

}
 
Example #10
Source File: JsonObjectCodec.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeNumberDecimal(BsonWriter writer, String name, Object value, EncoderContext ctx) {
  final String decimal = ((JsonObject) value).getString(DECIMAL_FIELD);
  if (decimal.contains(".")) {
    writer.writeDecimal128(new Decimal128(new BigDecimal(decimal)));
  } else {
    writer.writeDecimal128(new Decimal128(Long.parseLong(decimal)));
  }
}
 
Example #11
Source File: DecimalFieldConverter.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Override
public BsonValue toBson(Object data) {

    if(data instanceof BigDecimal) {
        if(format.equals(Format.DECIMAL128))
            return new BsonDecimal128(new Decimal128((BigDecimal)data));

        if(format.equals(Format.LEGACYDOUBLE))
            return new BsonDouble(((BigDecimal)data).doubleValue());
    }

    throw new DataException("error: decimal conversion not possible when data is"
                    + " of type "+data.getClass().getName() + " and format is "+format);

}
 
Example #12
Source File: MongoGenerator.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public BsonDocument toDoc() {
  BsonDocument res = new BsonDocument();
  if (id != null) {
    res.append("id", new BsonInt64(id));
  }
  if (tinyint != null) {
    res.append("tinyint", new BsonInt32(tinyint));
  }
  if (bigint != null) {
    res.append("bigint", new BsonInt64(bigint));
  }
  if (bytes != null) {
    res.append("bytes", new BsonBinary(bytes));
  }
  if (varchar != null) {
    res.append("varchar", new BsonString(varchar));
  }
  if (decimal != null && MongoVersion.from(version).onOrAfter(_3_4)) {
    res.append("decimal", new BsonDecimal128(new Decimal128(decimal)));
  }
  if (aDouble != null) {
    res.append("aDouble", new BsonDouble(aDouble));
  }
  if (timestamp != null) {
    long time = timestamp.getTime();
    BsonTimestamp value = new BsonTimestamp((int) (time / _1s), (int) (time % _1s));
    res.append("timestamp", value);
  }
  return res;
}
 
Example #13
Source File: ElepyCodec.java    From elepy with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static BsonValue constructIdValue(Object value, Optional<? extends AnnotatedElement> element) {
    if (element.isPresent() && element.get().isAnnotationPresent(org.mongojack.ObjectId.class)) {
        if (value instanceof String) {
            return new BsonObjectId(new ObjectId((String) value));
        }
        if (value instanceof byte[]) {
            return new BsonObjectId(new ObjectId((byte[]) value));
        }
        if (value instanceof Byte[]) {
            final Byte[] inputArray = (Byte[]) value;
            byte[] outputArray = new byte[inputArray.length];
            for (int i = 0; i < inputArray.length; i++) {
                outputArray[i] = inputArray[i];
            }
            return new BsonObjectId(new ObjectId(outputArray));
        }
    }
    if (value == null) {
        return BsonNull.VALUE;
    } else if (value instanceof Double) {
        return new BsonDouble((Double) value);
    } else if (value instanceof String) {
        return new BsonString((String) value);
    } else if (value instanceof ObjectId) {
        return new BsonObjectId((ObjectId) value);
    } else if (value instanceof Integer) {
        return new BsonInt32((Integer) value);
    } else if (value instanceof Long) {
        return new BsonInt64((Long) value);
    } else if (value instanceof Decimal128) {
        return new BsonDecimal128((Decimal128) value);
    }
    throw new IllegalArgumentException(String.format("Unsupported ID type: %s", value.getClass()));
}
 
Example #14
Source File: BsonGenerator.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public void writeNumber(BigDecimal number) throws IOException {
  if (number == null) {
    writeNull();
  } else {
    try {
      writer.writeDecimal128(new Decimal128(number));
    } catch (NumberFormatException e) {
      writer.writeString(number.toString());
    }
  }
}
 
Example #15
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void decimal128() throws IOException {
  BsonDecimal128 value = new BsonDecimal128(new Decimal128(BigDecimal.valueOf(1.1)));
  check(Parsers.parserAt(value).getCurrentToken()).is(JsonToken.VALUE_NUMBER_FLOAT);
  check(Parsers.parserAt(value).getNumberType()).is(JsonParser.NumberType.BIG_DECIMAL);
  check(Parsers.parserAt(value).getDoubleValue()).is(1.1);
  check(Parsers.parserAt(value).getDecimalValue()).is(BigDecimal.valueOf(1.1));
}
 
Example #16
Source File: DocumentReader.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public Decimal128 readDecimal128() {
    return (Decimal128) stage().value();
}
 
Example #17
Source File: DocumentReader.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public Decimal128 readDecimal128(final String name) {
    verifyName(name);
    return readDecimal128();
}
 
Example #18
Source File: DocumentWriter.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public void writeDecimal128(final Decimal128 value) {
    state.value(value);
}
 
Example #19
Source File: DocumentWriter.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public void writeDecimal128(final String name, final Decimal128 value) {
    state.name(name).value(value);
}
 
Example #20
Source File: MongoPageSource.java    From presto with Apache License 2.0 4 votes vote down vote up
private void appendTo(Type type, Object value, BlockBuilder output)
{
    if (value == null) {
        output.appendNull();
        return;
    }

    Class<?> javaType = type.getJavaType();
    try {
        if (javaType == boolean.class) {
            type.writeBoolean(output, (Boolean) value);
        }
        else if (javaType == long.class) {
            if (type.equals(BIGINT)) {
                type.writeLong(output, ((Number) value).longValue());
            }
            else if (type.equals(INTEGER)) {
                type.writeLong(output, ((Number) value).intValue());
            }
            else if (type.equals(SMALLINT)) {
                type.writeLong(output, Shorts.checkedCast(((Number) value).longValue()));
            }
            else if (type.equals(TINYINT)) {
                type.writeLong(output, SignedBytes.checkedCast(((Number) value).longValue()));
            }
            else if (type.equals(REAL)) {
                //noinspection NumericCastThatLosesPrecision
                type.writeLong(output, floatToIntBits(((float) ((Number) value).doubleValue())));
            }
            else if (type instanceof DecimalType) {
                type.writeLong(output, encodeShortScaledValue(((Decimal128) value).bigDecimalValue(), ((DecimalType) type).getScale()));
            }
            else if (type.equals(DATE)) {
                long utcMillis = ((Date) value).getTime();
                type.writeLong(output, TimeUnit.MILLISECONDS.toDays(utcMillis));
            }
            else if (type.equals(TIME)) {
                type.writeLong(output, UTC_CHRONOLOGY.millisOfDay().get(((Date) value).getTime()));
            }
            else if (type.equals(TIMESTAMP)) {
                // TODO provide correct TIMESTAMP mapping, and respecting session.isLegacyTimestamp()
                type.writeLong(output, ((Date) value).getTime());
            }
            else if (type.equals(TIMESTAMP_WITH_TIME_ZONE)) {
                type.writeLong(output, packDateTimeWithZone(((Date) value).getTime(), UTC_KEY));
            }
            else {
                throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unhandled type for " + javaType.getSimpleName() + ":" + type.getTypeSignature());
            }
        }
        else if (javaType == double.class) {
            type.writeDouble(output, ((Number) value).doubleValue());
        }
        else if (javaType == Slice.class) {
            writeSlice(output, type, value);
        }
        else if (javaType == Block.class) {
            writeBlock(output, type, value);
        }
        else {
            throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unhandled type for " + javaType.getSimpleName() + ":" + type.getTypeSignature());
        }
    }
    catch (ClassCastException ignore) {
        // TODO remove (fail clearly), or hide behind a toggle
        // returns null instead of raising exception
        output.appendNull();
    }
}
 
Example #21
Source File: TypeExpressionsTest.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Test
public void testToDecimal() {
    checkMinServerVersion(4.0);
    assertAndCheckDocShape("{$toDecimal: true }", toDecimal(value(true)), new Decimal128(1));
}
 
Example #22
Source File: BsonWriter.java    From immutables with Apache License 2.0 4 votes vote down vote up
private com.google.gson.stream.JsonWriter value(Decimal128 decimal) {
  delegate.writeDecimal128(decimal);
  return this;
}
 
Example #23
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 #24
Source File: JsonObjectCodecTest.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
@Test
public void readDocument_supportNumberDecimal() {
  JsonObjectCodec codec = new JsonObjectCodec(options);

  String v = "24.56";

  BsonDocument bson = new BsonDocument();
  BsonDocument numberDecimal = new BsonDocument();
  numberDecimal.append(JsonObjectCodec.DECIMAL_FIELD, new BsonDecimal128(new Decimal128(new BigDecimal(v))));
  bson.append("test", numberDecimal);

  BsonDocumentReader reader = new BsonDocumentReader(bson);

  JsonObject result = codec.readDocument(reader, DecoderContext.builder().build());

  String decimalValue = result.getJsonObject("test").getString(JsonObjectCodec.DECIMAL_FIELD);

  assertEquals(v, decimalValue);
}
 
Example #25
Source File: JsonObjectCodec.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
@Override
protected Object readNumberDecimal(BsonReader reader, DecoderContext ctx) {
  final Decimal128 decimal128 = reader.readDecimal128();
  return decimal128.toString();
}
 
Example #26
Source File: BigDecimalToDecimal128Converter.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@Override
public Decimal128 convert(BigDecimal bigDecimal) {
    return new Decimal128(bigDecimal);
}
 
Example #27
Source File: Decimal128ToBigDecimalConverter.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@Override
public BigDecimal convert(Decimal128 decimal128) {
    return decimal128.bigDecimalValue();
}
 
Example #28
Source File: FinanceStatisticsController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 法币/币币  总成交量/总成交额   区间:[startDate,endDate]
 * <p>
 * 此处仅按照币种区分 ,币币不按照交易对区分
 *
 * @param types
 * @param startDate
 * @param endDate
 * @param unit
 * @return
 */
@PostMapping("turnover-all")
@AccessLog(module = AdminModule.FINANCE, operation = "法币/币币  总成交量/总成交额")
public MessageResult getResult(
        String[] types,
        @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") Date startDate,
        @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") Date endDate,
        String unit) {

    Assert.notNull(types, "type must not be null ");
    if (endDate == null) {
        endDate = DateUtil.getDate(new Date(), 1);
    }

    ProjectionOperation projectionOperation = Aggregation.project("date", "type", "unit", "amount").andExclude("_id");

    List<Criteria> criterias = new ArrayList<>();

    if (startDate != null) {
        criterias.add(Criteria.where("date").gte(startDate));
    }

    criterias.add(Criteria.where("date").lte(endDate));

    if (!StringUtils.isEmpty(unit)) {
        criterias.add(Criteria.where("unit").is(unit));
    }

    MatchOperation matchOperation = Aggregation.match(
            Criteria.where("type").in(types)
                    .andOperator(criterias.toArray(new Criteria[criterias.size()]))

    );

    GroupOperation groupOperation = Aggregation.group("type", "unit").sum("amount").as("amount");

    Aggregation aggregation = Aggregation.newAggregation(projectionOperation, matchOperation, groupOperation);

    AggregationResults<Map> aggregationResults = this.mongoTemplate.aggregate(aggregation, "turnover_statistics", Map.class);

    List<Map> list = aggregationResults.getMappedResults();

    Set<String> units = new HashSet<>();

    for (Map map : list) {
        /* map.put("date",date);*/
        map.put("amount", ((Decimal128) map.get("amount")).bigDecimalValue());

        units.add(map.get("unit").toString());

        logger.info("成交信息:{}", map);
    }

    return MessageResult.getSuccessInstance(messageSource.getMessage("SUCCESS"), list);
}
 
Example #29
Source File: BigDecimalToDecimal128Converter.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@Override
public Decimal128 convert(BigDecimal bigDecimal) {
    return new Decimal128(bigDecimal);
}
 
Example #30
Source File: Decimal128ToBigDecimalConverter.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@Override
public BigDecimal convert(Decimal128 decimal128) {
    return decimal128.bigDecimalValue();
}