Java Code Examples for org.bson.types.Binary#getData()

The following examples show how to use org.bson.types.Binary#getData() . 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: EncryptSystemTest.java    From spring-data-mongodb-encrypt with Apache License 2.0 5 votes vote down vote up
@Test
public void consecutiveEncryptsDifferentResults() {
    MyBean bean = new MyBean();
    bean.nonSensitiveData = "grass is green";
    bean.secretString = "earth is flat";
    mongoTemplate.save(bean);

    Document fromMongo1 = mongoTemplate.getCollection(MyBean.MONGO_MYBEAN).find(new BasicDBObject("_id", new ObjectId(bean.id))).first();

    Binary cryptedSecretBinary1 = (Binary) fromMongo1.get(MyBean.MONGO_SECRETSTRING);
    byte[] cryptedSecret1 = cryptedSecretBinary1.getData();
    mongoTemplate.save(bean);

    Document fromMongo2 = mongoTemplate.getCollection(MyBean.MONGO_MYBEAN).find(new BasicDBObject("_id", new ObjectId(bean.id))).first();
    Binary cryptedSecretBinary2 = (Binary) fromMongo2.get(MyBean.MONGO_SECRETSTRING);
    byte[] cryptedSecret2 = cryptedSecretBinary2.getData();

    assertThat(cryptedSecret1.length, is(cryptedSecret2.length));
    // version
    assertThat(cryptedSecret1[0], is(cryptedSecret2[0]));

    // chances of having the same bytes in the same positions is negligible
    int equals = 0;
    for (int i = 1; i < cryptedSecret1.length; i++) {
        if (cryptedSecret1[i] == cryptedSecret2[i]) equals++;
    }

    assertThat("crypted fields look too much alike", equals, is(not(greaterThan(cryptedSecret1.length / 10))));
}
 
Example 2
Source File: ParameterBindingParser.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
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 3
Source File: MongoIdConverter.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 *
 * 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 4
Source File: MongoIdConverter.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * 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 5
Source File: CoreAwsS3ServiceClientUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "deprecation"})
public void testPutObject() throws IOException {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  final CoreAwsS3ServiceClient client = new CoreAwsS3ServiceClient(service);

  final String bucket = "stuff";
  final String key = "myFile";
  final String acl = "public-read";
  final String contentType = "plain/text";
  final String body = "some data yo";

  final String expectedLocation = "awsLocation";

  Mockito.doReturn(new AwsS3PutObjectResult(expectedLocation))
      .when(service).callFunction(any(), any(), any(Decoder.class));

  AwsS3PutObjectResult result =
      client.putObject(bucket, key, acl, contentType, body);
  assertEquals(result.getLocation(), expectedLocation);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<AwsS3PutObjectResult>> resultClassArg =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .callFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          resultClassArg.capture());

  assertEquals("put", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("bucket", bucket);
  expectedArgs.put("key", key);
  expectedArgs.put("acl", acl);
  expectedArgs.put("contentType", contentType);
  expectedArgs.put("body", body);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.putObjectResultDecoder, resultClassArg.getValue());

  final Binary bodyBin = new Binary("hello".getBytes(StandardCharsets.UTF_8));
  result =
      client.putObject(bucket, key, acl, contentType, bodyBin);
  assertEquals(result.getLocation(), expectedLocation);

  verify(service, times(2))
      .callFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          resultClassArg.capture());

  assertEquals("put", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  expectedArgs.put("body", bodyBin);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.putObjectResultDecoder, resultClassArg.getValue());

  result =
      client.putObject(bucket, key, acl, contentType, bodyBin.getData());
  assertEquals(result.getLocation(), expectedLocation);

  verify(service, times(3))
      .callFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          resultClassArg.capture());

  assertEquals("put", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.putObjectResultDecoder, resultClassArg.getValue());

  final InputStream bodyInput = new ByteArrayInputStream(bodyBin.getData());
  result =
      client.putObject(bucket, key, acl, contentType, bodyInput);
  assertEquals(result.getLocation(), expectedLocation);

  verify(service, times(4))
      .callFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          resultClassArg.capture());

  assertEquals("put", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.putObjectResultDecoder, resultClassArg.getValue());

  // Should pass along errors
  doThrow(new IllegalArgumentException("whoops"))
      .when(service).callFunction(any(), any(), any(Decoder.class));
  assertThrows(() -> client.putObject(bucket, key, acl, contentType, body),
      IllegalArgumentException.class);
}
 
Example 6
Source File: DeviceEventRestEndpoint.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "firmware/{apiKey}/binary", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity downloadFirmwareBinary(HttpServletRequest servletRequest,
                                       @PathVariable("apiKey") String apiKey,
                                       @AuthenticationPrincipal Device principal,
                                       Locale locale) {
    LOGGER.info("Downloading firmware: {}", apiKey);

    Device device = deviceRegisterService.findByApiKey(apiKey);

    if (!principal.getApiKey().equals(apiKey)) {
        return new ResponseEntity<>(
                EventResponse.builder().code(String.valueOf(HttpStatus.BAD_REQUEST.value()))
                        .message(applicationContext.getMessage(Messages.INVALID_RESOURCE.getCode(), null, locale)).build(),
                HttpStatus.BAD_REQUEST);
    }

    if (!Optional.ofNullable(device).isPresent()) {
        return new ResponseEntity<>(
                EventResponse.builder().code(String.valueOf(HttpStatus.BAD_REQUEST.value()))
                        .message(applicationContext.getMessage(Messages.DEVICE_NOT_FOUND.getCode(), null, locale)).build(),
                HttpStatus.BAD_REQUEST);
    }

    ServiceResponse<DeviceFwUpdate> serviceResponse = deviceFirmwareUpdateService.findPendingFwUpdateByDevice(
            device.getTenant(),
            device.getApplication(),
            device
    );

    if (serviceResponse.isOk()) {
        DeviceFwUpdate deviceFwUpdate = serviceResponse.getResult();
        DeviceFirmware deviceFirmware = deviceFwUpdate.getDeviceFirmware();
        Binary binary = deviceFirmware.getFirmware();
        String fileName = deviceFirmware.getVersion().replaceAll("\\.", "-") + ".bin";

        byte out[] = binary.getData();

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("content-disposition", "attachment; filename=" + fileName);
        responseHeaders.add("Content-Type", "application/octet-stream");

        deviceFirmwareUpdateService.updateStatus(device.getTenant(),
                device.getApplication(),
                device,
                deviceFwUpdate.getVersion(),
                FirmwareUpdateStatus.UPDATING);

        return new ResponseEntity(out, responseHeaders,HttpStatus.OK);
    } else {
        return new ResponseEntity<>(
                EventResponse.builder().code(String.valueOf(HttpStatus.NOT_FOUND.value()))
                        .message(applicationContext.getMessage(DeviceFirmwareUpdateService.Validations.FIRMWARE_UPDATE_PENDING_STATUS_DOES_NOT_EXIST.getCode(), null, locale)).build(),
                HttpStatus.NOT_FOUND);
    }
}
 
Example 7
Source File: ParameterBindingParser.java    From mongodb-aggregate-query-support with Apache License 2.0 4 votes vote down vote up
private int determineBinaryParameterIndex(Binary value) {
  byte [] bytes = value.getData();
  byte lastByte = bytes[6];
  return (lastByte + 48)/4;
}