com.google.api.client.http.json.JsonHttpContent Java Examples

The following examples show how to use com.google.api.client.http.json.JsonHttpContent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResumableUpload.java    From jdrivesync with Apache License 2.0 7 votes vote down vote up
private String requestUploadLocation(java.io.File fileToUpload, String mimeType, HttpRequestFactory requestFactory, com.google.api.services.drive.model.File remoteFile) throws IOException {
    GenericUrl initializationUrl = new GenericUrl("https://www.googleapis.com/upload/drive/v2/files");
    initializationUrl.put("uploadType", "resumable");
    HttpRequest httpRequest = createHttpRequest(requestFactory, HttpMethods.POST, initializationUrl, new JsonHttpContent(DriveFactory.getJsonFactory(), remoteFile));
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.put("X-Upload-Content-Type", mimeType);
    httpHeaders.put("X-Upload-Content-Length", fileToUpload.length());
    httpRequest.getHeaders().putAll(httpHeaders);
    LOGGER.log(Level.FINE, "Executing initial upload location request.");
    HttpResponse httpResponse = executeHttpRequest(httpRequest);
    if(!httpResponse.isSuccessStatusCode()) {
        throw new IOException("Request for upload location was not successful. Status-Code: " + httpResponse.getStatusCode());
    }
    String location = httpResponse.getHeaders().getLocation();
    LOGGER.log(Level.FINE, "URL for resumable upload: " + location);
    return location;
}
 
Example #2
Source File: HttpHelper.java    From firebase-admin-java with Apache License 2.0 7 votes vote down vote up
<T> void makePatchRequest(
    String url,
    Object payload,
    T parsedResponseInstance,
    String requestIdentifier,
    String requestIdentifierDescription) throws FirebaseProjectManagementException {
  try {
    HttpRequest baseRequest = requestFactory.buildPostRequest(
        new GenericUrl(url), new JsonHttpContent(jsonFactory, payload));
    baseRequest.getHeaders().set(PATCH_OVERRIDE_KEY, PATCH_OVERRIDE_VALUE);
    makeRequest(
        baseRequest, parsedResponseInstance, requestIdentifier, requestIdentifierDescription);
  } catch (IOException e) {
    handleError(requestIdentifier, requestIdentifierDescription, e);
  }
}
 
Example #3
Source File: FirebaseAuthIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private String signInWithCustomToken(String customToken) throws IOException {
  GenericUrl url = new GenericUrl(VERIFY_CUSTOM_TOKEN_URL + "?key="
      + IntegrationTestUtils.getApiKey());
  Map<String, Object> content = ImmutableMap.<String, Object>of(
      "token", customToken, "returnSecureToken", true);
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
      new JsonHttpContent(jsonFactory, content));
  request.setParser(new JsonObjectParser(jsonFactory));
  HttpResponse response = request.execute();
  try {
    GenericJson json = response.parseAs(GenericJson.class);
    return json.get("idToken").toString();
  } finally {
    response.disconnect();
  }
}
 
Example #4
Source File: Policy.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public boolean create(String name, String rules) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("rules", rules);

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/policy/" + name),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example #5
Source File: ResumableUpload.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
private String requestUploadLocation(java.io.File fileToUpload, String mimeType, HttpRequestFactory requestFactory, com.google.api.services.drive.model.File remoteFile) throws IOException {
    GenericUrl initializationUrl = new GenericUrl("https://www.googleapis.com/upload/drive/v2/files");
    initializationUrl.put("uploadType", "resumable");
    HttpRequest httpRequest = createHttpRequest(requestFactory, HttpMethods.POST, initializationUrl, new JsonHttpContent(DriveFactory.getJsonFactory(), remoteFile));
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.put("X-Upload-Content-Type", mimeType);
    httpHeaders.put("X-Upload-Content-Length", fileToUpload.length());
    httpRequest.getHeaders().putAll(httpHeaders);
    LOGGER.log(Level.FINE, "Executing initial upload location request.");
    HttpResponse httpResponse = executeHttpRequest(httpRequest);
    if(!httpResponse.isSuccessStatusCode()) {
        throw new IOException("Request for upload location was not successful. Status-Code: " + httpResponse.getStatusCode());
    }
    String location = httpResponse.getHeaders().getLocation();
    LOGGER.log(Level.FINE, "URL for resumable upload: " + location);
    return location;
}
 
Example #6
Source File: FirebaseAuthIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private String signInWithEmailLink(
    String email, String oobCode) throws IOException {
  GenericUrl url = new GenericUrl(EMAIL_LINK_SIGN_IN_URL + "?key="
      + IntegrationTestUtils.getApiKey());
  Map<String, Object> content = ImmutableMap.<String, Object>of(
      "email", email, "oobCode", oobCode);
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
      new JsonHttpContent(jsonFactory, content));
  request.setParser(new JsonObjectParser(jsonFactory));
  HttpResponse response = request.execute();
  try {
    GenericJson json = response.parseAs(GenericJson.class);
    return json.get("idToken").toString();
  } finally {
    response.disconnect();
  }
}
 
Example #7
Source File: FirebaseAuthIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private String resetPassword(
    String email, String oldPassword, String newPassword, String oobCode) throws IOException {
  GenericUrl url = new GenericUrl(RESET_PASSWORD_URL + "?key="
      + IntegrationTestUtils.getApiKey());
  Map<String, Object> content = ImmutableMap.<String, Object>of(
      "email", email, "oldPassword", oldPassword, "newPassword", newPassword, "oobCode", oobCode);
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
      new JsonHttpContent(jsonFactory, content));
  request.setParser(new JsonObjectParser(jsonFactory));
  HttpResponse response = request.execute();
  try {
    GenericJson json = response.parseAs(GenericJson.class);
    return json.get("email").toString();
  } finally {
    response.disconnect();
  }
}
 
Example #8
Source File: FirebaseAuthIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private String signInWithPassword(String email, String password) throws IOException {
  GenericUrl url = new GenericUrl(VERIFY_PASSWORD_URL + "?key="
      + IntegrationTestUtils.getApiKey());
  Map<String, Object> content = ImmutableMap.<String, Object>of(
      "email", email, "password", password, "returnSecureToken", true);
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
      new JsonHttpContent(jsonFactory, content));
  request.setParser(new JsonObjectParser(jsonFactory));
  HttpResponse response = request.execute();
  try {
    GenericJson json = response.parseAs(GenericJson.class);
    return json.get("idToken").toString();
  } finally {
    response.disconnect();
  }
}
 
Example #9
Source File: InstanceIdClientImpl.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private TopicManagementResponse sendInstanceIdRequest(
    String topic, List<String> registrationTokens, String path) throws IOException {
  String url = String.format("%s/%s", IID_HOST, path);
  Map<String, Object> payload = ImmutableMap.of(
      "to", getPrefixedTopic(topic),
      "registration_tokens", registrationTokens
  );
  HttpResponse response = null;
  try {
    HttpRequest request = requestFactory.buildPostRequest(
        new GenericUrl(url), new JsonHttpContent(jsonFactory, payload));
    request.getHeaders().set("access_token_auth", "true");
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setResponseInterceptor(responseInterceptor);
    response = request.execute();

    JsonParser parser = jsonFactory.createJsonParser(response.getContent());
    InstanceIdServiceResponse parsedResponse = new InstanceIdServiceResponse();
    parser.parse(parsedResponse);
    return new TopicManagementResponse(parsedResponse.results);
  } finally {
    ApiClientUtils.disconnectQuietly(response);
  }
}
 
Example #10
Source File: FirebaseMessagingClientImpl.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private BatchRequest newBatchRequest(
    List<Message> messages, boolean dryRun, MessagingBatchCallback callback) throws IOException {

  BatchRequest batch = new BatchRequest(
      requestFactory.getTransport(), getBatchRequestInitializer());
  batch.setBatchUrl(new GenericUrl(FCM_BATCH_URL));

  final JsonObjectParser jsonParser = new JsonObjectParser(this.jsonFactory);
  final GenericUrl sendUrl = new GenericUrl(fcmSendUrl);
  for (Message message : messages) {
    // Using a separate request factory without authorization is faster for large batches.
    // A simple performance test showed a 400-500ms speed up for batches of 1000 messages.
    HttpRequest request = childRequestFactory.buildPostRequest(
        sendUrl,
        new JsonHttpContent(jsonFactory, message.wrapForTransport(dryRun)));
    request.setParser(jsonParser);
    setCommonFcmHeaders(request.getHeaders());
    batch.queue(
        request, MessagingServiceResponse.class, MessagingServiceErrorResponse.class, callback);
  }
  return batch;
}
 
Example #11
Source File: FirebaseMessagingClientImpl.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private String sendSingleRequest(Message message, boolean dryRun) throws IOException {
  HttpRequest request = requestFactory.buildPostRequest(
      new GenericUrl(fcmSendUrl),
      new JsonHttpContent(jsonFactory, message.wrapForTransport(dryRun)));
  setCommonFcmHeaders(request.getHeaders());
  request.setParser(new JsonObjectParser(jsonFactory));
  request.setResponseInterceptor(responseInterceptor);
  HttpResponse response = request.execute();
  try {
    MessagingServiceResponse parsed = new MessagingServiceResponse();
    jsonFactory.createJsonParser(response.getContent()).parseAndClose(parsed);
    return parsed.getMessageId();
  } finally {
    ApiClientUtils.disconnectQuietly(response);
  }
}
 
Example #12
Source File: CryptoSigners.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] payload) throws IOException {
  String encodedUrl = String.format(IAM_SIGN_BLOB_URL, serviceAccount);
  HttpResponse response = null;
  String encodedPayload = BaseEncoding.base64().encode(payload);
  Map<String, String> content = ImmutableMap.of("bytesToSign", encodedPayload);
  try {
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(encodedUrl),
        new JsonHttpContent(jsonFactory, content));
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setResponseInterceptor(interceptor);
    response = request.execute();
    SignBlobResponse parsed = response.parseAs(SignBlobResponse.class);
    return BaseEncoding.base64().decode(parsed.signature);
  } finally {
    if (response != null) {
      try {
        response.disconnect();
      } catch (IOException ignored) {
        // Ignored
      }
    }
  }
}
 
Example #13
Source File: HttpHelper.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
<T> void makePostRequest(
    String url,
    Object payload,
    T parsedResponseInstance,
    String requestIdentifier,
    String requestIdentifierDescription) throws FirebaseProjectManagementException {
  try {
    makeRequest(
        requestFactory.buildPostRequest(
            new GenericUrl(url), new JsonHttpContent(jsonFactory, payload)),
        parsedResponseInstance,
        requestIdentifier,
        requestIdentifierDescription);
  } catch (IOException e) {
    handleError(requestIdentifier, requestIdentifierDescription, e);
  }
}
 
Example #14
Source File: GoogleVideosInterface.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
MediaItemSearchResponse listVideoItems(Optional<String> pageToken) throws IOException {
  Map<String, Object> params = new LinkedHashMap<>();
  params.put(PAGE_SIZE_KEY, String.valueOf(MEDIA_PAGE_SIZE));

  params.put(
      FILTERS_KEY,
      ImmutableMap.of(
          MEDIA_FILTER_KEY, ImmutableMap.of("mediaTypes", ImmutableList.of("VIDEO"))));

  if (pageToken.isPresent()) {
    params.put(TOKEN_KEY, pageToken.get());
  }
  HttpContent content = new JsonHttpContent(this.jsonFactory, params);
  return makePostRequest(
      BASE_URL + "mediaItems:search", Optional.empty(), content, MediaItemSearchResponse.class);
}
 
Example #15
Source File: GooglePhotosInterface.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
MediaItemSearchResponse listMediaItems(Optional<String> albumId, Optional<String> pageToken)
    throws IOException, InvalidTokenException, PermissionDeniedException {
  Map<String, Object> params = new LinkedHashMap<>();
  params.put(PAGE_SIZE_KEY, String.valueOf(MEDIA_PAGE_SIZE));
  if (albumId.isPresent()) {
    params.put(ALBUM_ID_KEY, albumId.get());
  } else {
    params.put(FILTERS_KEY, ImmutableMap.of(INCLUDE_ARCHIVED_KEY, String.valueOf(true)));
  }
  if (pageToken.isPresent()) {
    params.put(TOKEN_KEY, pageToken.get());
  }
  HttpContent content = new JsonHttpContent(new JacksonFactory(), params);
  return makePostRequest(
      BASE_URL + "mediaItems:search", Optional.empty(), content, MediaItemSearchResponse.class);
}
 
Example #16
Source File: GooglePhotosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
GoogleAlbum createAlbum(GoogleAlbum googleAlbum)
        throws IOException, InvalidTokenException, PermissionDeniedException {
  Map<String, Object> albumMap = createJsonMap(googleAlbum);
  Map<String, Object> contentMap = ImmutableMap.of("album", albumMap);
  HttpContent content = new JsonHttpContent(jsonFactory, contentMap);

  return makePostRequest(BASE_URL + "albums", Optional.empty(), content, GoogleAlbum.class);
}
 
Example #17
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
private HttpResponse executeSessionInitiationRequest(Drive drive, File remoteFile) throws IOException {
	GenericUrl url = new GenericUrl("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
	JsonHttpContent metadataContent = new JsonHttpContent(drive.getJsonFactory(), remoteFile);
	HttpRequest httpRequest = drive.getRequestFactory().buildPostRequest(url, metadataContent);
	LOGGER.log(Level.FINE, "Executing session initiation request to URL " + url);
	return httpRequest.execute();
}
 
Example #18
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testJsonHttpContent_wrapped() throws Exception {
  JsonFactory factory = newFactory();
  Simple simple = new Simple();
  simple.a = "b";
  JsonHttpContent content = new JsonHttpContent(factory, simple).setWrapperKey("d");
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  content.writeTo(out);
  assertEquals(SIMPLE_WRAPPED, out.toString("UTF-8"));
}
 
Example #19
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testJsonHttpContent_simple() throws Exception {
  JsonFactory factory = newFactory();
  Simple simple = new Simple();
  simple.a = "b";
  JsonHttpContent content = new JsonHttpContent(factory, simple);
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  content.writeTo(out);
  assertEquals(SIMPLE, out.toString("UTF-8"));
}
 
Example #20
Source File: GoogleCloudStorageIntegrationHelper.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/** Convert request to string representation that could be used for assertions in tests */
public static String requestToString(HttpRequest request) {
  String method = request.getRequestMethod();
  String url = request.getUrl().toString();
  String requestString = method + ":" + url;
  if ("POST".equals(method) && url.contains("uploadType=multipart")) {
    MultipartContent content = (MultipartContent) request.getContent();
    JsonHttpContent jsonRequest =
        (JsonHttpContent) Iterables.get(content.getParts(), 0).getContent();
    String objectName = ((StorageObject) jsonRequest.getData()).getName();
    requestString += ":" + objectName;
  }
  return requestString;
}
 
Example #21
Source File: Authenticate.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public Secret appRole(String roleId, String secretId, String namespace) throws VaultException {
  HttpContent content = new JsonHttpContent(
      getJsonFactory(),
      ImmutableMap.of("role_id", roleId, "secret_id", secretId)
  );
  namespace = namespace.replaceAll("\\s+","");
  if (!namespace.endsWith("/")) {
    namespace = namespace.concat("/");
  }
  return getSecret("/v1/" + namespace + "auth/approle/login", "POST", content);
}
 
Example #22
Source File: Mounts.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public boolean mount(String path, String type, String description, Map<String, String> config) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("type", type);

  if (description != null) {
    data.put("description", description);
  }

  if (config != null) {
    data.put("config", config);
  }

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/mounts/" + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example #23
Source File: Auth.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public boolean enable(String path, String type, String description) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("type", type);

  if (description != null) {
    data.put("description", description);
  }

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/auth/" + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example #24
Source File: Logical.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public Secret write(String path, Map<String, Object> params) throws VaultException {
  HttpContent content = new JsonHttpContent(
      getJsonFactory(),
      params
  );
  return getSecret("/v1/" + path, "POST", content);
}
 
Example #25
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
private HttpResponse executeSessionInitiationRequest(Drive drive, File remoteFile) throws IOException {
	GenericUrl url = new GenericUrl("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
	JsonHttpContent metadataContent = new JsonHttpContent(drive.getJsonFactory(), remoteFile);
	HttpRequest httpRequest = drive.getRequestFactory().buildPostRequest(url, metadataContent);
	LOGGER.log(Level.FINE, "Executing session initiation request to URL " + url);
	return httpRequest.execute();
}
 
Example #26
Source File: GerritApiTransportImpl.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T put(String path, Object request, Type responseType)
    throws RepoException, ValidationException {
  HttpRequestFactory requestFactory = getHttpRequestFactory(getCredentials(uri.toString()));
  GenericUrl url = getUrl(path);
  try {
    return execute(responseType, requestFactory.buildPutRequest(
        url, new JsonHttpContent(JSON_FACTORY, request)));
  } catch (IOException e) {
    throw new RepoException("Error running Gerrit API operation " + url, e);
  }
}
 
Example #27
Source File: GerritApiTransportImpl.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T post(String path, Object request, Type responseType)
    throws RepoException, ValidationException {
  HttpRequestFactory requestFactory = getHttpRequestFactory(getCredentials(uri.toString()));
  GenericUrl url = getUrl(path);
  try {
    return execute(responseType, requestFactory.buildPostRequest(
        url, new JsonHttpContent(JSON_FACTORY, request)));
  } catch (IOException e) {
    throw new RepoException("Error running Gerrit API operation " + url, e);
  }
}
 
Example #28
Source File: GoogleVideosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
BatchMediaItemResponse createVideo(NewMediaItemUpload newMediaItemUpload) throws IOException {
  HashMap<String, Object> map = createJsonMap(newMediaItemUpload);
  HttpContent httpContent = new JsonHttpContent(this.jsonFactory, map);

  return makePostRequest(
      BASE_URL + "mediaItems:batchCreate",
      Optional.empty(),
      httpContent,
      BatchMediaItemResponse.class);
}
 
Example #29
Source File: GooglePhotosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
BatchMediaItemResponse createPhoto(NewMediaItemUpload newMediaItemUpload)
    throws IOException, InvalidTokenException, PermissionDeniedException {
  HashMap<String, Object> map = createJsonMap(newMediaItemUpload);
  HttpContent httpContent = new JsonHttpContent(new JacksonFactory(), map);

  return makePostRequest(
      BASE_URL + "mediaItems:batchCreate",
      Optional.empty(),
      httpContent,
      BatchMediaItemResponse.class);
}
 
Example #30
Source File: LabelsSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Add or modify a label on a table.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelTable(
    String projectId, String datasetId, String tableId, String labelKey, String labelValue)
    throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  AccessToken accessToken = credential.refreshAccessToken();

  // Set the content of the request.
  Table table = new Table();
  table.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, table);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(
          String.format(urlFormat, projectId, datasetId, tableId, accessToken.getTokenValue()));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Table responseTable = response.parseAs(Table.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseTable.getLabels().get(labelKey));
}