Java Code Examples for com.google.api.client.http.HttpRequestFactory#buildPostRequest()

The following examples show how to use com.google.api.client.http.HttpRequestFactory#buildPostRequest() . 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: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
   * This methods is adds a document that exists in Mendeley to a specific folder
   * via the POST https://api.mendeley.com/folders/{id}/documents endpoint.
   * @param document This methods needs a dkocument to add
   * @param folder_id This passes the folder where to document is added to
   */
  public void addDocumentToFolder(MendeleyDocument document, String folder_id){
  	refreshTokenIfNecessary();
  	
  	HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  	HttpRequest request;
  	HttpRequest patch_request;
  	
  	Gson gson = new GsonBuilder().create();
  	String json_body = "{\"id\": \""+ document.getId() + "\" }";
  	String resource_url = "https://api.mendeley.com/folders/"+ folder_id + "/documents";
  	GenericUrl gen_url = new GenericUrl(resource_url);
  		
try {
	final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
	patch_request = requestFactory.buildPostRequest(gen_url, content);
	patch_request.getHeaders().setAuthorization("Bearer " + access_token);
	patch_request.getHeaders().setContentType("application/vnd.mendeley-document.1+json");
	String rawResponse = patch_request.execute().parseAsString();
} catch (IOException e) {
	e.printStackTrace();
}
  }
 
Example 2
Source File: OAuthUtils.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
static String makeRawPostRequest(HttpTransport httpTransport, String url, HttpContent httpContent)
    throws IOException {
  HttpRequestFactory factory = httpTransport.createRequestFactory();
  HttpRequest postRequest = factory.buildPostRequest(new GenericUrl(url), httpContent);
  HttpResponse response = postRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }
  return CharStreams
      .toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
}
 
Example 3
Source File: GooglePhotosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
<T> T makePostRequest(
    String url, Optional<Map<String, String>> parameters, HttpContent httpContent, Class<T> clazz)
    throws IOException, InvalidTokenException, PermissionDeniedException {
  // Wait for write permit before making request
  writeRateLimiter.acquire();

  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest postRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent);
  postRequest.setReadTimeout(2 * 60000); // 2 minutes read timeout
  HttpResponse response;

  try {
    response = postRequest.execute();
  } catch (HttpResponseException e) {
    response =
        handleHttpResponseException(
            () ->
                requestFactory.buildPostRequest(
                    new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent),
            e);
  }

  Preconditions.checkState(response.getStatusCode() == 200);
  String result =
      CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
  if (clazz.isAssignableFrom(String.class)) {
    return (T) result;
  } else {
    return objectMapper.readValue(result, clazz);
  }
}
 
Example 4
Source File: GoogleVideosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
<T> T makePostRequest(
    String url, Optional<Map<String, String>> parameters, HttpContent httpContent, Class<T> clazz)
    throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest postRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent);

  // TODO: Figure out why this is necessary for videos but not for photos
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType("application/octet-stream");
  headers.setAuthorization("Bearer " + this.credential.getAccessToken());
  headers.set("X-Goog-Upload-Protocol", "raw");
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }
  String result =
      CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
  if (clazz.isAssignableFrom(String.class)) {
    return (T) result;
  } else {
    return objectMapper.readValue(result, clazz);
  }
}
 
Example 5
Source File: TestUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public static HttpRequest createRequest(MockLowLevelHttpRequest request) throws IOException {
  HttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(request)
      .build();
  HttpRequestFactory requestFactory = transport.createRequestFactory();
  return requestFactory.buildPostRequest(TEST_URL, new EmptyContent());
}
 
Example 6
Source File: CloudClientLibGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
InputStream postRequest(String url, String boundary, String content) throws IOException {
  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url),
      ByteArrayContent.fromString("multipart/form-data; boundary=" + boundary, content));
  request.setReadTimeout(60000);  // 60 seconds is the max App Engine request time
  HttpResponse response = request.execute();
  if (response.getStatusCode() >= 300) {
    throw new IOException("Client Generation failed at server side: " + response.getContent());
  } else {
    return response.getContent();
  }
}
 
Example 7
Source File: TaskQueueNotificationServlet.java    From abelana with Apache License 2.0 5 votes vote down vote up
@Override
public final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
    throws IOException {
  HttpTransport httpTransport;
  try {
    Map<Object, Object> params = new HashMap<>();
    params.putAll(req.getParameterMap());
    params.put("task", req.getHeader("X-AppEngine-TaskName"));

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.getApplicationDefault()
        .createScoped(Collections.singleton("https://www.googleapis.com/auth/userinfo.email"));
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    GenericUrl url = new GenericUrl(ConfigurationConstants.IMAGE_RESIZER_URL);

    HttpRequest request = requestFactory.buildPostRequest(url, new UrlEncodedContent(params));
    credential.initialize(request);

    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      log("Call to the imageresizer failed: " + response.getContent().toString());
      resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
    } else {
      resp.setStatus(response.getStatusCode());
    }

  } catch (GeneralSecurityException | IOException e) {
    log("Http request error: " + e.getMessage());
    resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
  }
}
 
Example 8
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
   * This methods is used to add a new document to Mendeley via the POST https://api.mendeley.com/documents endpoint.
   * A successful response contains the newly added MendeleyDocument.
   * 
   * @param entry A BibTeXEntry is needed to add MendeleyDocument
   * @return This returns a MendeleyDocument if request was successful
   */
  public MendeleyDocument addDocument(BibTeXEntry entry ){
  	refreshTokenIfNecessary();
  	
  	HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  	HttpRequest request;
  	HttpRequest patch_request;
  	MendeleyDocument document = null;
  	
  	// create a new MendeleyDocument and add the fields from BibTeXEntry that should be added
  	MendeleyDocument document_to_add = new MendeleyDocument(entry);
  	
  	Gson gson = new GsonBuilder().create();
  	String json_body = gson.toJson(document_to_add);
  	
  	String resource_url = "https://api.mendeley.com/documents";
  	GenericUrl gen_url = new GenericUrl(resource_url); 	
  	
try {
	final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
	
	patch_request = requestFactory.buildPostRequest(gen_url, content);
	patch_request.getHeaders().setAuthorization("Bearer " + access_token);
	patch_request.getHeaders().setContentType("application/vnd.mendeley-document.1+json");
	String rawResponse = patch_request.execute().parseAsString();
	document = gson.fromJson(rawResponse, MendeleyDocument.class);
} catch (IOException e ) {
	e.printStackTrace();
}

return document;
  }
 
Example 9
Source File: BatchJobUploader.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Initiates the resumable upload by sending a request to Google Cloud Storage.
 *
 * @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob}
 * @return the URI for the initiated resumable upload
 */
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException {
  // This follows the Google Cloud Storage guidelines for initiating resumable uploads:
  // https://cloud.google.com/storage/docs/resumable-uploads-xml
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(
          req -> {
            HttpHeaders headers = createHttpHeaders();
            headers.setContentLength(0L);
            headers.set("x-goog-resumable", "start");
            req.setHeaders(headers);
            req.setLoggingEnabled(true);
          });

  try {
    HttpRequest httpRequest =
        requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent());
    HttpResponse response = httpRequest.execute();
    if (response.getHeaders() == null || response.getHeaders().getLocation() == null) {
      throw new BatchJobException(
          "Initiate upload failed. Resumable upload URI was not in the response.");
    }
    return URI.create(response.getHeaders().getLocation());
  } catch (IOException e) {
    throw new BatchJobException("Failed to initiate upload", e);
  }
}
 
Example 10
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 dataset.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelDataset(
    String projectId, String datasetId, 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.
  Dataset dataset = new Dataset();
  dataset.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(String.format(urlFormat, projectId, datasetId, 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());
  }

  Dataset responseDataset = response.parseAs(Dataset.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseDataset.getLabels().get(labelKey));
}
 
Example 11
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));
}
 
Example 12
Source File: ReportRequestFactoryHelperTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Tests the factory builds the request properly for this test's attributes. */
@Test
public void testGetHttpRequestFactory()
    throws ValidationException, AuthenticationException, IOException {
  final int timeoutFromLibConfig = 42;
  when(adWordsLibConfiguration.getReportDownloadTimeout()).thenReturn(timeoutFromLibConfig);
  AdWordsSession session =
      new AdWordsSession.Builder()
          .withDeveloperToken("foodevtoken")
          .withClientCustomerId("fooclientcustomerid")
          .withOAuth2Credential(credential)
          .withUserAgent("userAgent")
          .withReportingConfiguration(reportingConfiguration)
          .build();
  when(authorizationHeaderProvider.getAuthorizationHeader(session, ENDPOINT_URL.build()))
      .thenReturn("fooauthheader");
  when(userAgentCombiner.getUserAgent(anyString())).thenReturn("foouseragent");
  ReportRequestFactoryHelper helper =
      new ReportRequestFactoryHelper(
          session,
          authorizationHeaderProvider,
          userAgentCombiner,
          transport,
          adWordsLibConfiguration,
          reportResponseInterceptor);
  HttpRequestFactory requestFactory = helper.getHttpRequestFactory(ENDPOINT_URL.build(), version);

  HttpRequest request =
      requestFactory.buildPostRequest(
          ENDPOINT_URL, new AwqlReportBodyProvider("select 1", "csv").getHttpContent());
  HttpHeaders headers = request.getHeaders();
  assertEquals("foodevtoken", headers.get("developerToken"));
  assertEquals("fooauthheader", headers.getAuthorization());
  assertEquals("fooclientcustomerid", headers.get("clientCustomerId"));
  assertTrue((headers.getUserAgent()).contains("foouseragent"));

  if (reportingConfiguration == null) {
    assertFalse(
        "skipReportHeader should not be in the header if no reporting config is set",
        headers.containsKey("skipReportHeader"));
    assertFalse(
        "skipReportSummary should not be in the header if no reporting config is set",
        headers.containsKey("skipReportSummary"));
    assertEquals(
        "connect timeout is incorrect", timeoutFromLibConfig, request.getConnectTimeout());
    assertEquals("read timeout is incorrect", timeoutFromLibConfig, request.getReadTimeout());
  } else {
    Integer expectedTimeout = reportingConfiguration.getReportDownloadTimeout();
    if (expectedTimeout == null) {
      // Should fall back to the library level config value if the reporting config does not have
      // a timeout set.
      expectedTimeout = timeoutFromLibConfig;
    }
    assertEquals(
        "connect timeout is incorrect", expectedTimeout.intValue(), request.getConnectTimeout());
    assertEquals(
        "read timeout is incorrect", expectedTimeout.intValue(), request.getReadTimeout());
    assertEquals(
        "skipReportHeader not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isSkipReportHeader()),
        headers.get("skipReportHeader"));
    assertEquals(
        "skipColumnHeader not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isSkipColumnHeader()),
        headers.get("skipColumnHeader"));
    assertEquals(
        "skipReportSummary not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isSkipReportSummary()),
        headers.get("skipReportSummary"));
    assertEquals(
        "includeZeroImpressions not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isIncludeZeroImpressions()),
        headers.get("includeZeroImpressions"));
    assertEquals(
        "useRawEnumValues not equal to the reporting config setting",
        toStringBoolean(reportingConfiguration.isUseRawEnumValues()),
        headers.get("useRawEnumValues"));
  }
}