Java Code Examples for com.amazonaws.services.dynamodbv2.model.AttributeValue#setB()

The following examples show how to use com.amazonaws.services.dynamodbv2.model.AttributeValue#setB() . 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: DynamoDBEncryptor.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * Marshalls the <code>description</code> into a ByteBuffer by outputting
 * each key (modified UTF-8) followed by its value (also in modified UTF-8).
 *
 * @param description
 * @return the description encoded as an AttributeValue with a ByteBuffer value
 * @see java.io.DataOutput#writeUTF(String)
 */
protected static AttributeValue marshallDescription(Map<String, String> description) {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(bos);
        out.writeInt(CURRENT_VERSION);
        for (Map.Entry<String, String> entry : description.entrySet()) {
            byte[] bytes = entry.getKey().getBytes(UTF8);
            out.writeInt(bytes.length);
            out.write(bytes);
            bytes = entry.getValue().getBytes(UTF8);
            out.writeInt(bytes.length);
            out.write(bytes);
        }
        out.close();
        AttributeValue result = new AttributeValue();
        result.setB(ByteBuffer.wrap(bos.toByteArray()));
        return result;
    } catch (IOException ex) {
        // Due to the objects in use, an IOException is not possible.
        throw new RuntimeException("Unexpected exception", ex);
    }
}
 
Example 2
Source File: DDBTransaction.java    From Doradus with Apache License 2.0 6 votes vote down vote up
private AttributeValue mapColumnValue(String storeName, DColumn col) {
    AttributeValue attrValue = new AttributeValue();
    if (!DBService.isSystemTable(storeName)) {
        if (col.getRawValue().length == 0) {
            attrValue.setS(DynamoDBService.NULL_COLUMN_MARKER);
        } else {
            attrValue.setB(ByteBuffer.wrap(col.getRawValue()));
        }
    } else {
        String strValue = col.getValue();
        if (strValue.length() == 0) {
            strValue = DynamoDBService.NULL_COLUMN_MARKER;
        }
        attrValue.setS(strValue);
    }
    return attrValue;
}
 
Example 3
Source File: DynamoDSETranslatorJSONBlob.java    From dynamo-cassandra-proxy with Apache License 2.0 5 votes vote down vote up
private AttributeValue rowToAV(ColumnDefinition columnDefinition, Row row) {
    AttributeValue av = new AttributeValue();
    CqlIdentifier name = columnDefinition.getName();
    switch (columnDefinition.getType().getProtocolCode())
    {
        case BLOB:
            av.setB(row.getByteBuffer(name));
            break;
        case BIGINT:
        case BOOLEAN:
        case COUNTER:
        case DECIMAL:
        case DOUBLE:
        case FLOAT:
        case INT:
        case VARINT:
        case TINYINT:
        case SMALLINT:
            String v = String.valueOf(row.getDouble(name));
            if (v.endsWith(".0")) //Keep non doubles looking like non-doubles
                v = v.substring(0, v.length() - 2);
            av.setN(v);
            break;
        case TIMEUUID:
        case UUID:
        case INET:
        case DATE:
        case VARCHAR:
        case ASCII:
        case TIME:
            av.setS(row.getString(name));
            break;
        default:
            throw new IllegalArgumentException("Type not supported: " + name.asInternal() + " " + columnDefinition.getType());
    }
    return av;
}
 
Example 4
Source File: AttributeValueCoderTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPassForByteArray() throws IOException {
  AttributeValue expected = new AttributeValue();
  expected.setB(ByteBuffer.wrap("hello".getBytes(StandardCharsets.UTF_8)));

  AttributeValueCoder coder = AttributeValueCoder.of();
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  coder.encode(expected, output);

  ByteArrayInputStream in = new ByteArrayInputStream(output.toByteArray());

  AttributeValue actual = coder.decode(in);

  Assert.assertEquals(expected, actual);
}
 
Example 5
Source File: AttributeValueCoder.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeValue decode(InputStream inStream) throws IOException {
  AttributeValue attrValue = new AttributeValue();

  String type = StringUtf8Coder.of().decode(inStream);
  AttributeValueType attrType = AttributeValueType.valueOf(type);

  switch (attrType) {
    case s:
      attrValue.setS(StringUtf8Coder.of().decode(inStream));
      break;
    case n:
      attrValue.setN(StringUtf8Coder.of().decode(inStream));
      break;
    case bOOL:
      attrValue.setBOOL(BooleanCoder.of().decode(inStream));
      break;
    case b:
      attrValue.setB(ByteBuffer.wrap(ByteArrayCoder.of().decode(inStream)));
      break;
    case sS:
      attrValue.setSS(LIST_STRING_CODER.decode(inStream));
      break;
    case nS:
      attrValue.setNS(LIST_STRING_CODER.decode(inStream));
      break;
    case bS:
      attrValue.setBS(convertToListByteBuffer(LIST_BYTE_CODER.decode(inStream)));
      break;
    case l:
      attrValue.setL(LIST_ATTRIBUTE_CODER.decode(inStream));
      break;
    case m:
      attrValue.setM(MAP_ATTRIBUTE_CODER.decode(inStream));
      break;
    case nULLValue:
      attrValue.setNULL(BooleanCoder.of().decode(inStream));
      break;
    default:
      throw new CoderException("Unknown Type");
  }

  return attrValue;
}
 
Example 6
Source File: DynamoDbDelegate.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method that can clone an Attribute Value
 *
 * @param val the AttributeValue to copy
 * @param sourceDestinationMap used to avoid loops by keeping track of references
 * @return a copy of val
 */
public static AttributeValue clone(final AttributeValue val, final IdentityHashMap<AttributeValue, AttributeValue> sourceDestinationMap) {
    if (val == null) {
        return null;
    }

    if (sourceDestinationMap.containsKey(val)) {
        return sourceDestinationMap.get(val);
    }

    final AttributeValue clonedVal = new AttributeValue();
    sourceDestinationMap.put(val, clonedVal);
    if (val.getN() != null) {
        clonedVal.setN(val.getN());
    } else if (val.getS() != null) {
        clonedVal.setS(val.getS());
    } else if (val.getB() != null) {
        clonedVal.setB(val.getB());
    } else if (val.getNS() != null) {
        clonedVal.setNS(val.getNS());
    } else if (val.getSS() != null) {
        clonedVal.setSS(val.getSS());
    } else if (val.getBS() != null) {
        clonedVal.setBS(val.getBS());
    } else if (val.getBOOL() != null) {
        clonedVal.setBOOL(val.getBOOL());
    } else if (val.getNULL() != null) {
        clonedVal.setNULL(val.getNULL());
    } else if (val.getL() != null) {
        final List<AttributeValue> list = new ArrayList<>(val.getL().size());
        for (AttributeValue listItemValue : val.getL()) {
            if (!sourceDestinationMap.containsKey(listItemValue)) {
                sourceDestinationMap.put(listItemValue, clone(listItemValue, sourceDestinationMap));
            }
            list.add(sourceDestinationMap.get(listItemValue));
        }
        clonedVal.setL(list);
    } else if (val.getM() != null) {
        final Map<String, AttributeValue> map = new HashMap<>(val.getM().size());
        for (Entry<String, AttributeValue> pair : val.getM().entrySet()) {
            if (!sourceDestinationMap.containsKey(pair.getValue())) {
                sourceDestinationMap.put(pair.getValue(), clone(pair.getValue(), sourceDestinationMap));
            }
            map.put(pair.getKey(), sourceDestinationMap.get(pair.getValue()));
        }
        clonedVal.setM(map);
    }
    return clonedVal;
}
 
Example 7
Source File: DynamoDBEncryptor.java    From aws-dynamodb-encryption-java with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the encrypted (and signed) record, which is a map of item
 * attributes. There is no side effect on the input parameters upon calling
 * this method.
 * 
 * @param itemAttributes
 *            the input record
 * @param attributeFlags
 *            the corresponding encryption flags
 * @param context
 *            encryption context
 * @return a new instance of item attributes encrypted as necessary
 * @throws GeneralSecurityException
 *             if failed to encrypt the record
 */
public Map<String, AttributeValue> encryptRecord(
        Map<String, AttributeValue> itemAttributes,
        Map<String, Set<EncryptionFlags>> attributeFlags,
        EncryptionContext context) throws GeneralSecurityException {
    if (attributeFlags.isEmpty()) {
        return itemAttributes;
    }
    // Copy to avoid changing anyone elses objects
    itemAttributes = new HashMap<String, AttributeValue>(itemAttributes);

    // Copy the attribute values into the context
    context = new EncryptionContext.Builder(context)
        .withAttributeValues(itemAttributes)
        .build();

    Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator =
            getEncryptionContextOverrideOperator();
    if (encryptionContextOverrideOperator != null) {
        context = encryptionContextOverrideOperator.apply(context);
    }

    EncryptionMaterials materials = encryptionMaterialsProvider.getEncryptionMaterials(context);
    // We need to copy this because we modify it to record other encryption details
    Map<String, String> materialDescription = new HashMap<String, String>(
            materials.getMaterialDescription());
    SecretKey encryptionKey = materials.getEncryptionKey();

    actualEncryption(itemAttributes, attributeFlags, materialDescription, encryptionKey);

    // The description must be stored after encryption because its data
    // is necessary for proper decryption.
    final String signingAlgo = materialDescription.get(signingAlgorithmHeader);
    DynamoDBSigner signer;
    if (signingAlgo != null) {
        signer = DynamoDBSigner.getInstance(signingAlgo, Utils.getRng());
    } else {
        signer = DynamoDBSigner.getInstance(DEFAULT_SIGNATURE_ALGORITHM, Utils.getRng());
    }

    if (materials.getSigningKey() instanceof PrivateKey ) {
        materialDescription.put(signingAlgorithmHeader, signer.getSigningAlgorithm());
    }
    if (!materialDescription.isEmpty()) {
        itemAttributes.put(materialDescriptionFieldName, marshallDescription(materialDescription));
    }

    String associatedData = "TABLE>" + context.getTableName() + "<TABLE";
    byte[] signature = signer.calculateSignature(itemAttributes, attributeFlags,
            associatedData.getBytes(UTF8), materials.getSigningKey());

    AttributeValue signatureAttribute = new AttributeValue();
    signatureAttribute.setB(ByteBuffer.wrap(signature));
    itemAttributes.put(signatureFieldName, signatureAttribute);

    return itemAttributes;
}
 
Example 8
Source File: AttributeValueMarshaller.java    From aws-dynamodb-encryption-java with Apache License 2.0 4 votes vote down vote up
private static AttributeValue unmarshall(final DataInputStream in) throws IOException {
    char type = in.readChar();
    AttributeValue result = new AttributeValue();
    switch (type) {
    case '\0':
        result.setNULL(Boolean.TRUE);
        break;
    case 'b':
        result.setB(readBytes(in));
        break;
    case 'B':
        result.setBS(readBytesList(in));
        break;
    case 'n':
        result.setN(readString(in));
        break;
    case 'N':
        result.setNS(readStringList(in));
        break;
    case 's':
        result.setS(readString(in));
        break;
    case 'S':
        result.setSS(readStringList(in));
        break;
    case '?':
        final byte boolValue = in.readByte();

        if (boolValue == TRUE_FLAG) {
            result.setBOOL(Boolean.TRUE);
        } else if (boolValue == FALSE_FLAG) {
            result.setBOOL(Boolean.FALSE);
        } else {
            throw new IllegalArgumentException("Improperly formatted data");
        }
        break;
    case 'L':
        final int lCount = in.readInt();
        final List<AttributeValue> l = new ArrayList<AttributeValue>(lCount);
        for (int lIdx = 0; lIdx < lCount; lIdx++) {
            l.add(unmarshall(in));
        }
        result.setL(l);
        break;
    case 'M':
        final int mCount = in.readInt();
        final Map<String, AttributeValue> m = new HashMap<String, AttributeValue>();
        for (int mIdx = 0; mIdx < mCount; mIdx++) {
            final AttributeValue key = unmarshall(in);
            if (key.getS() == null) {
                throw new IllegalArgumentException("Improperly formatted data");
            }
            AttributeValue value = unmarshall(in);
            m.put(key.getS(), value);
        }
        result.setM(m);
        break;
    default:
        throw new IllegalArgumentException("Unsupported data encoding");
    }

    return result;
}