특정 버전의 리소스 가져오기

모든 리소스에는 리소스가 변경될 때마다 변경되는 버전 필드, 즉 etag 필드가 있습니다. Etag는 HTTP의 표준 부분이며 다음 두 가지 경우에 Calendar API에서 지원됩니다.

  • 그동안 이 리소스에 대한 다른 쓰기가 없도록 리소스 수정 (조건부 수정)
  • 리소스가 변경된 경우에만 리소스 데이터를 검색 (조건부 검색)할 때 리소스 가져오기

조건부 수정

리소스를 마지막으로 검색한 후 변경되지 않은 리소스만 업데이트하거나 삭제하려는 경우 이전 검색의 etag 값이 포함된 If-Match 헤더를 지정하면 됩니다. 이는 리소스 수정 사항이 손실되는 것을 방지하는 데 매우 유용합니다. 클라이언트는 리소스를 다시 검색하고 변경사항을 다시 적용할 수 있습니다.

마지막 검색 이후 항목 (및 태그의 etag)이 변경되지 않은 경우 수정이 성공하고 새 etag가 있는 리소스의 새 버전이 반환됩니다. 그렇지 않으면 412 (전제 조건 실패) 응답 코드를 받게 됩니다.

아래 샘플 코드 스니펫은 자바 클라이언트 라이브러리를 사용하여 조건부 수정을 수행하는 방법을 보여줍니다.

  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));
    }
  }

조건부 검색

리소스를 마지막으로 검색한 이후 변경된 경우에만 리소스를 검색하려면 이전 검색의 etag 값이 포함된 If-None-Match 헤더를 지정하면 됩니다. 마지막 검색 이후 항목 (및 그에 따른 etag)이 변경된 경우 새 etag가 있는 리소스의 새 버전이 반환됩니다. 그렇지 않으면 304 (수정되지 않음) 응답 코드가 표시됩니다.

아래 샘플 코드 스니펫은 자바 클라이언트 라이브러리를 사용하여 조건부 검색을 수행하는 방법을 보여줍니다.

  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;
      }
    }
  }