List of usage examples for com.amazonaws.services.dynamodbv2.document Item getMap
@SuppressWarnings("unchecked") public <T> Map<String, T> getMap(String attrName)
T's; or null if the attribute either doesn't exist or the attribute value is null. From source file:com.exorath.service.lobbymsg.impl.DynamoDBService.java
License:Apache License
@Override public Map<String, Message> fetchMessagesByGameId() throws Exception { Item item = db.getTable(tableName).getItem(getMapMessagesSpec()); if (item == null || !item.hasAttribute(MSGS_FIELD)) return new HashMap<>(); Map<String, Map<String, Object>> messages = item.getMap(MSGS_FIELD); return mapMessages(messages); }
From source file:com.innoq.hagmans.bachelor.DynamoDBUtils.java
License:Open Source License
/** * Persists the given temperatures on DynamoDB * /*w w w. j ava 2s. c o m*/ * @param tableName * The name of the table, where the records will be persisted * @param temperatureMap * A map containing the sensor names as the key, and as the value * a hashmap with the timestamp of the temperature as the key and * the temperature as the value * @param timestamp * The timestamp of the run */ public void putTemperatures(String tableName, HashMap<String, HashMap<String, String>> temperatureMap, long timestamp) { Table table = dynamoDB.getTable(tableName); for (String sensor : temperatureMap.keySet()) { QuerySpec spec = new QuerySpec().withHashKey(ATTRIBUTE_NAME_HASH_KEY, sensor).withRangeKeyCondition( new RangeKeyCondition(ATTRIBUTE_NAME_RANGE_KEY).eq(String.valueOf(timestamp))); ItemCollection<QueryOutcome> items = table.query(spec); Iterator<Item> iterator = items.iterator(); Item item = null; Map<String, String> temperatures = null; while (iterator.hasNext()) { item = iterator.next(); temperatures = item.getMap(ATTRIBUTE_NAME_TEMPERATURE); } if (temperatures == null) { temperatures = new HashMap<>(); } temperatures.putAll(temperatureMap.get(sensor)); table.putItem(new Item().withPrimaryKey(ATTRIBUTE_NAME_HASH_KEY, sensor, ATTRIBUTE_NAME_RANGE_KEY, String.valueOf(timestamp)).withMap(ATTRIBUTE_NAME_TEMPERATURE, temperatures)); System.out.println("PutItem succeeded!"); } }
From source file:com.innoq.hagmans.bachelor.DynamoDBUtils.java
License:Open Source License
/** * Gibt eine @HashMap mit allen Temperaturen zurck fr den bergebenen * Sensor//from ww w . ja v a2 s . co m * * @param sensor * @param tableName * @return @Hashmap, die als Key einen Timestamp enthalten, zu dessen * Zeitpunkt die Daten des Sensors erfasst werden und die Values * sind eine Liste der Temperaturen des Sensors zum Timestamp */ public HashMap<String, HashMap<String, Object>> getTemperaturesForSensor(String sensor, String tableName) { Table table = dynamoDB.getTable(tableName); QuerySpec spec = new QuerySpec().withHashKey(ATTRIBUTE_NAME_HASH_KEY, sensor); ItemCollection<QueryOutcome> items = table.query(spec); Iterator<Item> iterator = items.iterator(); Item item = null; HashMap<String, HashMap<String, Object>> temperatureMap = new HashMap<>(); while (iterator.hasNext()) { item = iterator.next(); temperatureMap.put(item.getString(ATTRIBUTE_NAME_RANGE_KEY), new HashMap<>(item.getMap(ATTRIBUTE_NAME_TEMPERATURE))); } return temperatureMap; }
From source file:ws.salient.aws.dynamodb.DynamoDBStore.java
License:Apache License
public void put(Session session, Command command, int requestIndex) { try {// w w w. j ava2 s.c o m eventsToPut.offer(encrypt( new Item() .withPrimaryKey("sessionId", session.getSessionId(), "timestamp", NANO_INSTANT.format(command.getTimestamp().plusNanos(requestIndex))) .withBinary("command", json.writeValueAsBytes(command)), session.getSecretKey(), "command")); if (session.store(command)) { byte[] sessionBytes = session.toByteArray(); byte[] properties = json.writeValueAsBytes(session.getProperties()); Item item = new Item() .withPrimaryKey("sessionId", command.getSessionId(), "timestamp", command.getTimestamp().toString()) .withString("accountId", command.getAccountId()) .withMap("factCount", session.getFactCount()) .withInt("processCount", session.getProcessCount()) .withString("knowledgeBaseId", command.getKnowledgeBaseId()) .withBinary("session", sessionBytes).withBinary("properties", properties); if (session.getSecretKey() != null) { item.withMap("secretKey", new LinkedHashMap()); item.getMap("secretKey").put("encrypted", session.getEncryptedKey()); item.getMap("secretKey").put("algorithm", session.getSecretKey().getAlgorithm()); } if (session.getSecretKey() != null) { item = encrypt(item, session.getSecretKey(), "properties", "session"); } sessionsToPut.offer(item); } putItemExecutor.execute(() -> { List<Item> eventItems = new LinkedList(); Item eventItem = eventsToPut.poll(); while (eventItem != null) { eventItems.add(eventItem); eventItem = eventsToPut.poll(); } if (!eventItems.isEmpty()) { TableWriteItems eventWriteItems = new TableWriteItems("SalientSessionEvent") .withItemsToPut(eventItems); log.info("Storing events: " + eventItems.size()); BatchWriteItemOutcome result = dynamodb.batchWriteItem(eventWriteItems); if (!result.getUnprocessedItems().isEmpty()) { log.error("Unprocessed items: " + result.toString()); } } Map<String, Item> sessionItems = new LinkedHashMap(); Item sessionItem = sessionsToPut.poll(); while (sessionItem != null) { // Only store latest session item sessionItems.put(sessionItem.getString("sessionId"), sessionItem); sessionItem = sessionsToPut.poll(); } if (!sessionItems.isEmpty()) { TableWriteItems sessionWriteItems = new TableWriteItems("SalientSession") .withItemsToPut(sessionItems.values()); log.info("Storing sessions: " + sessionItems.size()); BatchWriteItemOutcome result = dynamodb.batchWriteItem(sessionWriteItems); if (!result.getUnprocessedItems().isEmpty()) { log.error("Unprocessed items: " + result.toString()); } } }); } catch (JsonProcessingException ex) { throw new RuntimeException(ex); } }
From source file:ws.salient.aws.dynamodb.DynamoDBStore.java
License:Apache License
public Session get(Command command, KnowledgeRepository repository, Properties properties, Injector parentInjector, Sessions sessions, QuerySpec sessionQuery) { String sessionId = command.getSessionId(); String accountId = command.getAccountId(); SecretKeySpec secretKey;// w w w . j a v a 2 s . c om ByteBuffer encryptedKey; Session session = new Session(sessionId); Page<Item, QueryOutcome> page = dynamodb.getTable("SalientSession").query(sessionQuery).firstPage(); if (page != null && page.size() > 0) { try { Item result = page.iterator().next(); encryptedKey = ByteBuffer.wrap((byte[]) result.getMap("secretKey").get("encrypted")); if (encryptedKey != null) { DecryptResult decrypt = kms.decrypt(new DecryptRequest() .addEncryptionContextEntry("accountId", accountId) .addEncryptionContextEntry("sessionId", sessionId).withCiphertextBlob(encryptedKey)); byte[] key = decrypt.getPlaintext().array(); secretKey = new SecretKeySpec(key, (String) result.getMap("secretKey").get("algorithm")); } else { secretKey = null; } result = decrypt(result, secretKey, "properties", "session"); properties = json.readValue(result.getBinary("properties"), Properties.class); String knowledgeBaseId = result.getString("knowledgeBaseId"); KnowledgeBase knowledgeBase = repository.getKnowledgeBase(knowledgeBaseId); String timestamp = result.getString("timestamp"); session.init(knowledgeBase, properties, parentInjector, Instant.parse(timestamp), result.getBinary("session"), sessions); int processCount = session.getProcessCount(); List<Item> eventItems = new LinkedList(); ItemCollection<QueryOutcome> query = dynamodb.getTable("SalientSessionEvent") .query(new QuerySpec().withConsistentRead(true).withHashKey("sessionId", sessionId) .withRangeKeyCondition(new RangeKeyCondition("timestamp").gt(timestamp))); query.pages().forEach((eventPage) -> { eventPage.forEach((eventItem) -> { eventItems.add(eventItem); }); }); List<Command> commands = new LinkedList(); eventItems.forEach((eventItem) -> { try { eventItem = decrypt(eventItem, secretKey, "command"); byte[] value = eventItem.getBinary("command"); ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(value)) { protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { return session.getKnowledgeBase().getContainer().getClassLoader() .loadClass(desc.getName()); } }; Command event = (Command) objectIn.readObject(); if (event instanceof WorkItem) { session.getWorkItemHandlers().forEach((handler) -> { handler.getCompletedWorkItemIds().add(((WorkItem) event).getWorkItemId()); }); } commands.add(event); } catch (ClassNotFoundException | IOException ex) { throw new RuntimeException(ex); } }); commands.forEach((event) -> { session.accept(event); }); session.getWorkItemHandlers().forEach((handler) -> { handler.getCompletedWorkItemIds().clear(); }); } catch (IOException ex) { throw new RuntimeException(ex); } } else { GenerateDataKeyResult dataKey = generateEncryptionKey(accountId, sessionId); byte[] key = dataKey.getPlaintext().array(); secretKey = new SecretKeySpec(key, "AES"); encryptedKey = dataKey.getCiphertextBlob(); KnowledgeBase knowledgeBase = repository.getKnowledgeBase(command.getKnowledgeBaseId()); session.init(knowledgeBase, properties, parentInjector, command.getTimestamp(), sessions); } session.setEncryptedKey(encryptedKey); session.setSecretKey(secretKey); return session; }
From source file:ws.salient.aws.dynamodb.DynamoDBStore.java
License:Apache License
public Item encrypt(Item item, SecretKeySpec key, String... attributes) { try {//from www. j a va2 s . c om if (key != null) { Cipher cipher = Cipher.getInstance(transformation); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] iv = cipher.getIV(); for (String attribute : attributes) { byte[] value = item.getBinary(attribute); item.withBinary(attribute, cipher.doFinal(value)); } item.withMap("cipher", new LinkedHashMap()); item.getMap("cipher").put("transformation", transformation); item.getMap("cipher").put("iv", iv); } return item; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { throw new RuntimeException(ex); } }
From source file:ws.salient.aws.dynamodb.DynamoDBStore.java
License:Apache License
public Item decrypt(Item item, SecretKeySpec key, String... attributes) { try {/* w w w . j a v a2 s .c o m*/ if (key != null) { String transformation = (String) item.getMap("cipher").get("transformation"); byte[] iv = (byte[]) item.getMap("cipher").get("iv"); Cipher cipher = Cipher.getInstance(transformation); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); for (String attribute : attributes) { byte[] value = item.getBinary(attribute); item.withBinary(attribute, cipher.doFinal(value)); } } return item; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) { throw new RuntimeException(ex); } }