Example usage for com.amazonaws.services.dynamodbv2.document Table putItem

List of usage examples for com.amazonaws.services.dynamodbv2.document Table putItem

Introduction

In this page you can find the example usage for com.amazonaws.services.dynamodbv2.document Table putItem.

Prototype

@Override
    public PutItemOutcome putItem(PutItemSpec spec) 

Source Link

Usage

From source file:AddUserPassword.java

License:Open Source License

public static void main(String[] args) throws Exception {

    AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());

    DynamoDB dynamoDB = new DynamoDB(client);

    Table table = dynamoDB.getTable("UserLogin");

    int UserID = 0;
    String UserName = "Patrick Laflin";
    int UserPassword = 18924;

    try {//from   www.j a v a  2 s  .  com
        System.out.println("Adding a new item...");
        PutItemOutcome outcome = table.putItem(new Item().withPrimaryKey("UserID", UserID)
                .withString("User Name", UserName).withNumber("User Password", UserPassword));

        System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult());

    } catch (Exception e) {
        System.err.println("Unable to add item: " + UserID + " " + UserName);
        System.err.println(e.getMessage());
    }

}

From source file:AddUserInfo.java

License:Open Source License

public static void main(String[] args) throws Exception {

    AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());

    DynamoDB dynamoDB = new DynamoDB(client);

    Table table = dynamoDB.getTable("UserInfo");

    int UserID = 0;
    String FirstName = "Patrick";
    String LastName = "Laflin";
    String PhoneNumber = "(850)276-3816";
    String StreetAddressLine1 = "118 E Lakeshore Drive";
    String StreetAddressLine2 = "Unit B";
    String City = "Panama City Beach";
    String State = "FL";
    int ZipCode = 32413;
    String EmailAddress = "pbl14@my.fsu.edu";

    try {// ww  w. j a v  a  2 s  . co  m
        System.out.println("Adding a new item...");
        PutItemOutcome outcome = table.putItem(new Item().withPrimaryKey("UserID", UserID)
                .withString("First Name", FirstName).withString("Last Name", LastName)
                .withString("Phone Number", PhoneNumber).withString("Street Address Line 1", StreetAddressLine1)
                .withString("Street Address Line 2", StreetAddressLine2).withString("City", City)
                .withString("State", State).withNumber("Zip Code", ZipCode)
                .withString("Email Address", EmailAddress));

        System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult());

    } catch (Exception e) {
        System.err.println("Unable to add item: " + UserID);
        System.err.println(e.getMessage());
    }

}

From source file:AddUserRoutes.java

License:Open Source License

public static void main(String[] args) throws Exception {

    AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());

    DynamoDB dynamoDB = new DynamoDB(client);

    Table table = dynamoDB.getTable("UserRoutes");

    int UserID = 0;
    String Route1 = "NULL";
    String Route2 = "NULL";
    String Route3 = "NULL";
    String Route4 = "NULL";
    String Route5 = "NULL";

    try {//from  w ww.ja v  a  2  s  . co m
        System.out.println("Adding a new item...");
        PutItemOutcome outcome = table.putItem(new Item().withPrimaryKey("UserID", UserID)
                .withString("Route 1", Route1).withString("Route 2", Route2).withString("Route 3", Route3)
                .withString("Route 4", Route4).withString("Route 5", Route5));

        System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult());

    } catch (Exception e) {
        System.err.println("Unable to add item: " + UserID);
        System.err.println(e.getMessage());
    }

}

From source file:AddUserFavorites.java

License:Open Source License

public static void main(String[] args) throws Exception {

    AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());

    DynamoDB dynamoDB = new DynamoDB(client);

    Table table = dynamoDB.getTable("UserFavorites");

    int UserID = 0;
    String Location1 = "NULL";
    String Location2 = "NULL";
    String Location3 = "NULL";
    String Location4 = "NULL";
    String Location5 = "NULL";

    try {/*  w  w  w. j av  a2s  .  c  o m*/
        System.out.println("Adding a new item...");
        PutItemOutcome outcome = table
                .putItem(new Item().withPrimaryKey("UserID", UserID).withString("Location 1", Location1)
                        .withString("Location 2", Location2).withString("Location 3", Location3)
                        .withString("Location 4", Location4).withString("Location 5", Location5));

        System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult());

    } catch (Exception e) {
        System.err.println("Unable to add item: " + UserID);
        System.err.println(e.getMessage());
    }

}

From source file:chatbot.LambdaFunctionHandler.java

License:Open Source License

@Override
public String handleRequest(SlackData input, Context context) {
    String sResponse = ", Welcome to Service Bot";
    try {/*from   w  ww . ja v  a 2  s.com*/
        //context.getLogger().log(input);
        context.getLogger().log("Input Code: " + input.getCode());
        context.getLogger().log("Input State: " + input.getState());
        Env objEnv = input.getEnv();
        String sURL = "https://slack.com/api/oauth.access";
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("client_id", objEnv.getClientId()));
        urlParameters.add(new BasicNameValuePair("client_secret", objEnv.getSlackClientSecret()));
        urlParameters.add(new BasicNameValuePair("code", input.getCode()));
        urlParameters.add(new BasicNameValuePair("redirect_uri", objEnv.getSlackRedirectUrl()));
        String jsonInString = invokeSlackAPI(sURL, urlParameters, context);
        ObjectMapper mapper = new ObjectMapper();
        //JSON from String to Object
        SlackAuth objSlackAuth = mapper.readValue(jsonInString, SlackAuth.class);
        sResponse = objSlackAuth.getTeam_name() + sResponse;
        sURL = "https://slack.com/api/channels.list";
        urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("token", objSlackAuth.getAccess_token()));
        jsonInString = invokeSlackAPI(sURL, urlParameters, context);
        //JSON from String to Object
        SlackChannels objSlackChannels = mapper.readValue(jsonInString, SlackChannels.class);
        System.out.println("Channels " + objSlackChannels.getChannels());
        String sSiteChannel_ID = null;
        String sBuyersChannel_ID = null;
        String sManagers_ID = null;
        for (Channel objChannel : objSlackChannels.getChannels()) {
            if (objChannel.getName().equals("site-engineers")) {
                sSiteChannel_ID = objChannel.getId();
            }
            if (objChannel.getName().equals("buyers")) {
                sBuyersChannel_ID = objChannel.getId();
            }
            if (objChannel.getName().equals("operations-managers")) {
                sManagers_ID = objChannel.getId();
            }
        }
        sURL = "https://slack.com/api/channels.create";
        if (sSiteChannel_ID == null) {
            urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("token", objSlackAuth.getAccess_token()));
            urlParameters.add(new BasicNameValuePair("name", "site-engineers"));
            jsonInString = invokeSlackAPI(sURL, urlParameters, context);
            ChannelAddResponse objChannelAddResponse = mapper.readValue(jsonInString, ChannelAddResponse.class);
            sSiteChannel_ID = (objChannelAddResponse.getChannel()).getId();
        }
        if (sBuyersChannel_ID == null) {
            urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("token", objSlackAuth.getAccess_token()));
            urlParameters.add(new BasicNameValuePair("name", "buyers"));
            jsonInString = invokeSlackAPI(sURL, urlParameters, context);
            ChannelAddResponse objChannelAddResponse = mapper.readValue(jsonInString, ChannelAddResponse.class);
            sBuyersChannel_ID = (objChannelAddResponse.getChannel()).getId();
        }
        if (sManagers_ID == null) {
            urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("token", objSlackAuth.getAccess_token()));
            urlParameters.add(new BasicNameValuePair("name", "operations-managers"));
            jsonInString = invokeSlackAPI(sURL, urlParameters, context);
            ChannelAddResponse objChannelAddResponse = mapper.readValue(jsonInString, ChannelAddResponse.class);
            sManagers_ID = (objChannelAddResponse.getChannel()).getId();
        }
        AmazonDynamoDBClient objClient = new AmazonDynamoDBClient(new EnvironmentVariableCredentialsProvider());
        DynamoDB dynamoDB = new DynamoDB(objClient);
        //Get all data set status inactive
        Item objNewTeam = new Item().withPrimaryKey("TEAM_ID", objSlackAuth.getTeam_id())
                .withString("TEAM_NAME", objSlackAuth.getTeam_name()).withString("CHANNEL_1", sSiteChannel_ID)
                .withString("CHANNEL_2", sBuyersChannel_ID).withString("CHANNEL_3", sManagers_ID)
                .withString("ACCESS_TOKEN", objSlackAuth.getAccess_token());
        Table tableCases = dynamoDB.getTable("ENTITY");
        tableCases.putItem(objNewTeam);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sResponse;
}

From source file:chatbot.ServiceAlertHandler.java

License:Open Source License

@Override
public String handleRequest(ServiceData input, Context context) {
    String message_response = "_Hello";
    try {//  w  w w  .  ja  va 2s.  c o  m
        context.getLogger().log("Input: " + input.getTemperature());
        int Min = 3000;
        int Max = 8000;
        int ID = 0;
        while (true) {
            ID = Min + (int) (Math.random() * ((Max - Min) + 1));
            if (objIDList.containsKey(new Integer(ID))) {
                continue;
            } else
                break;
        }
        AmazonDynamoDBClient objClient = new AmazonDynamoDBClient(new EnvironmentVariableCredentialsProvider());
        DynamoDB dynamoDB = new DynamoDB(objClient);
        //Get all data set status inactive
        DynamoDBMapper mapper = new DynamoDBMapper(objClient);
        FindCasesActive(mapper, input.getTeam_id());
        Item objNewCase = new Item().withPrimaryKey("CASE_ID", ID).withString("USER", "unassigned")
                .withString("DESCRIPTION", "Blah").withString("STAGE", "0")
                .withString("TEAM_ID", input.getTeam_id()).withString("CASE_STATE", "ACTIVE");
        Table tableCases = dynamoDB.getTable("CASES");
        tableCases.putItem(objNewCase);

        message_response = "Service Alert : Priority - High";
        String sURL = "https://slack.com/api/chat.postMessage";
        HttpClient httpClient = HttpClients.createDefault();
        String sTeamId = input.getTeam_id();
        Entity objEntity = EntityHelper.getEntityObject(sTeamId);
        String sAuthToken = objEntity.getAccess_token();
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("token", sAuthToken));
        urlParameters.add(new BasicNameValuePair("channel", objEntity.getChannel_1()));
        urlParameters.add(new BasicNameValuePair("text", message_response));
        String sAttachment1 = "[\r\n        {\r\n            \"fallback\": \"Required plain-text summary of the attachment.\",\r\n             \"color\": \"#F35A00\",\r\n            \r\n            \"author_name\": \"Excavator System\",\r\n            \"author_link\": \"http://flickr.com/bobby/\",\r\n            \"author_icon\": \"http://flickr.com/icons/bobby.jpg\",\r\n            \"title\": \"Hydraulic Oil Temperature Alert\",\r\n            \"title_link\": \"https://api.slack.com/\",\r\n            \"text\": \"System detected abnormal rise in hydarulic oil temperature.\",\r\n            \"fields\": [                \r\n                {\r\n                    \"title\": \"Maximum\",\r\n                    \"value\": \"28\\u00B0 C\",\r\n                    \"short\": true\r\n                },\r\n                {\r\n                    \"title\": \"Recorded \",\r\n                    \"value\": \"";
        sAttachment1 += input.getTemperature();
        String sAttachment2 = "\\u00B0 C\",\r\n                    \"short\": true\r\n                }\r\n            ],\r\n            \"image_url\": \"http://servicebot.valueinnovation.co.in/slackhack/tempTrend1.jpg\",\r\n            \"thumb_url\": \"http://noamusic.fr/wp-content/rising-sea-levels-graph-7411.gif\",\r\n            \"footer\": \"MODEL 7830 L | SERIAL Number 8923901-23\",\r\n            \"footer_icon\": \"http://www.freeiconspng.com/uploads/alert-storm-warning-weather-icon--icon-search-engine-0.png\",\r\n            \"ts\":";
        long unixTime = System.currentTimeMillis() / 1000L;
        sAttachment2 += unixTime;
        String sAttachment3 = "\r\n        }\r\n    ]";
        urlParameters.add(new BasicNameValuePair("attachments", sAttachment1 + sAttachment2 + sAttachment3));
        HttpPost httpPost = new HttpPost(sURL);
        httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        System.out.println("POST Response Status:: " + httpResponse.getStatusLine().getStatusCode());
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        List<NameValuePair> urlParameters1 = new ArrayList<NameValuePair>();
        urlParameters1.add(new BasicNameValuePair("token", sAuthToken));
        urlParameters1.add(new BasicNameValuePair("channel", objEntity.getChannel_1()));
        try {
            Thread.sleep(4000);
        } catch (Exception e) {
        }
        urlParameters1.add(new BasicNameValuePair("text",
                "I recommend, we order a new coolant pump. Do you wish to see vendor parts?"));
        httpPost.setEntity(new UrlEncodedFormEntity(urlParameters1));
        httpResponse = httpClient.execute(httpPost);
        System.out.println("POST Response Status:: " + httpResponse.getStatusLine().getStatusCode());
        // print result
        System.out.println(response.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // TODO: implement your handler
    return "Hello " + input.getTemperature();
}

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  .  ja va 2  s  . c  o 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

@Override
public <T extends Item> T create(final T item,
        final PersistenceExceptionHandler<?>... persistenceExceptionHandlers) {
    item.setVersion(1l);/*from ww w  .  j a va2s.  c  o  m*/
    final ItemConfiguration itemConfiguration = getItemConfiguration(item.getClass());
    final Collection<PropertyDescriptor> createdConstraintPropertyDescriptors = createUniqueConstraintIndexes(
            item, itemConfiguration);
    final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName();
    final com.amazonaws.services.dynamodbv2.document.Item awsItem = com.amazonaws.services.dynamodbv2.document.Item
            .fromJSON(itemToString(item));
    final PutItemSpec putItemSpec = new PutItemSpec().withItem(awsItem);

    final Table table = dynamoDBClient.getTable(tableName);
    boolean itemRequestSucceeded = false;
    try {
        table.putItem(putItemSpec);
        itemRequestSucceeded = true;
    } finally {
        if (!itemRequestSucceeded) {
            try {
                deleteUniqueConstraintIndexes(item, itemConfiguration, createdConstraintPropertyDescriptors);
            } catch (final Exception deleteUniqueConstraintIndexesException) {
                logger.error(deleteUniqueConstraintIndexesException.getMessage(),
                        deleteUniqueConstraintIndexesException);
            }
        }
    }
    return item;
}

From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.DynamoDocumentStoreTemplate.java

License:Apache License

@Override
public <T extends Item> T update(final T item,
        final PersistenceExceptionHandler<?>... persistenceExceptionHandlers) {
    final ItemConfiguration itemConfiguration = getItemConfiguration(item.getClass());
    if (item.getVersion() == null) {
        return create(item);
    }//from   w ww . j  ava 2s.  co m

    final Expected expectedCondition = new Expected(VERSION_ATTRIBUTE).eq(item.getVersion());
    final Long newVersion = item.getVersion() + 1l;
    item.setVersion(newVersion);

    final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName();
    final String itemJson = itemToString(item);
    final PrimaryKey primaryKey = new PrimaryKey();
    final ItemId itemId = itemConfiguration.getItemId(item);
    final PrimaryKeyDefinition primaryKeyDefinition = itemConfiguration.primaryKeyDefinition();
    primaryKey.addComponent(primaryKeyDefinition.propertyName(), itemId.value());
    if (primaryKeyDefinition instanceof CompoundPrimaryKeyDefinition) {
        primaryKey.addComponent(((CompoundPrimaryKeyDefinition) primaryKeyDefinition).supportingPropertyName(),
                itemId.supportingValue());
    }
    final Table table = dynamoDBClient.getTable(tableName);
    final com.amazonaws.services.dynamodbv2.document.Item previousAwsItem = table.getItem(primaryKey);
    final String previousItemJson = previousAwsItem.toJSON();

    final String mergedJson = mergeJSONObjects(itemJson, previousItemJson);
    final com.amazonaws.services.dynamodbv2.document.Item awsItem = com.amazonaws.services.dynamodbv2.document.Item
            .fromJSON(mergedJson);
    final PutItemSpec putItemSpec = new PutItemSpec().withItem(awsItem).withExpected(expectedCondition);
    try {
        table.putItem(putItemSpec);
    } catch (final ConditionalCheckFailedException e) {
        throw new OptimisticLockException("Conflicting write detected while updating item");
    }
    return item;
}

From source file:com.eho.dynamodb.DynamoDBConnection.java

public static PutItemOutcome upload_resource_old(String resource) throws Exception {
    String id;//from  w  w w .  jav a 2s  . c om
    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);

    Item item_to_upload = Item.fromJSON(retreived_item.toJSONPretty()).withJSON("Document", resource);
    PutItemSpec putItemSpec = new PutItemSpec().withItem(item_to_upload).withReturnValues(ReturnValue.NONE);
    return table.putItem(putItemSpec);
}