List of usage examples for com.amazonaws.services.dynamodbv2.document.utils ValueMap ValueMap
ValueMap
From source file:NYSEQuery.java
License:Open Source License
private static void query(String tableName) { Table table = null;//from ww w.ja v a 2s.co m try { // Create table if it does not exist yet if (!Tables.doesTableExist(dynamoDB, tableName)) { System.out.println("Table " + tableName + " is does not exist"); } else { table = dynamo.getTable(tableName); } // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html // select stockTicker, tradeDate, v from stock_eod // where stockTicker = 'LEA' and tradeDate between '02-Oct-2013' and '03-Oct-2013' QuerySpec spec = new QuerySpec().withProjectionExpression("stockTicker,tradeDate,v") .withKeyConditionExpression("stockTicker = :v_st and tradeDate between :v_sd and :v_ed") // .withFilterExpression("contains(tradeDate, :v_t)") .withValueMap(new ValueMap().withString(":v_st", "LEA").withString(":v_sd", "02-Oct-2013") .withString(":v_ed", "03-Oct-2013") // .withString(":v_td", "01-Oct-2013") // .withString(":v_t", "Oct") ).withConsistentRead(true); ItemCollection<QueryOutcome> items = table.query(spec); Iterator<Item> iterator = items.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().toJSONPretty()); } } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with AWS, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } }
From source file:com.achow101.bittipaddr.server.addressServiceImpl.java
License:Open Source License
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the id String requestURI = request.getRequestURI(); String id = requestURI.substring(requestURI.lastIndexOf("/") + 1); // Setup the aws dynamo db client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); DynamoDB dynamoDB = new DynamoDB(client); // Setup blockcypher API BlockCypherContext blockCypherContext = new BlockCypherContext("v1", "btc", "main", "4d3109a5c07f426da9ccc2943da39244"); // Lookup ID and get current address, increment index String address = ""; Table table = dynamoDB.getTable("Bittipaddrs"); int currAddrInx = 0; try {/*from w w w . j av a 2 s .com*/ Item item = table.getItem("ID", id); currAddrInx = item.getInt("AddrIndex"); int origIndx = currAddrInx; List<String> addresses = item.getList("Addresses"); if (currAddrInx < addresses.size()) { address = addresses.get(currAddrInx); while (blockCypherContext.getAddressService().getAddress(address).getnTx() > 0 && currAddrInx < addresses.size()) { // Increment index and get next address currAddrInx++; address = addresses.get(currAddrInx); // Wait one third of a second to prevent rate limiting Thread.sleep(334); } } else { address = addresses.get(addresses.size() - 1); } // Update index if DB if it has changed if (currAddrInx != origIndx) { UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("ID", id) .withUpdateExpression("set AddrIndex=:i") .withValueMap(new ValueMap().withNumber(":i", currAddrInx)); table.updateItem(updateItemSpec); } } // Deal with rate limiting from BlockCypher catch (BlockCypherException e) { UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("ID", id) .withUpdateExpression("set AddrIndex=:i") .withValueMap(new ValueMap().withNumber(":i", currAddrInx)); table.updateItem(updateItemSpec); } catch (Exception e) { System.out.println("Error in getting item."); } // Send them a redirect to the bitcoin uri if redirect is set if (request.getParameter("redirect") != null) { response.sendRedirect("bitcoin:" + address); } else { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<a href=bitcoin:" + address + ">" + address + "</a>"); } }
From source file:com.achow101.bittipaddr.server.bittipaddrServiceImpl.java
License:Open Source License
public String addAddresses(AddrReq req) { // Setup the aws dynamo db client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Bittipaddrs"); // Check that the request is for editing an existing one if (!req.getId().equals("NEW")) { try {/*from ww w . j a va 2 s.co m*/ Item item = table.getItem("ID", req.getId()); // Check the password if (getHash(req.getPassword()).equals(item.getString("passhash"))) { // If the req has been edited, update DB if (req.isEdited()) { // Recalculate addresses if xpub is set if (!req.getXpub().equals("NONE")) { try { // Check Xpub DeterministicKey xpub = DeterministicKey.deserializeB58(req.getXpub(), params); DeterministicKey external = HDKeyDerivation.deriveChildKey(xpub, 0); // Derive 1000 addresses and add to req String[] addrs = new String[1000]; for (int i = 0; i < 1000; i++) { addrs[i] = HDKeyDerivation.deriveChildKey(external, i).toAddress(params) .toBase58(); } req.setAddresses(addrs); } catch (Exception e) { return "<p style=\"color:red;\">Invalid xpub" + req.getXpub() + "</p>"; } } if (req.getAddresses()[0].isEmpty()) return "<p style=\"color:red;\">Must have at least one address</p>"; UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("ID", req.getId()) .withUpdateExpression("set AddrIndex=:i, Addresses=:a, bip32xpub=:x") .withValueMap(new ValueMap().withNumber(":i", 0) .withList(":a", Arrays.asList(req.getAddresses())) .withString(":x", req.getXpub())); table.updateItem(updateItemSpec); return req.getHtml(); } String[] addresses = new String[item.getList("Addresses").size()]; item.getList("Addresses").toArray(addresses); req.setAddresses(addresses); req.setXpub(item.getString("bip32xpub")); if (req.isEditable()) return req.getPlain(); else return req.getHtml(); } else return "<p style=\"color:red;\">Incorrect password</p>"; } catch (Exception e) { return "<p style=\"color:red;\">Could not find unit</p>"; } } // Check validity of addresses else if (req.getXpub().equals("NONE") && req.getAddresses().length != 0) { for (int i = 0; i < req.getAddresses().length; i++) { try { Address addr = Address.fromBase58(params, req.getAddresses()[i]); } catch (AddressFormatException e) { return "<p style=\"color:red;\">Invalid address" + req.getAddresses()[i] + "</p>"; } } } // Check validity of xpub else if (!req.getXpub().equals("NONE") && req.getAddresses().length == 0) { try { // Check Xpub DeterministicKey xpub = DeterministicKey.deserializeB58(req.getXpub(), params); DeterministicKey external = HDKeyDerivation.deriveChildKey(xpub, 0); // Derive 1000 addresses and add to req String[] addrs = new String[1000]; for (int i = 0; i < 1000; i++) { addrs[i] = HDKeyDerivation.deriveChildKey(external, i).toAddress(params).toBase58(); } req.setAddresses(addrs); } catch (Exception e) { return "<p style=\"color:red;\">Invalid xpub" + req.getXpub() + "</p>"; } } // Set the request ID and unique password req.setId(new BigInteger(40, random).toString(32)); req.setPassword(new BigInteger(256, random).toString(32)); // Add request to DynamoDB Item item = null; try { item = new Item().withPrimaryKey("ID", req.getId()).withInt("AddrIndex", 0) .withList("Addresses", Arrays.asList(req.getAddresses())).withString("bip32xpub", req.getXpub()) .withString("passhash", getHash(req.getPassword())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } table.putItem(item); return req.getHtml(); }
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.DynamoDocumentStoreTemplate.java
License:Apache License
private <T extends Item> ScanSpec generateScanSpec(final AttributeQuery query, final Class<T> tableItemType) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { final Class<?> clazz = getScanSpecOperandType(query.getAttributeName(), tableItemType); ScanSpec scanSpec = new ScanSpec(); final StringBuilder filterExpression = new StringBuilder(); final ValueMap valueMap = new ValueMap(); int valueMapCount = 0; if (query.getCondition().getComparisonOperator() == Operators.NULL) { filterExpression.append("attribute_not_exists(").append(query.getAttributeName()).append(")"); } else if (query.getCondition().getComparisonOperator() == Operators.NOT_NULL) { filterExpression.append("attribute_exists(").append(query.getAttributeName()).append(")"); } else {// w w w .j a va 2s .c o m if (query.getCondition().getComparisonOperator() == Operators.EQUALS) { filterExpression.append(query.getAttributeName()).append(" IN ("); final Iterator<String> valueIterator = query.getCondition().getValues().iterator(); while (valueIterator.hasNext()) { filterExpression.append(":").append(valueMapCount); valueMap.with(":" + valueMapCount, valueIterator.next()); valueMapCount++; if (valueIterator.hasNext()) { filterExpression.append(","); } } filterExpression.append(")"); } else if (query.getCondition().getComparisonOperator() == Operators.LESS_THAN_OR_EQUALS) { if (query.getCondition().getValues().size() == 1) { filterExpression.append(query.getAttributeName()).append(" <= ").append(":") .append(valueMapCount); final Object valueInstance = clazz.getConstructor(String.class) .newInstance(query.getCondition().getValues().iterator().next()); valueMap.with(":" + valueMapCount, valueInstance); valueMapCount++; } else { // throw exeption?? } } else if (query.getCondition().getComparisonOperator() == Operators.GREATER_THAN_OR_EQUALS) { if (query.getCondition().getValues().size() == 1) { filterExpression.append(query.getAttributeName()).append(" >= ").append(":") .append(valueMapCount); final Object valueInstance = clazz.getConstructor(String.class) .newInstance(query.getCondition().getValues().iterator().next()); valueMap.with(":" + valueMapCount, valueInstance); valueMapCount++; } else { // throw exeption?? } } } if (filterExpression.length() > 0) { scanSpec = scanSpec.withFilterExpression(filterExpression.toString()); } if (valueMap.size() > 0) { scanSpec = scanSpec.withValueMap(valueMap); } return scanSpec; }
From source file:com.eho.dynamodb.DynamoDBConnection.java
public static UpdateItemOutcome update_resource(String resource) throws Exception { String id;/* w ww. ja va2 s . co m*/ JSONObject json_resource = new JSONObject(resource); //does the resource have a primary key? if (json_resource.has(PRIMARY_KEY))//if it does not have a primary key, create one using uuid id = json_resource.getString(PRIMARY_KEY); else id = UUID.randomUUID().toString(); DynamoDB dynamoDB = new DynamoDB(dynamoDBClient); Table table = dynamoDB.getTable(PATIENT_TABLE); //lets retreive based on the key. if key invalid (not assigned yet) nullis returned. Item retreived_item = table.getItem(PRIMARY_KEY, id); if (retreived_item == null)//if null instantiate it { retreived_item = new Item(); retreived_item.withPrimaryKey(PRIMARY_KEY, id); } Integer new_version = retreived_item.getInt("version") + 1; retreived_item.withInt("version", new_version); String new_version_str = new_version.toString(); UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(PRIMARY_KEY, id) .withUpdateExpression("SET " + new_version_str + "= :newval") .withValueMap(new ValueMap().withString(":newval", resource)).withReturnValues(ReturnValue.ALL_NEW); return table.updateItem(updateItemSpec); }
From source file:com.erudika.para.persistence.AWSDynamoDAO.java
License:Apache License
private <P extends ParaObject> String readPageFromSharedTable(String appid, Pager pager, LinkedList<P> results) { String lastKeyFragment = ""; ValueMap valueMap = new ValueMap().withString(":aid", appid); NameMap nameMap = null;/*from w ww .j a v a2 s. c om*/ if (!StringUtils.isBlank(pager.getLastKey())) { lastKeyFragment = " and #stamp > :ts"; valueMap.put(":ts", pager.getLastKey()); nameMap = new NameMap().with("#stamp", Config._TIMESTAMP); } Index index = getSharedIndex(); QuerySpec spec = new QuerySpec().withMaxPageSize(pager.getLimit()).withMaxResultSize(pager.getLimit()) .withKeyConditionExpression(Config._APPID + " = :aid" + lastKeyFragment).withValueMap(valueMap) .withNameMap(nameMap); if (index != null) { Page<Item, QueryOutcome> items = index.query(spec).firstPage(); for (Item item : items) { P obj = ParaObjectUtils.setAnnotatedFields(item.asMap()); if (obj != null) { results.add(obj); } } } if (!results.isEmpty()) { return Long.toString(results.peekLast().getTimestamp()); } else { return null; } }
From source file:com.exorath.service.lobbymsg.impl.DynamoDBService.java
License:Apache License
public static UpdateItemSpec getCheckMsgsMapExistsSpec() { return new UpdateItemSpec().withPrimaryKey(getPrimaryKey()) .withUpdateExpression("SET " + MSGS_FIELD + " = if_not_exists(" + MSGS_FIELD + ", :empty)") .withValueMap(new ValueMap().withMap(":empty", new HashMap<>())); }
From source file:com.exorath.service.lobbymsg.impl.DynamoDBService.java
License:Apache License
public static UpdateItemSpec getCheckMsgMapInMsgsMapExistsSpec(String gameId) { return new UpdateItemSpec() .withPrimaryKey(getPrimaryKey()).withUpdateExpression("SET " + MSGS_FIELD + "." + gameId + " = if_not_exists(" + MSGS_FIELD + "." + gameId + ", :empty)") .withValueMap(new ValueMap().withMap(":empty", new HashMap<>())); }
From source file:com.exorath.service.lobbymsg.impl.DynamoDBService.java
License:Apache License
public static UpdateItemSpec getUpdateItemSpec(String gameId, Message message) { String updateExpression;// ww w .j a v a 2 s . c o m ValueMap valueMap = new ValueMap(); if (message.getMsg() == null) updateExpression = "REMOVE " + MSGS_FIELD + "." + gameId; else { updateExpression = "SET " + MSGS_FIELD + "." + gameId + "=:msgMap"; ValueMap msgMap = new ValueMap().withString(MSG_FIELD, message.getMsg()); if (message.getFormat() != null) msgMap.withString(FORMAT_FIELD, message.getFormat()); valueMap.withMap(":msgMap", msgMap); } if (valueMap.isEmpty()) valueMap = null; System.out.println(updateExpression); return new UpdateItemSpec().withPrimaryKey(getPrimaryKey()).withUpdateExpression(updateExpression) .withValueMap(valueMap); }
From source file:com.netflix.hollow.example.producer.infrastructure.DynamoDBAnnouncer.java
License:Apache License
@Override public void announce(long stateVersion) { Table table = dynamoDB.getTable(tableName); UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("namespace", blobNamespace) .withUpdateExpression("set #version = :ver").withNameMap(new NameMap().with("#version", "version")) .withValueMap(new ValueMap().withNumber(":ver", stateVersion)); table.updateItem(updateItemSpec);/* w w w . ja v a 2 s . c om*/ }