private RealVector unmarshall(Document doc, int limit) { if (!metadata.isBinary()) { throw new UnsupportedOperationException("Can't consume non-binary models."); } try { final Binary binary = doc.get(VECTOR_FIELD_NAME, Binary.class); final byte[] b = binary.getData(); if (metadata.getLoaderId().equalsIgnoreCase("legacy")) { return BinaryCodecs.legacyUnmarshall(b, limit, metadata.isSparse(), metadata.getDimensions()); } else { return BinaryCodecs.unmarshall(b, metadata.isSparse(), metadata.getDimensions()); } } catch (Exception e) { logger.error("Error unmarshalling vector", e); } return null; }
public static Literal getLobLiteral(Object inputValue, String dataType, Connection connection) throws SQLException{ Literal literal = null; if(connection==null){ literal = new NullLiteral(); }else{ if(SqlColumnType.BLOB.equalsIgnoreCase(dataType)){ literal= new BlobLiteral(); Blob blob = connection.createBlob(); Binary objArray = (Binary) inputValue; blob.setBytes(1, objArray.getData()); literal.setLiteralValue(blob); }else if(SqlColumnType.CLOB.equalsIgnoreCase(dataType)){ literal = new ClobLiteral(); Clob clob = connection.createClob(); clob.setString(1, String.valueOf(inputValue)); literal.setLiteralValue(clob); } } return literal; }
private BsonTest getObject() { BsonTest bsonTest = new BsonTest(); bsonTest.setTestDouble(20.00); bsonTest.setTestString("测试一下"); byte[] bytes = new byte[3]; bytes[0] = 3; bytes[1] = 4; bytes[2] = 1; bsonTest.setTestBinary(new Binary(BsonBinarySubType.USER_DEFINED, bytes)); ArrayList<BsonTest> testArray = new ArrayList<BsonTest>(); BsonTest test1 = new BsonTest(); test1.setTestDouble(30.00); testArray.add(test1); bsonTest.setTestArray(testArray); bsonTest.setBsonTest(test1); bsonTest.setTestObjectId(new ObjectId()); bsonTest.setTestStringObjectId("59074307568fad36808ff0c5"); bsonTest.setTestBoolean(true); bsonTest.setTestDate(new Date()); bsonTest.setTestNull(null); bsonTest.setTestInt(2333); bsonTest.setTestLong(2222L); return bsonTest; }
private BsonTest getObject() { BsonTest bsonTest = new BsonTest(); bsonTest.setTestDouble(20.00); bsonTest.setTestString("测试一下"); byte[] bytes = new byte[3]; bytes[0] = 3; bytes[1] = 4; bytes[2] = 1; bsonTest.setTestBinary(new Binary(BsonBinarySubType.USER_DEFINED, bytes)); ArrayList<BsonTest> testArray = new ArrayList<BsonTest>(); BsonTest test1 = new BsonTest(); test1.setTestDouble(30.00); testArray.add(test1); bsonTest.setTestArray(testArray); bsonTest.setBsonTest(test1); ObjectId testObjectId = new ObjectId(); bsonTest.setTestObjectId(testObjectId); bsonTest.setTestStringObjectId(testObjectId.toHexString()); bsonTest.setTestBoolean(true); bsonTest.setTestDate(new Date()); bsonTest.setTestNull(null); bsonTest.setTestInt(2333); bsonTest.setTestLong(2222L); return bsonTest; }
@Before public void setUp() { tenant = tenantRepository.findByDomainName("konker"); application = applicationRepository.findByTenantAndName(tenant.getId(), "konker"); otherApplication = applicationRepository.findByTenantAndName(tenant.getId(), "smartffkonker"); deviceModel1 = DeviceModel.builder() .tenant(tenant) .application(application) .name("air conditioner") .guid("be68c474-b961-4974-829d-daeed9e4142b") .build(); deviceModelRepository.save(deviceModel1); DeviceFirmware deviceFirmware = DeviceFirmware.builder() .tenant(tenant) .application(application) .deviceModel(deviceModel1) .firmware(new Binary(firmwareBinary)) .uploadDate(Instant.now()) .version("0.1.0") .build(); deviceFirmwareRepository.save(deviceFirmware); }
@Test public void shouldSave() { DeviceFirmware newFirmware = DeviceFirmware.builder() .tenant(tenant) .application(application) .deviceModel(deviceModel1) .version("0.2.0") .firmware(new Binary(firmwareBinary)) .build(); ServiceResponse<DeviceFirmware> response = subject.save(tenant, application, newFirmware); assertThat(response, isResponseOk()); assertThat(response.getResult(), notNullValue()); DeviceFirmware firmwareFromDB = deviceFirmwareRepository.findUnique(tenant.getId(), application.getName(), deviceModel1.getId(), "0.2.0"); assertThat(firmwareFromDB.getVersion(), is("0.2.0")); assertThat(firmwareFromDB.getFirmware().getData(), is(firmwareBinary)); assertThat(firmwareFromDB.getUploadDate(), notNullValue()); }
@Override public ByteBuffer readBytes(ByteBuffer old) throws IOException { jumpToNextField(); try { Object next = iteratorStack.peek().next(); if (next == null) { return null; } else if (next instanceof Binary) { return ByteBuffer.wrap(((Binary) next).getData()); } else { return ByteBuffer.wrap((byte[]) next); } } finally { finishRead(); } }
private String getDataType(Object value) { if (value instanceof Integer) { return TypeFacility.RUNTIME_NAMES.INTEGER; } else if (value instanceof Double) { return TypeFacility.RUNTIME_NAMES.DOUBLE; } else if (value instanceof Boolean) { return TypeFacility.RUNTIME_NAMES.BOOLEAN; } else if (value instanceof Long) { return TypeFacility.RUNTIME_NAMES.LONG; } else if (value instanceof String) { return TypeFacility.RUNTIME_NAMES.STRING; } else if (value instanceof Date) { return TypeFacility.RUNTIME_NAMES.TIMESTAMP; } else if (value instanceof Binary || value instanceof byte[]) { return TypeFacility.RUNTIME_NAMES.VARBINARY; } else { return TypeFacility.RUNTIME_NAMES.OBJECT; } }
@SuppressWarnings("unchecked") @Test public void testWithDocument() { MongoDatabase db = connect(); BytePojo pojo = insert(db); MongoCollection<Document> coll = db.getCollection(COLL_NAME); Document doc = coll.find().first(); assertThat(doc).hasSize(8); assertThat(doc.get("_id")).isEqualTo(pojo.getId()); assertThat(doc.get("scalarPrimitive")).isEqualTo((int) pojo.getScalarPrimitive()); assertThat(doc.get("scalar")).isEqualTo(pojo.getScalar().intValue()); assertThat(doc.get("arrayPrimitive")) .isEqualTo(new Binary(new byte[] { 3, 4, 5 })); assertThat(doc.get("array")).isEqualTo(new Binary(new byte[] { 6, 7, 8 })); assertThat((List<Integer>) doc.get("list")).containsExactly(10, 11); assertThat((List<Integer>) doc.get("set")).containsOnly(12, 13); assertThat((Map<String, Integer>) doc.get("map")).containsOnly( MapEntry.entry("one", 1), MapEntry.entry("two", 2), MapEntry.entry("three", 3), MapEntry.entry("null", null)); }
@Nullable @Override public byte[] fromDb(@Nullable final Object dbValue) throws MapperException { if (dbValue == null) { return null; } if (dbValue instanceof Binary) { final Binary binary = (Binary) dbValue; return binary.getData(); } if (dbValue instanceof byte[]) { final byte[] bytes = (byte[]) dbValue; return bytes; } throw new MapperException("Bytes expected, " + "got a value of type: " + dbValue.getClass().getCanonicalName()); }
@Test @UsingDataSet(loadStrategy = LoadStrategyEnum.DELETE_ALL) public void shouldInsertOneDocumentWithBinaryData() throws IOException { // given final byte[] bytes = new byte[]{0,1,2,3,4,5,6,7,9}; final Foo foo = new FooBuilder().withStringField("jdoe").withPrimitiveIntField(42) .withEnumFoo(EnumFoo.FOO).withBytes(bytes).build(); // when fooCollection.add(foo); // then assertThat(foo.getId()).isNotNull(); assertThat( getMongoClient().getDatabase(DATABASE_NAME).getCollection(getCollectionName()).count()) .isEqualTo(1); final Document createdDoc = getMongoClient().getDatabase(DATABASE_NAME) .getCollection(getCollectionName()).find().first(); final Binary retrievedBinaryContent = (Binary) createdDoc.get("raw_content"); assertThat(retrievedBinaryContent).isNotNull(); assertThat(retrievedBinaryContent.getData()).as("Check insertion of byte[]").isEqualTo(bytes); }
@Test @UsingDataSet(loadStrategy = LoadStrategyEnum.DELETE_ALL) public void shouldInsertDocumentWithBinaryField() throws IOException { // given // when final Foo foo = new FooBuilder().withId(new ObjectId("54c28b0b0f2dacc85ede5286")) .withBytes(new byte[]{1,2,3,4}).build(); fooCollection.add(foo); // then assertThat( getMongoClient().getDatabase(DATABASE_NAME).getCollection(getCollectionName()).count()) .isEqualTo(1); final Document createdDoc = getMongoClient().getDatabase(DATABASE_NAME) .getCollection(getCollectionName()).find().first(); assertThat(createdDoc.get("raw_content")).isNotNull().isEqualTo(new Binary(new byte[]{1,2,3,4})); final Foo foundFoo = fooCollection.all().first(); assertThat(foundFoo.getBytes()).isNotNull().isEqualTo(new byte[]{1,2,3,4}); }
public SnapImag(Object snapId, String url, BufferedImage imag) { _dbo = new BasicDBObject(); _dbo.put(_idField, snapId); _dbo.put(_urlField, url); _dbo.put(_widthField, imag.getWidth()); _dbo.put(_heightField, imag.getHeight()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(imag, "jpg", baos); baos.flush(); } catch (IOException e) { throw new IllegalStateException("Could not serialize image", e); } byte[] bytes = baos.toByteArray(); _dbo.put(_bytesField, new Binary(bytes)); }
public final static AliveStatus findAliveStatus( DBCollection coll, byte[] id, Date now) { BasicDBObject q = new BasicDBObject(); q.put(_idField, new Binary(id)); BasicDBObject f = new BasicDBObject(); f.put(_dyingDateField, 1); f.put(_deadDateField, 1); DBObject dbo = coll.findOne(q, f); if (dbo != null) { SummResult result = new SummResult(dbo); return result.getAliveStatus(now); } else { // not found at all return AliveStatus.Dead; } }
public SnapThumb(Object snapId, int kindId, BufferedImage imag) { _dbo = new BasicDBObject(); _dbo.put(_snapIdField, snapId); _dbo.put(_kindIdField, kindId); _dbo.put(_widthField, imag.getWidth()); _dbo.put(_heightField, imag.getHeight()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(imag, "jpg", baos); baos.flush(); } catch (IOException e) { throw new IllegalStateException("Could not serialize image", e); } byte[] bytes = baos.toByteArray(); _dbo.put(_bytesField, new Binary(bytes)); }
public Paths( byte[] id, Date date, DBObject rootItem, BasicDBList autoItemsList, DBObject patternEntityItemsMap, DBObject patternGroupItemsMap, DBObject topicGroupItemsMap) { _dbo = new BasicDBObject(); _dbo.put(_idField, new Binary(id)); _dbo.put(_dateField, date); _dbo.put(_rootItemField, rootItem); _dbo.put(_autoItemsListField, autoItemsList); _dbo.put(_patternEntityItemsMapField, patternEntityItemsMap); _dbo.put(_patternGroupItemsMapField, patternGroupItemsMap); _dbo.put(_topicGroupItemsMapField, topicGroupItemsMap); }
public final static AliveStatus findAliveStatus( DBCollection coll, byte[] idData, Date now, Period period) { BasicDBObject q = new BasicDBObject(); q.put(_idField, new Binary(idData)); BasicDBObject f = new BasicDBObject(); f.put(_dateField, 1); DBObject dbo = coll.findOne(q, f); if (dbo != null) { return getAliveStatus(dbo, period, now); } else { // not found at all return AliveStatus.Dead; } }
private MongoBlock fetchBlock(Integer blockNumber, boolean createIfNotExist) throws IOException { MongoCollection<Document> c = mongoDirectory.getBlocksCollection(); Document query = new Document(); query.put(MongoDirectory.FILE_NUMBER, fileNumber); query.put(MongoDirectory.BLOCK_NUMBER, blockNumber); Document result = c.find(query).first(); byte[] bytes; if (result != null) { bytes = ((Binary) result.get(MongoDirectory.BYTES)).getData(); return new MongoBlock(this, blockNumber, bytes); } if (createIfNotExist) { bytes = new byte[blockSize]; MongoBlock mongoBlock = new MongoBlock(this, blockNumber, bytes); storeBlock(mongoBlock); return mongoBlock; } return null; }
public static void storeBlock(MongoBlock mongoBlock) { // System.out.println("Store: " + mongoBlock.getBlockNumber()); MongoCollection<Document> c = mongoBlock.mongoFile.mongoDirectory.getBlocksCollection(); Document query = new Document(); query.put(MongoDirectory.FILE_NUMBER, mongoBlock.mongoFile.fileNumber); query.put(MongoDirectory.BLOCK_NUMBER, mongoBlock.blockNumber); Document object = new Document(); object.put(MongoDirectory.FILE_NUMBER, mongoBlock.mongoFile.fileNumber); object.put(MongoDirectory.BLOCK_NUMBER, mongoBlock.blockNumber); object.put(MongoDirectory.BYTES, new Binary(mongoBlock.bytes)); c.replaceOne(query, object, new UpdateOptions().upsert(true)); }
@Override public void writeBinaryData(final Binary binary) { checkPreconditions("writeBinaryData", State.VALUE); buffer.write(BSONType.BINARY.getValue()); writeCurrentName(); int totalLen = binary.length(); if (binary.getType() == BSONBinarySubType.OldBinary.getValue()) { totalLen += 4; } buffer.writeInt(totalLen); buffer.write(binary.getType()); if (binary.getType() == BSONBinarySubType.OldBinary.getValue()) { buffer.writeInt(totalLen - 4); } buffer.write(binary.getData()); setState(getNextState()); }
protected static int mongoToKettleType( Object fieldValue ) { if ( fieldValue == null ) { return ValueMetaInterface.TYPE_STRING; } if ( fieldValue instanceof Symbol || fieldValue instanceof String || fieldValue instanceof Code || fieldValue instanceof ObjectId || fieldValue instanceof MinKey || fieldValue instanceof MaxKey ) { return ValueMetaInterface.TYPE_STRING; } else if ( fieldValue instanceof Date ) { return ValueMetaInterface.TYPE_DATE; } else if ( fieldValue instanceof Number ) { // try to parse as an Integer try { Integer.parseInt( fieldValue.toString() ); return ValueMetaInterface.TYPE_INTEGER; } catch ( NumberFormatException e ) { return ValueMetaInterface.TYPE_NUMBER; } } else if ( fieldValue instanceof Binary ) { return ValueMetaInterface.TYPE_BINARY; } else if ( fieldValue instanceof BSONTimestamp ) { return ValueMetaInterface.TYPE_INTEGER; } return ValueMetaInterface.TYPE_STRING; }
/** * deserializes DBBinary/byte[] to object * * @param data the data to read * @param zipped true if the data is compressed * @return the deserialized object * @throws IOException thrown when an error is encountered reading the data * @throws ClassNotFoundException thrown if the Class definition can not be found */ public static Object deserialize(final Object data, final boolean zipped) throws IOException, ClassNotFoundException { final ByteArrayInputStream bais; if (data instanceof Binary) { bais = new ByteArrayInputStream(((Binary) data).getData()); } else { bais = new ByteArrayInputStream((byte[]) data); } InputStream is = bais; try { if (zipped) { is = new GZIPInputStream(is); } final ObjectInputStream ois = new ObjectInputStream(is); return ois.readObject(); } finally { is.close(); } }
@Override public Object handle(Request request, Response response) throws Exception { QueryParamsMap params = request.queryMap(); Set<String> headers = request.headers(); if(headers.contains("Host") && params.hasKey("u") && params.hasKey("t") && params.hasKey("a")) { Document r = (Document) collection.find( new Document("username", params.value("u")) ).limit(1).first(); if(r != null) { String passwordHash = DatatypeConverter.printHexBinary(((Binary) r.get("password")).getData()); String authToken = DatatypeConverter.printHexBinary(MessageDigest.getInstance("md5").digest((passwordHash.toLowerCase() + params.value("t")).getBytes())); if(params.value("a").equalsIgnoreCase(authToken)) { WAILUser user = WAILUser.fromDocument(r); WAILToken token = new WAILToken(user); String host = request.headers("Host"); StringBuilder sb = new StringBuilder("OK\n"); sb.append(token.getString()); sb.append('\n'); sb.append(String.format("http://%s/api/dstatus\n", host)); sb.append(String.format("http://%s/api/dscrobble\n", host)); return sb.toString(); } } } return "BADAUTH\n"; }
@SuppressWarnings("unchecked") public static WAILSession restore(byte[] id) { WAILSession session = new WAILSession(); Document r = (Document) collection.find(new Document("sessions.id", id)).limit(1).first(); if(r == null) { session.remove(); return null; } for(Map item : ((List<Map>) r.get("sessions"))) { if(Arrays.equals(((Binary) item.get("id")).getData(), id)) { session.id = id; session.expireDate = (Date) item.get("expires"); break; } } if(new Date().after(session.expireDate)) { session.remove(); return null; } session.user = WAILUser.fromDocument(r); session.renew(); return session; }
public List<Message> get(OfflineMessagesMeta meta) { Document query = new Document("topic", meta.topic).append("msgid", new Document().append("$gt", meta.start).append("$lte", meta.end)); FindIterable<Document> list = this.mongo.find(query).sort(Sorts.ascending("msgid")); List<Message> messages = new ArrayList<>(); for (Document doc : list) { messages.add(new Message(doc.getString("topic"), doc.getLong("msgid"), ((Binary) doc.get("msg")).getData())); } return messages; }
@SuppressWarnings("unchecked") private void deserializeAttributes(Document sessionWrapper, Session session) { Object sessionAttributes = sessionWrapper.get(ATTRIBUTES); byte[] attributesBytes = (sessionAttributes instanceof Binary ? ((Binary) sessionAttributes).getData() : (byte[]) sessionAttributes); Map<String, Object> attributes = (Map<String, Object>) this.deserializer.convert(attributesBytes); for (Map.Entry<String, Object> entry : attributes.entrySet()) { session.setAttribute(entry.getKey(), entry.getValue()); } }
public static void checkBsonTest(BsonTest bsonTest) { Assert.assertEquals(20.99, bsonTest.getTestDouble(), 0); Assert.assertEquals("testStringV", bsonTest.getTestString()); Assert.assertNotNull(bsonTest.getTestArray()); for (BsonTest innerTestObj : bsonTest.getTestArray()) { Assert.assertEquals(20.777, innerTestObj.getTestDouble(), 0); Assert.assertNull(innerTestObj.getTestString()); } Assert.assertNotNull(bsonTest.getBsonTest()); BsonTest testHasTest = bsonTest.getBsonTest(); BsonTest expected = new BsonTest(); expected.setTestDouble(20.99); expected.setTestString("testStringV"); ArrayList<BsonTest> testArray = new ArrayList<BsonTest>(); BsonTest arrayInner = new BsonTest(); arrayInner.setTestDouble(20.777); testArray.add(arrayInner); testArray.add(arrayInner); expected.setTestArray(testArray); Assert.assertEquals(expected, testHasTest); byte[] bytes = new byte[3]; bytes[0] = 3; bytes[1] = 2; bytes[2] = 1; Assert.assertEquals(new Binary(bytes), bsonTest.getTestBinary()); Assert.assertNotNull(bsonTest.getTestObjectId()); Assert.assertTrue(bsonTest.getTestObjectId().getClass() == ObjectId.class); Assert.assertNotNull(bsonTest.getTestStringObjectId()); Assert.assertNull(bsonTest.getTestIgnore()); Assert.assertTrue(bsonTest.isTestBoolean()); Assert.assertEquals(new Date(time), bsonTest.getTestDate()); Assert.assertEquals(null, bsonTest.getTestNull()); Assert.assertTrue(bsonTest.getTestInt() == 233); Assert.assertTrue(bsonTest.getTestLong() == 233332L); }
@PostMapping(path = "/{deviceModelName}", consumes = "multipart/form-data") @ApiOperation(value = "Create a device firmware") @PreAuthorize("hasAuthority('CREATE_DEVICE_CONFIG')") public DeviceFirmwareVO create( @PathVariable("application") String applicationId, @PathVariable("deviceModelName") String deviceModelName, @RequestParam(value = "firmware", required = true) MultipartFile firmwareFile, @RequestParam(value = "checksum", required = true) MultipartFile checksumFile, @RequestParam(value = "version", required = true) String version ) throws BadServiceResponseException, NotFoundResponseException, IOException { Tenant tenant = user.getTenant(); Application application = getApplication(applicationId); DeviceModel deviceModel = getDeviceModel(tenant, application, deviceModelName); String checksum = getChecksum(checksumFile); validateChecksum(firmwareFile.getBytes(), checksum); DeviceFirmware deviceFirmware = DeviceFirmware.builder() .tenant(tenant) .application(application) .deviceModel(deviceModel) .firmware(new Binary(firmwareFile.getBytes())) .version(version) .build(); ServiceResponse<DeviceFirmware> serviceResponse = deviceFirmwareService.save(tenant, application, deviceFirmware); if (!serviceResponse.isOk()) { throw new BadServiceResponseException( serviceResponse, validationsCode); } else { return new DeviceFirmwareVO().apply(serviceResponse.getResult()); } }
@Test public void shouldTrySaveWithNullApplication() { DeviceFirmware newFirmware = DeviceFirmware.builder() .tenant(tenant) .application(application) .deviceModel(deviceModel1) .version("0.2.0") .firmware(new Binary(firmwareBinary)) .build(); ServiceResponse<DeviceFirmware> response = subject.save(tenant, null, newFirmware); assertThat(response, hasErrorMessage(ApplicationService.Validations.APPLICATION_NULL.getCode())); }
@Test public void shouldTrySaveWithExistingBinary() { DeviceFirmware newFirmware = DeviceFirmware.builder() .tenant(tenant) .application(application) .deviceModel(deviceModel1) .version("0.1.0") .firmware(new Binary(firmwareBinary)) .build(); ServiceResponse<DeviceFirmware> response = subject.save(tenant, application, newFirmware); assertThat(response, hasErrorMessage(DeviceFirmwareService.Validations.FIRMWARE_ALREADY_REGISTERED.getCode())); }
@Test public void shouldTrySaveWithInvalidVersion() { DeviceFirmware newFirmware = DeviceFirmware.builder() .tenant(tenant) .application(application) .deviceModel(deviceModel1) .version("0.1.0cccc") .firmware(new Binary(firmwareBinary)) .build(); ServiceResponse<DeviceFirmware> response = subject.save(tenant, application, newFirmware); assertThat(response, hasErrorMessage(DeviceFirmware.Validations.INVALID_VERSION.getCode())); }
@Test public void shouldTryListByDeviceModelWithOtherApplication() { DeviceFirmware newFirmware = DeviceFirmware.builder() .tenant(tenant) .application(otherApplication) .deviceModel(deviceModel1) .version("0.2.0") .firmware(new Binary(firmwareBinary)) .build(); ServiceResponse<DeviceFirmware> response = subject.save(tenant, otherApplication, newFirmware); assertThat(response, hasErrorMessage(DeviceModelService.Validations.DEVICE_MODEL_DOES_NOT_EXIST.getCode())); }
private void handleBinary(Document document) { if (needConvertBin) { for (String binaryField : binaryFields) { Object object = document.get(binaryField); if (object != null && object instanceof Binary) { Binary binary = (Binary) object; document.put(binaryField, binary.getData()); } } } }
private void convertBin2ByteArr(Document document) { // 获取其中的二进制字段转换为字节数组 try { for (String binField : bin_fields) { Binary binary = (Binary) document.get(binField); if (binary != null) { document.put(binField, binary.getData()); } } } catch (Exception e) { logger.error(String.format("将BsonBinary转换为byte[]出错:%s", document), e); } }
/** * Serialize an object into a BSON binary. * * @param o * The object * @return The binary */ private static Binary toBinary( Object o ) { try { return new Binary( BINARY_TYPE, IoUtil.serialize( o ) ); } catch( IOException x ) { throw new RuntimeException( x ); } }
@Test public void testPrimitives() throws Exception { Schema schema = Primitives.SCHEMA$; GenericRecordBuilder builder = new GenericRecordBuilder(schema); builder.set("i", 1); builder.set("l", 2l); builder.set("s", "This is a string"); builder.set("b", true); builder.set("f", 3.1f); builder.set("d", 4.2); builder.set("n", null); builder.set("by", ByteBuffer.wrap("This is a string in bytes".getBytes())); Record record1 = builder.build(); DBObject object = new BasicDBObject(); object.put("i", 1); object.put("l", 2l); object.put("s", "This is a string"); object.put("b", true); object.put("f", 3.1f); object.put("d", 4.2); object.put("n", null); object.put("by", new Binary("This is a string in bytes".getBytes())); Record record2 = RecordConverter.toRecord(schema, object, getClass().getClassLoader()); assertThat(record2, is(record1)); assertThat(AvroHelper.toSimpleJson(schema, record2), is(AvroHelper.toSimpleJson(schema, record1))); }
@Nullable @Override public Binary toDb(@Nullable final byte[] value) { if (value == null) { return null; } return new Binary(value); }
@Override public BasicDBObject buildDocumentFromByteArray(byte[] payload) { BasicDBObject root = new BasicDBObject(); Binary xys = new Binary(payload); root.put("payload", xys); return root; }
public byte[] getFwdHitsData() { Object o = _dbo.get(_fwdHitsData); if (o instanceof Binary) { return ((Binary)o).getData(); } else { return (byte[])o; } }