org.bson.types.Binary Java Examples
The following examples show how to use
org.bson.types.Binary.
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: MongoTypeUtil.java From syncer with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #2
Source File: BsonTypeMap.java From morphia with Apache License 2.0 | 6 votes |
/** * 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: MongodbInputDiscoverFieldsImpl.java From pentaho-mongodb-plugin with Apache License 2.0 | 6 votes |
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; }
Example #4
Source File: MongoFile.java From lumongo with Apache License 2.0 | 6 votes |
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)); }
Example #5
Source File: MongoFile.java From lumongo with Apache License 2.0 | 6 votes |
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; }
Example #6
Source File: DeviceFirmwareServiceTest.java From konker-platform with Apache License 2.0 | 6 votes |
@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()); }
Example #7
Source File: DeviceFirmwareServiceTest.java From konker-platform with Apache License 2.0 | 6 votes |
@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); }
Example #8
Source File: MongoCertificateRepository.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
private Certificate convert(CertificateMongo certificateMongo) { if (certificateMongo == null) { return null; } Certificate certificate = new Certificate(); certificate.setId(certificateMongo.getId()); certificate.setName(certificateMongo.getName()); certificate.setType(certificateMongo.getType()); certificate.setConfiguration(certificateMongo.getConfiguration()); certificate.setDomain(certificateMongo.getDomain()); if (certificateMongo.getMetadata() != null) { // convert bson binary type back to byte array Map<String, Object> metadata = certificateMongo.getMetadata().entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue() instanceof Binary ? ((Binary) e.getValue()).getData() : e)); certificate.setMetadata(metadata); } certificate.setCreatedAt(certificateMongo.getCreatedAt()); certificate.setUpdatedAt(certificateMongo.getUpdatedAt()); return certificate; }
Example #9
Source File: PolymorphismSystemTest.java From spring-data-mongodb-encrypt with Apache License 2.0 | 6 votes |
@Test public void checkReflectiveEncryption() { TestObject testObject = new TestObject(); SubObject subObject = new SubObject(); subObject.field = "this is a test"; testObject.list = Collections.singletonList(subObject); mongoTemplate.save(testObject); TestObject fromDb = mongoTemplate.findOne(query(where("_id").is(testObject.id)), TestObject.class); assertThat(fromDb.list, hasSize(1)); assertThat(((SubObject) fromDb.list.get(0)).field, is(subObject.field)); Document fromMongo = mongoTemplate.getCollection(TestObject.MONGO_TESTOBJECT).find(new Document("_id", new ObjectId(testObject.id))).first(); ArrayList dbNestedList = (ArrayList) fromMongo.get("list"); Document dbBean = (Document) dbNestedList.get(0); Object encryptedField = dbBean.get("field"); assertThat(encryptedField, is(instanceOf(Binary.class))); Object encryptedFieldData = ((Binary) encryptedField).getData(); assertThat(encryptedFieldData, is(instanceOf(byte[].class))); }
Example #10
Source File: EncryptSystemTest.java From spring-data-mongodb-encrypt with Apache License 2.0 | 6 votes |
@Test public void testNestedListMap() { MyBean bean = new MyBean(); Map<String, List<MySubBean>> map = new HashMap<>(); map.put("one", Arrays.asList(new MySubBean("one1", "one2"), new MySubBean("one3", "one4"))); map.put("two", Arrays.asList(new MySubBean("two1", "two2"), new MySubBean("two3", "two4"))); bean.nestedListMap = map; mongoTemplate.save(bean); MyBean fromDb = mongoTemplate.findOne(query(where("_id").is(bean.id)), MyBean.class); assertThat(fromDb.nestedListMap.get("one").get(1).secretString, is("one4")); Document fromMongo = mongoTemplate.getCollection(MyBean.MONGO_MYBEAN).find(new BasicDBObject("_id", new ObjectId(bean.id))).first(); Document dbNestedListMap = (Document) fromMongo.get("nestedListMap"); ArrayList dbNestedList = (ArrayList) dbNestedListMap.get("one"); Document dbBean = (Document) dbNestedList.get(1); Object encryptedField = dbBean.get("secretString"); assertThat(encryptedField, is(instanceOf(Binary.class))); Object encryptedFieldData = ((Binary) encryptedField).getData(); assertThat(encryptedFieldData, is(instanceOf(byte[].class))); }
Example #11
Source File: EncryptSystemTest.java From spring-data-mongodb-encrypt with Apache License 2.0 | 6 votes |
@Test public void testEncryptedNestedListMap() { MyBean bean = new MyBean(); Map<String, List<MySubBean>> map = new HashMap<>(); map.put("one", Arrays.asList(new MySubBean("one1", "one2"), new MySubBean("one3", "one4"))); map.put("two", Arrays.asList(new MySubBean("two1", "two2"), new MySubBean("two3", "two4"))); bean.encryptedNestedListMap = map; mongoTemplate.save(bean); MyBean fromDb = mongoTemplate.findOne(query(where("_id").is(bean.id)), MyBean.class); assertThat(fromDb.encryptedNestedListMap.get("one").get(1).secretString, is("one4")); Document fromMongo = mongoTemplate.getCollection(MyBean.MONGO_MYBEAN).find(new BasicDBObject("_id", new ObjectId(bean.id))).first(); Object binarySecret = fromMongo.get("encryptedNestedListMap"); assertThat(binarySecret, is(instanceOf(Binary.class))); assertThat(((Binary) binarySecret).getData(), is(instanceOf(byte[].class))); }
Example #12
Source File: AbstractEncryptionEventListener.java From spring-data-mongodb-encrypt with Apache License 2.0 | 6 votes |
public Object apply(Object o) { byte[] data; if (o instanceof Binary) data = ((Binary) o).getData(); else if (o instanceof byte[]) data = (byte[]) o; else throw new IllegalStateException("Got " + o.getClass() + ", expected: Binary or byte[]"); try { byte[] serialized = cryptVault.decrypt((data)); BSONCallback bsonCallback = new BasicDBObjectCallback(); decode(serialized, bsonCallback); BSONObject deserialized = (BSONObject) bsonCallback.get(); return deserialized.get(""); } catch (CryptOperationException e) { if (silentDecryptionFailure) return null; throw e; } }
Example #13
Source File: MongoPageSource.java From presto with Apache License 2.0 | 6 votes |
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 #14
Source File: FileController.java From mongodb-file-server with MIT License | 6 votes |
/** * 上传 * * @param file * @param redirectAttributes * @return */ @PostMapping("/") public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { try { File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(), new Binary(file.getBytes())); f.setMd5(MD5Util.getMD5(file.getInputStream())); fileService.saveFile(f); } catch (IOException | NoSuchAlgorithmException ex) { ex.printStackTrace(); redirectAttributes.addFlashAttribute("message", "Your " + file.getOriginalFilename() + " is wrong!"); return "redirect:/"; } redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!"); return "redirect:/"; }
Example #15
Source File: FileController.java From mongodb-file-server with MIT License | 6 votes |
/** * 上传接口 * * @param file * @return */ @PostMapping("/upload") @ResponseBody public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) { File returnFile = null; try { File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(), new Binary(file.getBytes())); f.setMd5(MD5Util.getMD5(file.getInputStream())); returnFile = fileService.saveFile(f); String path = "//" + serverAddress + ":" + serverPort + "/view/" + returnFile.getId(); return ResponseEntity.status(HttpStatus.OK).body(path); } catch (IOException | NoSuchAlgorithmException ex) { ex.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage()); } }
Example #16
Source File: DeviceFirmwareServiceTest.java From konker-platform with Apache License 2.0 | 5 votes |
@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())); }
Example #17
Source File: MongoIdConverter.java From secure-data-service with Apache License 2.0 | 5 votes |
/** * * Converts the given Binary into a String that represent a UUID. * * @param id * @return */ public static String binaryToUUIDString(Object id) { Binary binary = (Binary) id; byte[] arr = binary.getData(); ByteBuffer buff = ByteBuffer.wrap(arr); long msb = buff.getLong(0); long lsb = buff.getLong(8); UUID uid = new UUID(msb, lsb); return uid.toString(); }
Example #18
Source File: MongoIdConverter.java From secure-data-service with Apache License 2.0 | 5 votes |
/** * * Converts the given Binary into a String that represent a UUID. * * @param id * @return */ public static String binaryToUUIDString(Object id) { Binary binary = (Binary) id; byte[] arr = binary.getData(); ByteBuffer buff = ByteBuffer.wrap(arr); long msb = buff.getLong(0); long lsb = buff.getLong(8); UUID uid = new UUID(msb, lsb); return uid.toString(); }
Example #19
Source File: MongoDBTest.java From jlogstash-input-plugin with Apache License 2.0 | 5 votes |
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); } }
Example #20
Source File: MongoDB.java From jlogstash-input-plugin with Apache License 2.0 | 5 votes |
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()); } } } }
Example #21
Source File: ParameterBindingParser.java From mongodb-aggregate-query-support with Apache License 2.0 | 5 votes |
private boolean binaryValueNeedsReplacing(Binary value) { final byte [] paramBytes = {0, 10, 90, -83, -87, -128}; byte [] bytes = value.getData(); if(bytes.length != paramBytes.length + 1) { return false; } for (int i = 0; i < paramBytes.length; i++) { if(bytes[i] != paramBytes[i]) { return false; } } return true; }
Example #22
Source File: DeviceFirmwareServiceTest.java From konker-platform with Apache License 2.0 | 5 votes |
@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())); }
Example #23
Source File: DeviceFirmwareServiceTest.java From konker-platform with Apache License 2.0 | 5 votes |
@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())); }
Example #24
Source File: DeviceFirmwareServiceTest.java From konker-platform with Apache License 2.0 | 5 votes |
@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())); }
Example #25
Source File: CoreAwsS3ServiceClient.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
public AwsS3PutObjectResult putObject( final String bucket, final String key, final String acl, final String contentType, final byte[] body ) { return putObject(bucket, key, acl, contentType, new Binary(body)); }
Example #26
Source File: File.java From mongodb-file-server with MIT License | 5 votes |
public File(String name, String contentType, long size,Binary content) { this.name = name; this.contentType = contentType; this.size = size; this.uploadDate = new Date(); this.content = content; }
Example #27
Source File: DeviceFirmwareRestController.java From konker-platform with Apache License 2.0 | 5 votes |
@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()); } }
Example #28
Source File: CoreAwsS3ServiceClient.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
public AwsS3PutObjectResult putObject( final String bucket, final String key, final String acl, final String contentType, final InputStream body ) throws IOException { return putObject(bucket, key, acl, contentType, new Binary(readAllToBytes(body))); }
Example #29
Source File: CoreAwsS3ServiceClient.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
public AwsS3PutObjectResult putObject( final String bucket, final String key, final String acl, final String contentType, final Binary body ) { return putObjectInternal(bucket, key, acl, contentType, body); }
Example #30
Source File: EncryptSystemTest.java From spring-data-mongodb-encrypt with Apache License 2.0 | 5 votes |
byte[] cryptedResultInDb(String value) { MyBean bean = new MyBean(); bean.secretString = value; bean.nonSensitiveData = getClass().getSimpleName(); mongoTemplate.insert(bean); Document fromMongo = mongoTemplate.getCollection(MyBean.MONGO_MYBEAN).find(new Document("_id", new ObjectId(bean.id))).first(); Object cryptedSecret = fromMongo.get(MONGO_SECRETSTRING); assertThat(cryptedSecret, is(instanceOf(Binary.class))); Object cryptedSecretData = ((Binary) cryptedSecret).getData(); assertThat(cryptedSecretData, is(instanceOf(byte[].class))); return (byte[]) cryptedSecretData; }