Ogni risorsa ha un campo versione che cambia ogni volta che la risorsa
viene modificata: il campo etag
. Gli ETag sono una parte standard di HTTP e sono
supportati nell'API Calendar in due casi:
- sulle modifiche alle risorse per assicurarsi che nel frattempo non siano state apportate altre scritture a questa risorsa (modifica condizionale)
- sul recupero delle risorse per recuperare i dati delle risorse solo se la risorsa è stata modificata (recupero condizionale)
Modifica condizionale
Se vuoi aggiornare o eliminare una risorsa solo se non è stata modificata dall'ultima volta che l'hai recuperata, puoi specificare un'intestazione If-Match
che contenga il valore dell'etag del recupero precedente. Questo è molto utile per evitare
la perdita di modifiche alle risorse. I client hanno la possibilità di recuperare nuovamente
la risorsa e riapplicare le modifiche.
Se la voce (e il relativo etag) non è cambiata dall'ultimo recupero, la modifica va a buon fine e viene restituita la nuova versione della risorsa con il nuovo etag. In caso contrario, riceverai un codice di risposta 412 (Precondizione non riuscita).
Lo snippet di codice di esempio riportato di seguito mostra come eseguire modifiche condizionali con la libreria client Java.
private static void run() throws IOException { // Create a test event. Event event = Utils.createTestEvent(client, "Test Event"); System.out.println(String.format("Event created: %s", event.getHtmlLink())); // Pause while the user modifies the event in the Calendar UI. System.out.println("Modify the event's description and hit enter to continue."); System.in.read(); // Modify the local copy of the event. event.setSummary("Updated Test Event"); // Update the event, making sure that we don't overwrite other changes. int numAttempts = 0; boolean isUpdated = false; do { Calendar.Events.Update request = client.events().update("primary", event.getId(), event); request.setRequestHeaders(new HttpHeaders().setIfMatch(event.getEtag())); try { event = request.execute(); isUpdated = true; } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 412) { // A 412 status code, "Precondition failed", indicates that the etag values didn't // match, and the event was updated on the server since we last retrieved it. Use // {@link Calendar.Events.Get} to retrieve the latest version. Event latestEvent = client.events().get("primary", event.getId()).execute(); // You may want to have more complex logic here to resolve conflicts. In this sample we're // simply overwriting the summary. latestEvent.setSummary(event.getSummary()); event = latestEvent; } else { throw e; } } numAttempts++; } while (!isUpdated && numAttempts <= MAX_UPDATE_ATTEMPTS); if (isUpdated) { System.out.println("Event updated."); } else { System.out.println(String.format("Failed to update event after %d attempts.", numAttempts)); } }
Recupero condizionale
Se vuoi recuperare una risorsa solo se è stata modificata dall'ultima volta che l'hai recuperata, puoi specificare un'intestazione If-None-Match
che contiene il valore dell'etag del recupero precedente. Se la voce (e quindi il relativo etag)
è cambiata dall'ultimo recupero, verrà restituita la nuova versione della risorsa con il
nuovo etag. In caso contrario, riceverai un codice di risposta 304 (Non modificato).
Lo snippet di codice di esempio riportato di seguito mostra come eseguire il recupero condizionale con la libreria client Java.
private static void run() throws IOException { // Create a test event. Event event = Utils.createTestEvent(client, "Test Event"); System.out.println(String.format("Event created: %s", event.getHtmlLink())); // Pause while the user modifies the event in the Calendar UI. System.out.println("Modify the event's description and hit enter to continue."); System.in.read(); // Fetch the event again if it's been modified. Calendar.Events.Get getRequest = client.events().get("primary", event.getId()); getRequest.setRequestHeaders(new HttpHeaders().setIfNoneMatch(event.getEtag())); try { event = getRequest.execute(); System.out.println("The event was modified, retrieved latest version."); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 304) { // A 304 status code, "Not modified", indicates that the etags match, and the event has // not been modified since we last retrieved it. System.out.println("The event was not modified, using local version."); } else { throw e; } } }