

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Utilizzo degli elementi: Java
<a name="JavaDocumentAPIItemCRUD"></a>

Puoi utilizzare l'API AWS SDK per Java Document per eseguire operazioni tipiche di creazione, lettura, aggiornamento ed eliminazione (CRUD) sugli elementi di Amazon DynamoDB in una tabella.

**Nota**  
L'SDK per Java offre inoltre un modello di persistenza degli oggetti che permette di mappare le classi lato client alle tabelle DynamoDB. Questo approccio può ridurre la quantità di codice da scrivere. Per ulteriori informazioni, consulta [Java 1.x: Dinamo DBMapper](DynamoDBMapper.md).

Questa sezione contiene esempi Java per eseguire diverse operazioni operazioni sugli elementi dell'API documento Java e diversi esempi di lavoro completi.

**Topics**
+ [Collocazione di un elemento](#PutDocumentAPIJava)
+ [Ottenimento di un elemento](#JavaDocumentAPIGetItem)
+ [Scrittura in batch: collocazione ed eliminazione di più elementi](#BatchWriteDocumentAPIJava)
+ [Ricezione in batch: ricezione di più elementi](#JavaDocumentAPIBatchGetItem)
+ [Aggiornamento di un elemento](#JavaDocumentAPIItemUpdate)
+ [Eliminazione di un elemento](#DeleteMidLevelJava)
+ [Esempio: operazioni CRUD che utilizzano l'API del documento AWS SDK per Java](JavaDocumentAPICRUDExample.md)
+ [Esempio: operazioni Batch utilizzando l'API AWS SDK per Java dei documenti](batch-operation-document-api-java.md)
+ [Esempio: gestione degli attributi di tipo binario utilizzando l'API del AWS SDK per Java documento](JavaDocumentAPIBinaryTypeExample.md)

## Collocazione di un elemento
<a name="PutDocumentAPIJava"></a>

Il metodo `putItem` memorizza un item nella tabella. Se l'item esiste, lo sostituisce per intero. Se invece di sostituire l'intero item vuoi aggiornare solo attributi specifici, puoi utilizzare il metodo `updateItem`. Per ulteriori informazioni, consulta [Aggiornamento di un elemento](#JavaDocumentAPIItemUpdate). 

------
#### [ Java v2 ]

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import java.util.HashMap;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * To place items into an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client. See the EnhancedPutItem example.
 */
public class PutItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval>

                Where:
                    tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3).
                    key - The key used in the Amazon DynamoDB table (for example, Artist).
                    keyval - The key value that represents the item to get (for example, Famous Band).
                    albumTitle - The Album title (for example, AlbumTitle).
                    AlbumTitleValue - The name of the album (for example, Songs About Life ).
                    Awards - The awards column (for example, Awards).
                    AwardVal - The value of the awards (for example, 10).
                    SongTitle - The song title (for example, SongTitle).
                    SongTitleVal - The value of the song title (for example, Happy Day).
                **Warning** This program will  place an item that you specify into a table!
                """;

        if (args.length != 9) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        String albumTitle = args[3];
        String albumTitleValue = args[4];
        String awards = args[5];
        String awardVal = args[6];
        String songTitle = args[7];
        String songTitleVal = args[8];

        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle,
                songTitleVal);
        System.out.println("Done!");
        ddb.close();
    }

    public static void putItemInTable(DynamoDbClient ddb,
            String tableName,
            String key,
            String keyVal,
            String albumTitle,
            String albumTitleValue,
            String awards,
            String awardVal,
            String songTitle,
            String songTitleVal) {

        HashMap<String, AttributeValue> itemValues = new HashMap<>();
        itemValues.put(key, AttributeValue.builder().s(keyVal).build());
        itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build());
        itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build());
        itemValues.put(awards, AttributeValue.builder().s(awardVal).build());

        PutItemRequest request = PutItemRequest.builder()
                .tableName(tableName)
                .item(itemValues)
                .build();

        try {
            PutItemResponse response = ddb.putItem(request);
            System.out.println(tableName + " was successfully updated. The request id is "
                    + response.responseMetadata().requestId());

        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            System.err.println("Be sure that it exists and that you've typed its name correctly!");
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```

------
#### [ Java v1 ]

Completare la procedura riportata di seguito. 

1. Creare un'istanza della classe `DynamoDB`.

1. Crea un'istanza della classe `Table` per rappresentare la tabella con cui vuoi lavorare.

1. Crea un'istanza della classe `Item` per rappresentare il nuovo item. Devi specificare la chiave primaria del nuovo item e gli attributi.

1. Chiama il metodo `putItem` dell'oggetto `Table` usando l'elemento `Item` creato nella fase precedente.

Il seguente esempio di codice Java mostra le attività precedenti. Il codice scrive un nuovo item nella tabella `ProductCatalog`.

**Example**  

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

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

// Build a list of related items
List<Number> relatedItems = new ArrayList<Number>();
relatedItems.add(341);
relatedItems.add(472);
relatedItems.add(649);

//Build a map of product pictures
Map<String, String> pictures = new HashMap<String, String>();
pictures.put("FrontView", "http://example.com/products/123_front.jpg");
pictures.put("RearView", "http://example.com/products/123_rear.jpg");
pictures.put("SideView", "http://example.com/products/123_left_side.jpg");

//Build a map of product reviews
Map<String, List<String>> reviews = new HashMap<String, List<String>>();

List<String> fiveStarReviews = new ArrayList<String>();
fiveStarReviews.add("Excellent! Can't recommend it highly enough!  Buy it!");
fiveStarReviews.add("Do yourself a favor and buy this");
reviews.put("FiveStar", fiveStarReviews);

List<String> oneStarReviews = new ArrayList<String>();
oneStarReviews.add("Terrible product!  Do not buy this.");
reviews.put("OneStar", oneStarReviews);

// Build the item
Item item = new Item()
    .withPrimaryKey("Id", 123)
    .withString("Title", "Bicycle 123")
    .withString("Description", "123 description")
    .withString("BicycleType", "Hybrid")
    .withString("Brand", "Brand-Company C")
    .withNumber("Price", 500)
    .withStringSet("Color",  new HashSet<String>(Arrays.asList("Red", "Black")))
    .withString("ProductCategory", "Bicycle")
    .withBoolean("InStock", true)
    .withNull("QuantityOnHand")
    .withList("RelatedItems", relatedItems)
    .withMap("Pictures", pictures)
    .withMap("Reviews", reviews);

// Write the item to the table
PutItemOutcome outcome = table.putItem(item);
```

Nell'esempio precedente, l'item ha attributi scalari (`String`, `Number`, `Boolean`, `Null`), set (`String Set`) e tipi di documento (`List`, `Map`).

------

### Specifica dei parametri facoltativi
<a name="PutItemJavaDocumentAPIOptions"></a>

Insieme ai parametri richiesti, puoi anche specificare parametri opzionali per il metodo `putItem`. Ad esempio, il seguente esempio di codice Java utilizza un parametro facoltativo per specificare una condizione per il caricamento dell'item. Se la condizione specificata non è soddisfatta, genera un. AWS SDK per Java `ConditionalCheckFailedException` L'esempio di codice specifica i seguenti parametri facoltativi nel metodo `putItem`:
+ un item `ConditionExpression` che definisce le condizioni della richiesta. Il codice definisce la condizione in cui l'item esistente che ha la stessa chiave primaria viene sostituito solo se ha un attributo ISBN uguale a un valore specifico. 
+ Una mappa per `ExpressionAttributeValues` che viene usata nella condizione. In questo caso, è necessaria una sola sostituzione: il segnaposto `:val` nell'espressione della condizione viene sostituito al runtime con il valore ISBN effettivo da verificare.

Nell'esempio seguente viene aggiunto un nuovo item del libro utilizzando questi parametri facoltativi.

**Example**  

```
Item item = new Item()
    .withPrimaryKey("Id", 104)
    .withString("Title", "Book 104 Title")
    .withString("ISBN", "444-4444444444")
    .withNumber("Price", 20)
    .withStringSet("Authors",
        new HashSet<String>(Arrays.asList("Author1", "Author2")));

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val", "444-4444444444");

PutItemOutcome outcome = table.putItem(
    item,
    "ISBN = :val", // ConditionExpression parameter
    null,          // ExpressionAttributeNames parameter - we're not using it for this example
    expressionAttributeValues);
```

### PutItem e documenti JSON
<a name="PutItemJavaDocumentAPI.JSON"></a>

È possibile memorizzare un documento JSON come attributo in una tabella DynamoDB. Per eseguire questa operazione, usa il metodo `withJSON` di `Item`. Questo metodo analizza il documento JSON e mappa ciascun elemento a un tipo di dati DynamoDB nativo.

Supponiamo di voler memorizzare il seguente documento JSON, contenente i fornitori in grado di soddisfare gli ordini di un determinato prodotto.

**Example**  

```
{
    "V01": {
        "Name": "Acme Books",
        "Offices": [ "Seattle" ]
    },
    "V02": {
        "Name": "New Publishers, Inc.",
        "Offices": ["London", "New York"
        ]
    },
    "V03": {
        "Name": "Better Buy Books",
        "Offices": [ "Tokyo", "Los Angeles", "Sydney"
        ]
    }
}
```

Puoi utilizzare il metodo `withJSON` per memorizzarlo nella tabella `ProductCatalog`, in un attributo `Map` denominato `VendorInfo`. Il seguente codice di esempio Java dimostra come eseguire questa operazione.

```
// Convert the document into a String.  Must escape all double-quotes.
String vendorDocument = "{"
    + "    \"V01\": {"
    + "        \"Name\": \"Acme Books\","
    + "        \"Offices\": [ \"Seattle\" ]"
    + "    },"
    + "    \"V02\": {"
    + "        \"Name\": \"New Publishers, Inc.\","
    + "        \"Offices\": [ \"London\", \"New York\"" + "]" + "},"
    + "    \"V03\": {"
    + "        \"Name\": \"Better Buy Books\","
    +          "\"Offices\": [ \"Tokyo\", \"Los Angeles\", \"Sydney\""
    + "            ]"
    + "        }"
    + "    }";

Item item = new Item()
    .withPrimaryKey("Id", 210)
    .withString("Title", "Book 210 Title")
    .withString("ISBN", "210-2102102102")
    .withNumber("Price", 30)
    .withJSON("VendorInfo", vendorDocument);

PutItemOutcome outcome = table.putItem(item);
```

## Ottenimento di un elemento
<a name="JavaDocumentAPIGetItem"></a>

Per recuperare un singolo item usa il metodo `getItem` di un oggetto `Table`. Completare la procedura riportata di seguito. 

1. Creare un'istanza della classe `DynamoDB`.

1. Crea un'istanza della classe `Table` per rappresentare la tabella con cui vuoi lavorare.

1. Chiama il metodo `getItem` dell'istanza di `Table`. Devi specificare la chiave primaria dell'item che intendi recuperare.

Il seguente esempio di codice Java mostra le fasi precedenti. Il codice ottiene l'item che ha la chiave di partizione specificata.

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

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

Item item = table.getItem("Id", 210);
```

### Specifica dei parametri facoltativi
<a name="GetItemJavaDocumentAPIOptions"></a>

Insieme ai parametri richiesti, puoi anche specificare parametri opzionali per il metodo `getItem`. Ad esempio, il seguente esempio di codice Java utilizza un metodo facoltativo per recuperare un solo elenco specifico di attributi e per specificare letture fortemente consistenti. Per ulteriori informazioni sulla lettura consistente, consulta [Coerenza di lettura di DynamoDB](HowItWorks.ReadConsistency.md).

Puoi usare un `ProjectionExpression` per recuperare solo attributi o elementi specifici, piuttosto che un intero item. Un `ProjectionExpression` può specificare attributi nidificati o di primo livello usando i percorsi dei documenti. Per ulteriori informazioni, consulta [Utilizzo di espressioni di proiezione in DynamoDB](Expressions.ProjectionExpressions.md).

I parametri del metodo `getItem` non consentono di specificare lettura coerente. Tuttavia, puoi creare un `GetItemSpec`, che fornisce l'accesso completo a tutti gli input all'operazione `GetItem` di basso livello. Il seguente esempio di codice consente di creare un `GetItemSpec` e utilizzare tale specifica come input per il metodo `getItem`.

**Example**  

```
GetItemSpec spec = new GetItemSpec()
    .withPrimaryKey("Id", 206)
    .withProjectionExpression("Id, Title, RelatedItems[0], Reviews.FiveStar")
    .withConsistentRead(true);

Item item = table.getItem(spec);

System.out.println(item.toJSONPretty());
```

 Per stampare un `Item` in un formato leggibile, utilizza il metodo `toJSONPretty`. L'aspetto dell'output dall'esempio precedente è simile al seguente.

```
{
  "RelatedItems" : [ 341 ],
  "Reviews" : {
    "FiveStar" : [ "Excellent! Can't recommend it highly enough! Buy it!", "Do yourself a favor and buy this" ]
  },
  "Id" : 123,
  "Title" : "20-Bicycle 123"
}
```

### GetItem e documenti JSON
<a name="GetItemJavaDocumentAPI.JSON"></a>

Nella sezione [PutItem e documenti JSON](#PutItemJavaDocumentAPI.JSON), viene archiviato un documento JSON in un attributo `Map` denominato `VendorInfo`. Puoi utilizzare il metodo `getItem` per recuperare l'intero documento nel formato JSON. Oppure puoi utilizzare la notazione del percorso del documento per recuperare solo gli stessi elementi nel documento. Il seguente esempio di codice Java mostra queste tecniche.

```
GetItemSpec spec = new GetItemSpec()
    .withPrimaryKey("Id", 210);

System.out.println("All vendor info:");
spec.withProjectionExpression("VendorInfo");
System.out.println(table.getItem(spec).toJSON());

System.out.println("A single vendor:");
spec.withProjectionExpression("VendorInfo.V03");
System.out.println(table.getItem(spec).toJSON());

System.out.println("First office location for this vendor:");
spec.withProjectionExpression("VendorInfo.V03.Offices[0]");
System.out.println(table.getItem(spec).toJSON());
```

L'aspetto dell'output dall'esempio precedente è simile al seguente.

```
All vendor info:
{"VendorInfo":{"V03":{"Name":"Better Buy Books","Offices":["Tokyo","Los Angeles","Sydney"]},"V02":{"Name":"New Publishers, Inc.","Offices":["London","New York"]},"V01":{"Name":"Acme Books","Offices":["Seattle"]}}}
A single vendor:
{"VendorInfo":{"V03":{"Name":"Better Buy Books","Offices":["Tokyo","Los Angeles","Sydney"]}}}
First office location for a single vendor:
{"VendorInfo":{"V03":{"Offices":["Tokyo"]}}}
```

**Nota**  
Puoi usare il metodo `toJSON` per convertire qualsiasi item (o gli attributi) in una stringa in formato JSON. Il seguente codice recupera diversi attributi di primo livello e nidificati e stampa i risultati come JSON.  

```
GetItemSpec spec = new GetItemSpec()
    .withPrimaryKey("Id", 210)
    .withProjectionExpression("VendorInfo.V01, Title, Price");

Item item = table.getItem(spec);
System.out.println(item.toJSON());
```
L'output sarà simile al seguente.  

```
{"VendorInfo":{"V01":{"Name":"Acme Books","Offices":["Seattle"]}},"Price":30,"Title":"Book 210 Title"}
```

## Scrittura in batch: collocazione ed eliminazione di più elementi
<a name="BatchWriteDocumentAPIJava"></a>

La *scrittura in batch* fa riferimento alla collocazione e all'eliminazione di più item in un batch. Il metodo `batchWriteItem` ti consente di inserire ed eliminare più item da una o più tabelle con un'unica chiamata. Di seguito sono riportati i passaggi per inserire o eliminare più elementi utilizzando l'API AWS SDK per Java Document.

1. Creare un'istanza della classe `DynamoDB`.

1. Crea un'istanza della classe `TableWriteItems` che descrive tutte le operazioni di inserimento ed eliminazione per una tabella. Se vuoi scrivere su più tabelle in una sola operazione di scrittura in batch, devi creare un'istanza di `TableWriteItems` per tabella.

1. Chiama il metodo `batchWriteItem` fornendo gli oggetti `TableWriteItems` creati nella fase precedente. 

1. Elabora la risposta. Dovresti controllare se erano presenti item di richiesta non elaborati restituiti nella risposta. Questo potrebbe accadere se raggiungi la quota di throughput assegnata o si verifica un altro errore transitorio. Inoltre, DynamoDB limita la dimensione della richiesta e il numero di operazioni che possono essere specificate in una richiesta. Se si superano questi limiti, DynamoDB rifiuta la richiesta. Per ulteriori informazioni, consulta [Quote in Amazon DynamoDB](ServiceQuotas.md). 

Il seguente esempio di codice Java mostra le fasi precedenti. L'esempio esegue un'operazione `batchWriteItem` su due tabelle: `Forum` e `Thread`. Gli oggetti `TableWriteItems` corrispondenti definiscono le operazioni seguenti:
+ inserimento di un item nella tabella `Forum`.
+ Inserimento ed eliminazione di un item nella tabella `Thread`.

Il codice quindi chiama `batchWriteItem` per eseguire l'operazione.

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

TableWriteItems forumTableWriteItems = new TableWriteItems("Forum")
    .withItemsToPut(
        new Item()
            .withPrimaryKey("Name", "Amazon RDS")
            .withNumber("Threads", 0));

TableWriteItems threadTableWriteItems = new TableWriteItems("Thread")
    .withItemsToPut(
        new Item()
            .withPrimaryKey("ForumName","Amazon RDS","Subject","Amazon RDS Thread 1")
    .withHashAndRangeKeysToDelete("ForumName","Some partition key value", "Amazon S3", "Some sort key value");

BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(forumTableWriteItems, threadTableWriteItems);

// Code for checking unprocessed items is omitted in this example
```

Per un esempio di utilizzo, consulta [Esempio: operazione di scrittura in batch utilizzando l'API del AWS SDK per Java documento](batch-operation-document-api-java.md#JavaDocumentAPIBatchWrite). 

## Ricezione in batch: ricezione di più elementi
<a name="JavaDocumentAPIBatchGetItem"></a>

Il metodo `batchGetItem` ti consente di recuperare più item da una o più tabelle. Per recuperare un singolo item puoi usare il metodo `getItem`. 

Completare la procedura riportata di seguito. 

1. Creare un'istanza della classe `DynamoDB`.

1. Crea un'istanza della classe `TableKeysAndAttributes` e descrivi un elenco di valori delle chiavi primarie da recuperare da una tabella. Se vuoi leggere da più tabelle in una sola operazione Get in batch, devi creare un'istanza di `TableKeysAndAttributes` per tabella.

1. Chiama il metodo `batchGetItem` fornendo gli oggetti `TableKeysAndAttributes` creati nella fase precedente.

Il seguente esempio di codice Java mostra le fasi precedenti. L'esempio consente di recuperare due item dalla tabella `Forum` e tre item dalla tabella `Thread`.

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

    TableKeysAndAttributes forumTableKeysAndAttributes = new TableKeysAndAttributes(forumTableName);
    forumTableKeysAndAttributes.addHashOnlyPrimaryKeys("Name",
    "Amazon S3",
    "Amazon DynamoDB");

TableKeysAndAttributes threadTableKeysAndAttributes = new TableKeysAndAttributes(threadTableName);
threadTableKeysAndAttributes.addHashAndRangePrimaryKeys("ForumName", "Subject",
    "Amazon DynamoDB","DynamoDB Thread 1",
    "Amazon DynamoDB","DynamoDB Thread 2",
    "Amazon S3","S3 Thread 1");

BatchGetItemOutcome outcome = dynamoDB.batchGetItem(
    forumTableKeysAndAttributes, threadTableKeysAndAttributes);

for (String tableName : outcome.getTableItems().keySet()) {
    System.out.println("Items in table " + tableName);
    List<Item> items = outcome.getTableItems().get(tableName);
    for (Item item : items) {
        System.out.println(item);
    }
}
```

### Specifica dei parametri facoltativi
<a name="BatchGetItemJavaDocumentAPIOptions"></a>

Insieme ai parametri richiesti, puoi anche specificare parametri opzionali usando `batchGetItem`. Puoi ad esempio fornire un `ProjectionExpression` con ogni `TableKeysAndAttributes` che definisci. Ciò ti consente di specificare gli attributi che vuoi recuperare dalla tabella.

L'esempio di codice seguente recupera due item dalla tabella `Forum`. Il parametro `withProjectionExpression` specifica che deve essere recuperato solo l'attributo `Threads`.

**Example**  

```
TableKeysAndAttributes forumTableKeysAndAttributes = new TableKeysAndAttributes("Forum")
    .withProjectionExpression("Threads");

forumTableKeysAndAttributes.addHashOnlyPrimaryKeys("Name",
    "Amazon S3",
    "Amazon DynamoDB");

BatchGetItemOutcome outcome = dynamoDB.batchGetItem(forumTableKeysAndAttributes);
```

## Aggiornamento di un elemento
<a name="JavaDocumentAPIItemUpdate"></a>

Il metodo `updateItem` di un oggetto `Table` può aggiornare i valori degli attributi esistenti, aggiungere nuovi attributi o eliminare attributi da un item esistente. 

Il metodo `updateItem` si comporta nel modo seguente:
+ Se un item non esiste (nessun item nella tabella con la chiave primaria specificata), `updateItem` aggiunge un nuovo item alla tabella.
+ Se un item esiste, `updateItem` esegue l'aggiornamento come specificato dal parametro `UpdateExpression`.

**Nota**  
È anche possibile "aggiornare" un item usando `putItem`. Ad esempio, se chiami `putItem` per aggiungere un item alla tabella ma esiste già un item con la chiave primaria specificata, `putItem` sostituisce l'intero item. Se nell'item esistente sono presenti attributi che non sono specificati nell'input, `putItem` rimuove quegli attributi dall'item.  
Come regola generale, ti consigliamo di usare `updateItem` ogni volta che desideri modificare qualsiasi attributo dell'item. Il metodo `updateItem` modifica solo gli attributi specificati nell'input e gli altri attributi dell'item rimangono invariati.

Completare la procedura riportata di seguito. 

1. Crea un'istanza della classe `Table` per rappresentare la tabella da utilizzare.

1. Chiama il metodo `updateTable` dell'istanza di `Table`. Dovrai specificare la chiave primaria dell'item che vuoi recuperare, insieme a una `UpdateExpression` che descrive gli attributi da modificare e come modificarli.

Il seguente esempio di codice Java mostra le attività precedenti. Il codice aggiorna un item libro nella tabella `ProductCatalog`. Aggiunge un nuovo autore al set di `Authors` ed elimina l'attributo `ISBN` esistente. Inoltre, riduce il prezzo di una unità.

Una mappa `ExpressionAttributeValues` viene usata in `UpdateExpression`. I segnaposto `:val1` e `:val2` vengono sostituiti al runtime con i valori effettivi per `Authors` e `Price`.

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

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

Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#A", "Authors");
expressionAttributeNames.put("#P", "Price");
expressionAttributeNames.put("#I", "ISBN");

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1",
    new HashSet<String>(Arrays.asList("Author YY","Author ZZ")));
expressionAttributeValues.put(":val2", 1);   //Price

UpdateItemOutcome outcome =  table.updateItem(
    "Id",          // key attribute name
    101,           // key attribute value
    "add #A :val1 set #P = #P - :val2 remove #I", // UpdateExpression
    expressionAttributeNames,
    expressionAttributeValues);
```

### Specifica dei parametri facoltativi
<a name="UpdateItemJavaDocumentAPIOptions"></a>

Insieme ai parametri obbligatori puoi specificare anche dei parametri facoltativi per il metodo `updateItem`, inclusa una condizione che deve essere soddisfatta affinché l'aggiornamento possa avere luogo. Se la condizione specificata non è soddisfatta, AWS SDK per Java genera un`ConditionalCheckFailedException`. Ad esempio, il seguente esempio di codice Java aggiorna in base a condizioni il prezzo di un libro a 25. Specifica una `ConditionExpression` che afferma che il prezzo deve essere aggiornato solo se il prezzo esistente è 20.

**Example**  

```
Table table = dynamoDB.getTable("ProductCatalog");

Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#P", "Price");

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1", 25);  // update Price to 25...
expressionAttributeValues.put(":val2", 20);  //...but only if existing Price is 20

UpdateItemOutcome outcome = table.updateItem(
    new PrimaryKey("Id",101),
    "set #P = :val1", // UpdateExpression
    "#P = :val2",     // ConditionExpression
    expressionAttributeNames,
    expressionAttributeValues);
```

### Contatore atomico
<a name="AtomicCounterJavaDocumentAPI"></a>

Puoi usare il metodo `updateItem` per implementare un contatore atomico e incrementare o decrementare il valore di un attributo esistente senza interferire con altre richieste di scrittura. Per incrementare un contatore atomico, usa un `UpdateExpression` con un'operazione `set` per aggiungere un valore numerico a un attributo esistente di tipo `Number`.

Il seguente esempio ne dimostra l'uso, incrementando l'attributo `Quantity` di uno. Dimostra anche l'uso del parametro `ExpressionAttributeNames` in una `UpdateExpression`.

```
Table table = dynamoDB.getTable("ProductCatalog");

Map<String,String> expressionAttributeNames = new HashMap<String,String>();
expressionAttributeNames.put("#p", "PageCount");

Map<String,Object> expressionAttributeValues = new HashMap<String,Object>();
expressionAttributeValues.put(":val", 1);

UpdateItemOutcome outcome = table.updateItem(
    "Id", 121,
    "set #p = #p + :val",
    expressionAttributeNames,
    expressionAttributeValues);
```

## Eliminazione di un elemento
<a name="DeleteMidLevelJava"></a>

Il metodo `deleteItem` elimina un item da una tabella. È necessario fornire la chiave primaria dell'item che intendi eliminare.

Completare la procedura riportata di seguito. 

1. Crea un'istanza del client `DynamoDB`.

1. Chiama il metodo `deleteItem` fornendo la chiave dell'item che desideri eliminare. 

Il seguente esempio Java mostra queste attività.

**Example**  

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

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

DeleteItemOutcome outcome = table.deleteItem("Id", 101);
```

### Specifica dei parametri facoltativi
<a name="DeleteItemJavaDocumentAPIOptions"></a>

Puoi specificare i parametri facoltativi per `deleteItem`. Ad esempio, il seguente esempio di codice Java specifica una `ConditionExpression`, in cui si afferma che un item libro in `InPublication` può essere eliminato solo se il libro non è più in pubblicazione (l'attributo `ProductCatalog` è false).

**Example**  

```
Map<String,Object> expressionAttributeValues = new HashMap<String,Object>();
expressionAttributeValues.put(":val", false);

DeleteItemOutcome outcome = table.deleteItem("Id",103,
    "InPublication = :val",
    null, // ExpressionAttributeNames - not used in this example
    expressionAttributeValues);
```

# Esempio: operazioni CRUD che utilizzano l'API del documento AWS SDK per Java
<a name="JavaDocumentAPICRUDExample"></a>

Il seguente esempio di codice illustra le operazioni CRUD su un elemento di Amazon DynamoDB. L'esempio consente di creare un item, recuperarlo, eseguire vari aggiornamenti e infine eliminare l'item.

**Nota**  
L'SDK per Java offre inoltre un modello di persistenza degli oggetti che permette di mappare le classi lato client alle tabelle DynamoDB. Questo approccio può ridurre la quantità di codice da scrivere. Per ulteriori informazioni, consulta [Java 1.x: Dinamo DBMapper](DynamoDBMapper.md).

**Nota**  
In questo esempio di codice si presuppone che i dati siano già stati caricati in DynamoDB per l'account seguendo le istruzioni riportate nella sezione [Creazione di tabelle e caricamento di dati per esempi di codice in DynamoDB](SampleData.md).  
Per step-by-step istruzioni su come eseguire l'esempio seguente, vedere[Esempi di codice Java](CodeSamples.Java.md).

```
package com.amazonaws.codesamples.document;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;

public class DocumentAPIItemCRUDExample {

    static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
    static DynamoDB dynamoDB = new DynamoDB(client);

    static String tableName = "ProductCatalog";

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

        createItems();

        retrieveItem();

        // Perform various updates.
        updateMultipleAttributes();
        updateAddNewAttribute();
        updateExistingAttributeConditionally();

        // Delete the item.
        deleteItem();

    }

    private static void createItems() {

        Table table = dynamoDB.getTable(tableName);
        try {

            Item item = new Item().withPrimaryKey("Id", 120).withString("Title", "Book 120 Title")
                    .withString("ISBN", "120-1111111111")
                    .withStringSet("Authors", new HashSet<String>(Arrays.asList("Author12", "Author22")))
                    .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500)
                    .withBoolean("InPublication", false).withString("ProductCategory", "Book");
            table.putItem(item);

            item = new Item().withPrimaryKey("Id", 121).withString("Title", "Book 121 Title")
                    .withString("ISBN", "121-1111111111")
                    .withStringSet("Authors", new HashSet<String>(Arrays.asList("Author21", "Author 22")))
                    .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500)
                    .withBoolean("InPublication", true).withString("ProductCategory", "Book");
            table.putItem(item);

        } catch (Exception e) {
            System.err.println("Create items failed.");
            System.err.println(e.getMessage());

        }
    }

    private static void retrieveItem() {
        Table table = dynamoDB.getTable(tableName);

        try {

            Item item = table.getItem("Id", 120, "Id, ISBN, Title, Authors", null);

            System.out.println("Printing item after retrieving it....");
            System.out.println(item.toJSONPretty());

        } catch (Exception e) {
            System.err.println("GetItem failed.");
            System.err.println(e.getMessage());
        }

    }

    private static void updateAddNewAttribute() {
        Table table = dynamoDB.getTable(tableName);

        try {

            UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 121)
                    .withUpdateExpression("set #na = :val1").withNameMap(new NameMap().with("#na", "NewAttribute"))
                    .withValueMap(new ValueMap().withString(":val1", "Some value"))
                    .withReturnValues(ReturnValue.ALL_NEW);

            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

            // Check the response.
            System.out.println("Printing item after adding new attribute...");
            System.out.println(outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Failed to add new attribute in " + tableName);
            System.err.println(e.getMessage());
        }
    }

    private static void updateMultipleAttributes() {

        Table table = dynamoDB.getTable(tableName);

        try {

            UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 120)
                    .withUpdateExpression("add #a :val1 set #na=:val2")
                    .withNameMap(new NameMap().with("#a", "Authors").with("#na", "NewAttribute"))
                    .withValueMap(
                            new ValueMap().withStringSet(":val1", "Author YY", "Author ZZ").withString(":val2",
                                    "someValue"))
                    .withReturnValues(ReturnValue.ALL_NEW);

            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

            // Check the response.
            System.out.println("Printing item after multiple attribute update...");
            System.out.println(outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Failed to update multiple attributes in " + tableName);
            System.err.println(e.getMessage());

        }
    }

    private static void updateExistingAttributeConditionally() {

        Table table = dynamoDB.getTable(tableName);

        try {

            // Specify the desired price (25.00) and also the condition (price =
            // 20.00)

            UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 120)
                    .withReturnValues(ReturnValue.ALL_NEW).withUpdateExpression("set #p = :val1")
                    .withConditionExpression("#p = :val2").withNameMap(new NameMap().with("#p", "Price"))
                    .withValueMap(new ValueMap().withNumber(":val1", 25).withNumber(":val2", 20));

            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

            // Check the response.
            System.out.println("Printing item after conditional update to new attribute...");
            System.out.println(outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Error updating item in " + tableName);
            System.err.println(e.getMessage());
        }
    }

    private static void deleteItem() {

        Table table = dynamoDB.getTable(tableName);

        try {

            DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey("Id", 120)
                    .withConditionExpression("#ip = :val").withNameMap(new NameMap().with("#ip", "InPublication"))
                    .withValueMap(new ValueMap().withBoolean(":val", false)).withReturnValues(ReturnValue.ALL_OLD);

            DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec);

            // Check the response.
            System.out.println("Printing item that was deleted...");
            System.out.println(outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Error deleting item in " + tableName);
            System.err.println(e.getMessage());
        }
    }
}
```

# Esempio: operazioni Batch utilizzando l'API AWS SDK per Java dei documenti
<a name="batch-operation-document-api-java"></a>

Questa sezione fornisce esempi di operazioni di scrittura e acquisizione in batch in Amazon DynamoDB utilizzando AWS SDK per Java l'API Document.

**Nota**  
L'SDK per Java offre inoltre un modello di persistenza degli oggetti che permette di mappare le classi lato client alle tabelle DynamoDB. Questo approccio può ridurre la quantità di codice da scrivere. Per ulteriori informazioni, consulta [Java 1.x: Dinamo DBMapper](DynamoDBMapper.md).

**Topics**
+ [Esempio: operazione di scrittura in batch utilizzando l'API del AWS SDK per Java documento](#JavaDocumentAPIBatchWrite)
+ [Esempio: operazione Batch get utilizzando l'API del AWS SDK per Java documento](#JavaDocumentAPIBatchGet)

## Esempio: operazione di scrittura in batch utilizzando l'API del AWS SDK per Java documento
<a name="JavaDocumentAPIBatchWrite"></a>

Nel seguente esempio di codice Java viene utilizzato il metodo `batchWriteItem` per eseguire le seguenti operazioni di eliminazione e inserimento:
+ inserimento di un item nella tabella `Forum`;
+ Inserimento di un item ed eliminazione di un item dalla tabella `Thread`. 

Quando crei la tua risposta di scrittura in batch, puoi specificare qualsiasi quantità di richieste di inserimento ed eliminazione in una o più tabelle. Tuttavia, `batchWriteItem` limita la dimensione di una richiesta di scrittura in batch e il numero di operazioni di inserimento ed eliminazione in una singola operazione di scrittura in batch. Se la tua richiesta eccede questi limiti, essa verrà rigettata. Se la tua tabella non dispone di sufficiente throughput assegnato per soddisfare questa richiesta, gli elementi di richiesta non eseguiti vengono restituiti nella risposta. 

Il seguente esempio controlla la risposta nel caso in cui vi siano degli elementi di richiesta non eseguiti. Se sono presenti, esegue il loopback e invia nuovamente la richiesta `batchWriteItem` con gli elementi non elaborati della richiesta. Seguendo gli esempi presenti in questa guida dovrebbe essere già avvenuta la creazione delle tabelle `Forum` e `Thread`. Puoi anche creare queste tabelle e caricare i dati di esempio a livello di programmazione. Per ulteriori informazioni, consulta [Creazione di tabelle di esempio e caricamento di dati utilizzando AWS SDK per Java](AppendixSampleDataCodeJava.md).

Per step-by-step istruzioni su come testare il seguente esempio, vedere[Esempi di codice Java](CodeSamples.Java.md). 

**Example**  

```
package com.amazonaws.codesamples.document;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
import com.amazonaws.services.dynamodbv2.model.WriteRequest;

public class DocumentAPIBatchWrite {

    static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
    static DynamoDB dynamoDB = new DynamoDB(client);

    static String forumTableName = "Forum";
    static String threadTableName = "Thread";

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

        writeMultipleItemsBatchWrite();

    }

    private static void writeMultipleItemsBatchWrite() {
        try {

            // Add a new item to Forum
            TableWriteItems forumTableWriteItems = new TableWriteItems(forumTableName) // Forum
                    .withItemsToPut(new Item().withPrimaryKey("Name", "Amazon RDS").withNumber("Threads", 0));

            // Add a new item, and delete an existing item, from Thread
            // This table has a partition key and range key, so need to specify
            // both of them
            TableWriteItems threadTableWriteItems = new TableWriteItems(threadTableName)
                    .withItemsToPut(
                            new Item().withPrimaryKey("ForumName", "Amazon RDS", "Subject", "Amazon RDS Thread 1")
                                    .withString("Message", "ElastiCache Thread 1 message")
                                    .withStringSet("Tags", new HashSet<String>(Arrays.asList("cache", "in-memory"))))
                    .withHashAndRangeKeysToDelete("ForumName", "Subject", "Amazon S3", "S3 Thread 100");

            System.out.println("Making the request.");
            BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(forumTableWriteItems, threadTableWriteItems);

            do {

                // Check for unprocessed keys which could happen if you exceed
                // provisioned throughput

                Map<String, List<WriteRequest>> unprocessedItems = outcome.getUnprocessedItems();

                if (outcome.getUnprocessedItems().size() == 0) {
                    System.out.println("No unprocessed items found");
                } else {
                    System.out.println("Retrieving the unprocessed items");
                    outcome = dynamoDB.batchWriteItemUnprocessed(unprocessedItems);
                }

            } while (outcome.getUnprocessedItems().size() > 0);

        } catch (Exception e) {
            System.err.println("Failed to retrieve items: ");
            e.printStackTrace(System.err);
        }

    }

}
```

## Esempio: operazione Batch get utilizzando l'API del AWS SDK per Java documento
<a name="JavaDocumentAPIBatchGet"></a>

Nel seguente esempio di codice Java si utilizza il metodo `batchGetItem` per recuperare più item dalle tabelle `Forum` e `Thread`. L'item `BatchGetItemRequest` specifica i nomi delle tabelle e un elenco di chiavi per ogni item da ottenere. Nell'esempio si esegue la risposta stampando gli elementi recuperati.

**Nota**  
In questo esempio di codice si presuppone che i dati siano già stati caricati in DynamoDB per l'account seguendo le istruzioni riportate nella sezione [Creazione di tabelle e caricamento di dati per esempi di codice in DynamoDB](SampleData.md).  
Per step-by-step istruzioni su come eseguire l'esempio seguente, consulta[Esempi di codice Java](CodeSamples.Java.md).

**Example**  

```
package com.amazonaws.codesamples.document;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.BatchGetItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.TableKeysAndAttributes;
import com.amazonaws.services.dynamodbv2.model.KeysAndAttributes;

public class DocumentAPIBatchGet {
    static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
    static DynamoDB dynamoDB = new DynamoDB(client);

    static String forumTableName = "Forum";
    static String threadTableName = "Thread";

    public static void main(String[] args) throws IOException {
        retrieveMultipleItemsBatchGet();
    }

    private static void retrieveMultipleItemsBatchGet() {

        try {

            TableKeysAndAttributes forumTableKeysAndAttributes = new TableKeysAndAttributes(forumTableName);
            // Add a partition key
            forumTableKeysAndAttributes.addHashOnlyPrimaryKeys("Name", "Amazon S3", "Amazon DynamoDB");

            TableKeysAndAttributes threadTableKeysAndAttributes = new TableKeysAndAttributes(threadTableName);
            // Add a partition key and a sort key
            threadTableKeysAndAttributes.addHashAndRangePrimaryKeys("ForumName", "Subject", "Amazon DynamoDB",
                    "DynamoDB Thread 1", "Amazon DynamoDB", "DynamoDB Thread 2", "Amazon S3", "S3 Thread 1");

            System.out.println("Making the request.");

            BatchGetItemOutcome outcome = dynamoDB.batchGetItem(forumTableKeysAndAttributes,
                    threadTableKeysAndAttributes);

            Map<String, KeysAndAttributes> unprocessed = null;

            do {
                for (String tableName : outcome.getTableItems().keySet()) {
                    System.out.println("Items in table " + tableName);
                    List<Item> items = outcome.getTableItems().get(tableName);
                    for (Item item : items) {
                        System.out.println(item.toJSONPretty());
                    }
                }

                // Check for unprocessed keys which could happen if you exceed
                // provisioned
                // throughput or reach the limit on response size.
                unprocessed = outcome.getUnprocessedKeys();

                if (unprocessed.isEmpty()) {
                    System.out.println("No unprocessed keys found");
                } else {
                    System.out.println("Retrieving the unprocessed keys");
                    outcome = dynamoDB.batchGetItemUnprocessed(unprocessed);
                }

            } while (!unprocessed.isEmpty());

        } catch (Exception e) {
            System.err.println("Failed to retrieve items.");
            System.err.println(e.getMessage());
        }

    }

}
```

# Esempio: gestione degli attributi di tipo binario utilizzando l'API del AWS SDK per Java documento
<a name="JavaDocumentAPIBinaryTypeExample"></a>

Il seguente esempio di codice Java illustra come gestire gli attributi di tipo binario. L'esempio aggiunge un item alla tabella `Reply`. L'item include un attributo di tipo binario (`ExtendedMessage`) che memorizza i dati compressi. L'esempio recupera quindi l'item e stampa tutti valori degli attributi. Nell'esempio si utilizza la classe `GZIPOutputStream` per comprimere un flusso di esempio e assegnarlo all'attributo `ExtendedMessage`. Quando l'attributo binario viene recuperato, viene decompresso utilizzando la classe `GZIPInputStream`. 

**Nota**  
L'SDK per Java offre inoltre un modello di persistenza degli oggetti che permette di mappare le classi lato client alle tabelle DynamoDB. Questo approccio può ridurre la quantità di codice da scrivere. Per ulteriori informazioni, consulta [Java 1.x: Dinamo DBMapper](DynamoDBMapper.md).

Se hai seguito la sezione [Creazione di tabelle e caricamento di dati per esempi di codice in DynamoDB](SampleData.md) dovresti aver già creato la tabella `Reply`. Puoi anche creare questa tabella a livello di programmazione. Per ulteriori informazioni, consulta [Creazione di tabelle di esempio e caricamento di dati utilizzando AWS SDK per Java](AppendixSampleDataCodeJava.md).

Per step-by-step istruzioni su come testare il seguente esempio, vedere[Esempi di codice Java](CodeSamples.Java.md). 

**Example**  

```
package com.amazonaws.codesamples.document;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec;

public class DocumentAPIItemBinaryExample {

    static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
    static DynamoDB dynamoDB = new DynamoDB(client);

    static String tableName = "Reply";
    static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

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

            // Format the primary key values
            String threadId = "Amazon DynamoDB#DynamoDB Thread 2";

            dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
            String replyDateTime = dateFormatter.format(new Date());

            // Add a new reply with a binary attribute type
            createItem(threadId, replyDateTime);

            // Retrieve the reply with a binary attribute type
            retrieveItem(threadId, replyDateTime);

            // clean up by deleting the item
            deleteItem(threadId, replyDateTime);
        } catch (Exception e) {
            System.err.println("Error running the binary attribute type example: " + e);
            e.printStackTrace(System.err);
        }
    }

    public static void createItem(String threadId, String replyDateTime) throws IOException {

        Table table = dynamoDB.getTable(tableName);

        // Craft a long message
        String messageInput = "Long message to be compressed in a lengthy forum reply";

        // Compress the long message
        ByteBuffer compressedMessage = compressString(messageInput.toString());

        table.putItem(new Item().withPrimaryKey("Id", threadId).withString("ReplyDateTime", replyDateTime)
                .withString("Message", "Long message follows").withBinary("ExtendedMessage", compressedMessage)
                .withString("PostedBy", "User A"));
    }

    public static void retrieveItem(String threadId, String replyDateTime) throws IOException {

        Table table = dynamoDB.getTable(tableName);

        GetItemSpec spec = new GetItemSpec().withPrimaryKey("Id", threadId, "ReplyDateTime", replyDateTime)
                .withConsistentRead(true);

        Item item = table.getItem(spec);

        // Uncompress the reply message and print
        String uncompressed = uncompressString(ByteBuffer.wrap(item.getBinary("ExtendedMessage")));

        System.out.println("Reply message:\n" + " Id: " + item.getString("Id") + "\n" + " ReplyDateTime: "
                + item.getString("ReplyDateTime") + "\n" + " PostedBy: " + item.getString("PostedBy") + "\n"
                + " Message: "
                + item.getString("Message") + "\n" + " ExtendedMessage (uncompressed): " + uncompressed + "\n");
    }

    public static void deleteItem(String threadId, String replyDateTime) {

        Table table = dynamoDB.getTable(tableName);
        table.deleteItem("Id", threadId, "ReplyDateTime", replyDateTime);
    }

    private static ByteBuffer compressString(String input) throws IOException {
        // Compress the UTF-8 encoded String into a byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream os = new GZIPOutputStream(baos);
        os.write(input.getBytes("UTF-8"));
        os.close();
        baos.close();
        byte[] compressedBytes = baos.toByteArray();

        // The following code writes the compressed bytes to a ByteBuffer.
        // A simpler way to do this is by simply calling
        // ByteBuffer.wrap(compressedBytes);
        // However, the longer form below shows the importance of resetting the
        // position of the buffer
        // back to the beginning of the buffer if you are writing bytes directly
        // to it, since the SDK
        // will consider only the bytes after the current position when sending
        // data to DynamoDB.
        // Using the "wrap" method automatically resets the position to zero.
        ByteBuffer buffer = ByteBuffer.allocate(compressedBytes.length);
        buffer.put(compressedBytes, 0, compressedBytes.length);
        buffer.position(0); // Important: reset the position of the ByteBuffer
                            // to the beginning
        return buffer;
    }

    private static String uncompressString(ByteBuffer input) throws IOException {
        byte[] bytes = input.array();
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPInputStream is = new GZIPInputStream(bais);

        int chunkSize = 1024;
        byte[] buffer = new byte[chunkSize];
        int length = 0;
        while ((length = is.read(buffer, 0, chunkSize)) != -1) {
            baos.write(buffer, 0, length);
        }

        String result = new String(baos.toByteArray(), "UTF-8");

        is.close();
        baos.close();
        bais.close();

        return result;
    }
}
```