Java Code Examples for com.amazonaws.util.Base64#encodeAsString()

The following examples show how to use com.amazonaws.util.Base64#encodeAsString() . 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: GetNewSecret.java    From strongbox with Apache License 2.0 6 votes vote down vote up
private SecretValue getSecretValue(ToggleGroup valueSource, String value, String generated, File file) {
    Toggle current = valueSource.getSelectedToggle();

    String secretString;
    if (current.getUserData().equals("value")) {
        secretString = value;
    } else if (current.getUserData().equals("generated")) {
        Integer numBytesToGenerate = Integer.valueOf(generated);
        // TODO: store as plain bytes?
        byte[] random = Singleton.randomGenerator.generateRandom(numBytesToGenerate);
        secretString = Base64.encodeAsString(random);
    } else {
        String path = null;
        try {
            path = file.getCanonicalPath();
            return SecretValueConverter.inferEncoding(Files.readAllBytes(Paths.get(path)), SecretType.OPAQUE);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read secret from file");
        }
    }

    return new SecretValue(secretString, SecretType.OPAQUE);
}
 
Example 2
Source File: SecretModel.java    From strongbox with Apache License 2.0 5 votes vote down vote up
private SecretValue extractSecretValueOrThrow(boolean valueFromStdin, String generate, String valueFile) {
    String secretValue = "";
    int sum = booleanIfExists(valueFromStdin) + booleanIfExists(generate) + booleanIfExists(valueFile);

    SecretType secretType = SecretType.OPAQUE;

    if (sum == 0) {
        throw new RuntimeException("You must specify either --value-from-stdin, --value-from-file or --generate-value");
    }
    if (sum > 1) {
        throw new RuntimeException("You must specify one and only one of --value-from-stdin, --value-from-file and --generate-value");
    }

    if (generate != null) {
        secretValue = Base64.encodeAsString(randomGenerator.generateRandom(extractGenerate(generate)));
    }

    if (valueFile != null) {
        return SecretValueConverter.inferEncoding(extractValueFromFile(valueFile), secretType);
    }

    if (valueFromStdin) {
        return SecretValueConverter.inferEncoding(fromStdin(), secretType);
    }

    return new SecretValue(secretValue, secretType);
}
 
Example 3
Source File: AwsUploadRepository.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
public String downloadAsBase64(String filePath) throws Exception {
    if (!Optional.ofNullable(filePath).isPresent()) {
        throw new Exception(UploadService.Validations.INVALID_PATH.getCode());
    }
    try {
        return Base64.encodeAsString(IOUtils.toByteArray(downloadFile(filePath)));
    } catch (IOException e) {
        throw new Exception(e.getMessage());
    }
}
 
Example 4
Source File: SQSSender.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
@Override
public Call<Void> sendSpans(List<byte[]> list) {
  if (closeCalled) throw new IllegalStateException("closed");

  byte[] encodedSpans = BytesMessageEncoder.forEncoding(encoding()).encode(list);
  String body =
      encoding() == Encoding.JSON && isAscii(encodedSpans)
          ? new String(encodedSpans, UTF_8)
          : Base64.encodeAsString(encodedSpans);

  return new SQSCall(new SendMessageRequest(queueUrl, body));
}
 
Example 5
Source File: S3TestUtils.java    From beam with Apache License 2.0 5 votes vote down vote up
@Nullable
static String getSSECustomerKeyMd5(S3Options options) {
  SSECustomerKey sseCostumerKey = options.getSSECustomerKey();
  if (sseCostumerKey != null) {
    return Base64.encodeAsString(DigestUtils.md5(Base64.decode(sseCostumerKey.getKey())));
  }
  return null;
}
 
Example 6
Source File: SQSMessageProducerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test sendInternal input with SQSByteMessage
 */
@Test
public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSException, IOException {
    
    /*
     * Set up non JMS sqs message
     */
    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();
    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");

    byte[] byteArray = new byte[] { 1, 0, 'a', 65 };
    String messageBody = Base64.encodeAsString(byteArray);
    com.amazonaws.services.sqs.model.Message message =
            new com.amazonaws.services.sqs.model.Message()
                    .withMessageAttributes(mapMessageAttributes)
                    .withAttributes(mapAttributes)
                    .withBody(messageBody);

    SQSObjectMessage msg = spy(new SQSObjectMessage(acknowledger, QUEUE_URL, message));

    Map<String, MessageAttributeValue> messageAttributes = createMessageAttribute("object");

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_2));

    producer.sendInternal(destination, msg);

    verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, Arrays.asList(messageBody),
            messageAttributes)));
    verify(msg).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1);
    verify(msg).setSQSMessageId(MESSAGE_ID_1);
}
 
Example 7
Source File: SQSMessageProducerFifoTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test sendInternal input with SQSByteMessage
 */
@Test
public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSException, IOException {
    
    /*
     * Set up non JMS sqs message
     */
    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();
    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");
    mapAttributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, GROUP_ID);
    mapAttributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, DEDUP_ID);
    mapAttributes.put(SQSMessagingClientConstants.SEQUENCE_NUMBER, SEQ_NUMBER);

    byte[] byteArray = new byte[] { 1, 0, 'a', 65 };
    String messageBody = Base64.encodeAsString(byteArray);
    com.amazonaws.services.sqs.model.Message message =
            new com.amazonaws.services.sqs.model.Message()
                    .withMessageAttributes(mapMessageAttributes)
                    .withAttributes(mapAttributes)
                    .withBody(messageBody);

    SQSBytesMessage msg = spy(new SQSBytesMessage(acknowledger, QUEUE_URL, message));

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID).withSequenceNumber(SEQ_NUMBER_2));

    producer.sendInternal(destination, msg);

    verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messageBody, SQSMessage.BYTE_MESSAGE_TYPE, GROUP_ID, DEDUP_ID)));
    verify(msg).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID);
    verify(msg).setSQSMessageId(MESSAGE_ID);
    verify(msg).setSequenceNumber(SEQ_NUMBER_2);
}
 
Example 8
Source File: Encoder.java    From strongbox with Apache License 2.0 4 votes vote down vote up
public static String base64encode(byte[] value) {
    return Base64.encodeAsString(value);
}
 
Example 9
Source File: SnowflakeFileTransferAgent.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
/**
 * Compress an input stream with GZIP and return the result size, digest and
 * compressed stream.
 *
 * @param inputStream data input
 * @return result size, digest and compressed stream
 * @throws SnowflakeSQLException if encountered exception when compressing
 */
private static InputStreamWithMetadata compressStreamWithGZIP(
    InputStream inputStream) throws SnowflakeSQLException
{
  FileBackedOutputStream tempStream =
      new FileBackedOutputStream(MAX_BUFFER_SIZE, true);

  try
  {

    DigestOutputStream digestStream = new DigestOutputStream(tempStream,
                                                             MessageDigest.getInstance("SHA-256"));

    CountingOutputStream countingStream =
        new CountingOutputStream(digestStream);

    // construct a gzip stream with sync_flush mode
    GZIPOutputStream gzipStream;

    gzipStream = new GZIPOutputStream(countingStream, true);

    IOUtils.copy(inputStream, gzipStream);

    inputStream.close();

    gzipStream.finish();
    gzipStream.flush();

    countingStream.flush();

    return new InputStreamWithMetadata(countingStream.getCount(),
                                       Base64.encodeAsString(digestStream.getMessageDigest().digest()),
                                       tempStream);

  }
  catch (IOException | NoSuchAlgorithmException ex)
  {
    logger.error("Exception compressing input stream", ex);

    throw new SnowflakeSQLException(ex, SqlState.INTERNAL_ERROR,
                                    ErrorCode.INTERNAL_ERROR.getMessageCode(),
                                    "error encountered for compression");
  }

}
 
Example 10
Source File: StreamPart.java    From s3-stream-upload with MIT License 4 votes vote down vote up
public String getMD5Digest() {
    return Base64.encodeAsString(stream.getMD5Digest());
}
 
Example 11
Source File: S3DataGenerator.java    From aws-big-data-blog with Apache License 2.0 4 votes vote down vote up
private static String md5b64(byte[] content) {
   return Base64.encodeAsString(md5(content));
}
 
Example 12
Source File: SQSMessageProducer.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 4 votes vote down vote up
void sendInternal(SQSQueueDestination queue, Message rawMessage) throws JMSException {
    checkClosed();
    String sqsMessageBody = null;
    String messageType = null;
    if (!(rawMessage instanceof SQSMessage)) {
        throw new MessageFormatException(
                "Unrecognized message type. Messages have to be one of: SQSBytesMessage, SQSObjectMessage, or SQSTextMessage");            
    }
    
    SQSMessage message = (SQSMessage)rawMessage;
    message.setJMSDestination(queue);
    if (message instanceof SQSBytesMessage) {
        sqsMessageBody = Base64.encodeAsString(((SQSBytesMessage) message).getBodyAsBytes());
        messageType = SQSMessage.BYTE_MESSAGE_TYPE;
    } else if (message instanceof SQSObjectMessage) {
        sqsMessageBody = ((SQSObjectMessage) message).getMessageBody();
        messageType = SQSMessage.OBJECT_MESSAGE_TYPE;
    } else if (message instanceof SQSTextMessage) {            
        sqsMessageBody = ((SQSTextMessage) message).getText();
        messageType = SQSMessage.TEXT_MESSAGE_TYPE;
    }
    
    if (sqsMessageBody == null || sqsMessageBody.isEmpty()) {
        throw new JMSException("Message body cannot be null or empty");
    }
    Map<String, MessageAttributeValue> messageAttributes = propertyToMessageAttribute((SQSMessage) message);

    /**
     * These will override existing attributes if they exist. Everything that
     * has prefix JMS_ is reserved for JMS Provider, but if the user sets that
     * attribute, it will be overwritten.
     */
    addStringAttribute(messageAttributes, SQSMessage.JMS_SQS_MESSAGE_TYPE, messageType);
    addReplyToQueueReservedAttributes(messageAttributes, message);
    addCorrelationIDToQueueReservedAttributes(messageAttributes, message);

    SendMessageRequest sendMessageRequest = new SendMessageRequest(queue.getQueueUrl(), sqsMessageBody);
    sendMessageRequest.setMessageAttributes(messageAttributes);

    if (deliveryDelaySeconds != 0) {
        sendMessageRequest.setDelaySeconds(deliveryDelaySeconds);
    }

    //for FIFO queues, we have to specify both MessageGroupId, which we obtain from standard property JMSX_GROUP_ID
    //and MessageDeduplicationId, which we obtain from a custom provider specific property JMS_SQS_DEDUPLICATION_ID
    //notice that this code does not validate if the values are actually set by the JMS user
    //this means that failure to provide the required values will fail server side and throw a JMSException
    if (queue.isFifo()) {
        sendMessageRequest.setMessageGroupId(message.getSQSMessageGroupId());
        sendMessageRequest.setMessageDeduplicationId(message.getSQSMessageDeduplicationId());
    }

    SendMessageResult sendMessageResult = amazonSQSClient.sendMessage(sendMessageRequest);
    String messageId = sendMessageResult.getMessageId();
    LOG.info("Message sent to SQS with SQS-assigned messageId: " + messageId);
    /** TODO: Do not support disableMessageID for now. */
    message.setSQSMessageId(messageId);

    // if the message was sent to FIFO queue, the sequence number will be
    // set in the response
    // pass it to JMS user through provider specific JMS property
    if (sendMessageResult.getSequenceNumber() != null) {
        message.setSequenceNumber(sendMessageResult.getSequenceNumber());
    }
}
 
Example 13
Source File: SQSMessageProducerTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Test sendInternal input with SQSObjectMessage
 */
@Test
public void testSendInternalSQSObjectMessageFromReceivedMessage() throws JMSException, IOException {

    /*
     * Set up non JMS sqs message
     */
    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();

    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.OBJECT_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");

    // Encode an object to byte array
    Integer integer = new Integer("10");
    ByteArrayOutputStream array = new ByteArrayOutputStream(10);
    ObjectOutputStream oStream = new ObjectOutputStream(array);
    oStream.writeObject(integer);
    oStream.close();

    String messageBody = Base64.encodeAsString(array.toByteArray());
    com.amazonaws.services.sqs.model.Message message =
            new com.amazonaws.services.sqs.model.Message()
                    .withMessageAttributes(mapMessageAttributes)
                    .withAttributes(mapAttributes)
                    .withBody(messageBody);

    SQSObjectMessage msg = spy(new SQSObjectMessage(acknowledger, QUEUE_URL, message));

    Map<String, MessageAttributeValue> messageAttributes = createMessageAttribute("object");

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_2));

    producer.sendInternal(destination, msg);

    verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, Arrays.asList(messageBody),
            messageAttributes)));
    verify(msg).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1);
    verify(msg).setSQSMessageId(MESSAGE_ID_1);
}
 
Example 14
Source File: SQSMessageProducerFifoTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Test sendInternal input with SQSObjectMessage
 */
@Test
public void testSendInternalSQSObjectMessageFromReceivedMessage() throws JMSException, IOException {

    /*
     * Set up non JMS sqs message
     */
    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();

    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.OBJECT_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");
    mapAttributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, GROUP_ID);
    mapAttributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, DEDUP_ID);
    mapAttributes.put(SQSMessagingClientConstants.SEQUENCE_NUMBER, SEQ_NUMBER);

    // Encode an object to byte array
    Integer integer = new Integer("10");
    ByteArrayOutputStream array = new ByteArrayOutputStream(10);
    ObjectOutputStream oStream = new ObjectOutputStream(array);
    oStream.writeObject(integer);
    oStream.close();

    String messageBody = Base64.encodeAsString(array.toByteArray());
    com.amazonaws.services.sqs.model.Message message =
            new com.amazonaws.services.sqs.model.Message()
                    .withMessageAttributes(mapMessageAttributes)
                    .withAttributes(mapAttributes)
                    .withBody(messageBody);

    SQSObjectMessage msg = spy(new SQSObjectMessage(acknowledger, QUEUE_URL, message));

    when(amazonSQSClient.sendMessage(any(SendMessageRequest.class)))
            .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID).withSequenceNumber(SEQ_NUMBER_2));

    producer.sendInternal(destination, msg);

    verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messageBody, SQSMessage.OBJECT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID)));
    verify(msg).setJMSDestination(destination);
    verify(msg).setJMSMessageID("ID:" + MESSAGE_ID);
    verify(msg).setSQSMessageId(MESSAGE_ID);
    verify(msg).setSequenceNumber(SEQ_NUMBER_2);
}