Acessar versões específicas dos recursos

Todo recurso tem um campo de versão que muda sempre que o recurso é alterado: o campo etag. As Etags são uma parte padrão do HTTP e são compatíveis com a API Calendar em dois casos:

  • sobre modificações de recursos para garantir que não tenha ocorrido outra gravação nesse recurso enquanto isso (modificação condicional)
  • na recuperação de recursos para recuperar dados de recursos apenas se o recurso tiver sido alterado (recuperação condicional)

Modificação condicional

Se você quiser atualizar ou excluir um recurso somente se ele não tiver sido alterado desde a última vez que o recuperou, especifique um cabeçalho If-Match que contenha o valor da etag da recuperação anterior. Isso é muito útil para evitar modificações perdidas nos recursos. Os clientes têm a opção de recuperar o recurso e aplicar novamente as alterações.

Se a entrada (e a etag) não tiverem sido alteradas desde a última recuperação, a modificação será bem-sucedida, e a nova versão do recurso com a nova etag será retornada. Caso contrário, você vai receber o código de resposta 412 (Falha na pré-condição).

O snippet de exemplo de código abaixo demonstra como fazer modificações condicionais com a biblioteca de cliente 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));
    }
  }

Recuperação condicional

Se você quiser recuperar um recurso somente se ele tiver sido alterado desde a última recuperação, especifique um cabeçalho If-None-Match que contenha o valor da ETag da recuperação anterior. Se a entrada (e, portanto, sua etag) tiver sido alterada desde a última recuperação, a nova versão do recurso com a nova etag será retornada. Caso contrário, você receberá um código de resposta 304 (não modificado).

O snippet de exemplo de código abaixo demonstra como executar a recuperação condicional com a biblioteca de cliente 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;
      }
    }
  }