Java Code Examples for com.google.api.client.http.HttpRequest#setParser()

The following examples show how to use com.google.api.client.http.HttpRequest#setParser() . 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: 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 2
Source File: BatchRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void subTestExecuteWithVoidCallback(boolean testServerError) throws IOException {
  MockTransport transport = new MockTransport(testServerError, false,false, false, false);
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, null, null).setApplicationName("Test Application")
      .build();
  MockGoogleClientRequest<String> jsonHttpRequest1 =
      new MockGoogleClientRequest<String>(client, METHOD1, URI_TEMPLATE1, null, String.class);
  MockGoogleClientRequest<String> jsonHttpRequest2 =
      new MockGoogleClientRequest<String>(client, METHOD2, URI_TEMPLATE2, null, String.class);
  ObjectParser parser = new JsonObjectParser(new JacksonFactory());
  BatchRequest batchRequest =
      new BatchRequest(transport, null).setBatchUrl(new GenericUrl(TEST_BATCH_URL));
  HttpRequest request1 = jsonHttpRequest1.buildHttpRequest();
  request1.setParser(parser);
  HttpRequest request2 = jsonHttpRequest2.buildHttpRequest();
  request2.setParser(parser);
  batchRequest.queue(request1, MockDataClass1.class, GoogleJsonErrorContainer.class, callback1);
  batchRequest.queue(request2, Void.class, Void.class, callback3);
  batchRequest.execute();
  // Assert transport called expected number of times.
  assertEquals(1, transport.actualCalls);
}
 
Example 3
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 4
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 5
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 6
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 7
Source File: FirebaseInstanceId.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private CallableOperation<Void, FirebaseInstanceIdException> deleteInstanceIdOp(
    final String instanceId) {
  checkArgument(!Strings.isNullOrEmpty(instanceId), "instance ID must not be null or empty");
  return new CallableOperation<Void, FirebaseInstanceIdException>() {
    @Override
    protected Void execute() throws FirebaseInstanceIdException {
      String url = String.format(
          "%s/project/%s/instanceId/%s", IID_SERVICE_URL, projectId, instanceId);
      HttpResponse response = null;
      try {
        HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(url));
        request.setParser(new JsonObjectParser(jsonFactory));
        request.setResponseInterceptor(interceptor);
        response = request.execute();
        ByteStreams.exhaust(response.getContent());
      } catch (Exception e) {
        handleError(instanceId, e);
      } finally {
        disconnectQuietly(response);
      }
      return null;
    }
  };
}
 
Example 8
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 9
Source File: HttpHelper.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
<T> void makeRequest(
    HttpRequest baseRequest,
    T parsedResponseInstance,
    String requestIdentifier,
    String requestIdentifierDescription) throws FirebaseProjectManagementException {
  HttpResponse response = null;
  try {
    baseRequest.getHeaders().set(CLIENT_VERSION_HEADER, clientVersion);
    baseRequest.setParser(new JsonObjectParser(jsonFactory));
    baseRequest.setResponseInterceptor(interceptor);
    response = baseRequest.execute();
    jsonFactory.createJsonParser(response.getContent(), Charsets.UTF_8)
        .parseAndClose(parsedResponseInstance);
  } catch (Exception e) {
    handleError(requestIdentifier, requestIdentifierDescription, e);
  } finally {
    disconnectQuietly(response);
  }
}
 
Example 10
Source File: PostRequest.java    From Broadsheet.ie-Android with MIT License 5 votes vote down vote up
@Override
public SinglePost loadDataFromNetwork() throws Exception {
    Log.d(TAG, url);

    HttpRequest request = getHttpRequestFactory().buildGetRequest(new GenericUrl(url));
    request.setParser(new JacksonFactory().createJsonObjectParser());
    return request.execute().parseAs(getResultType());
}
 
Example 11
Source File: PostListRequest.java    From Broadsheet.ie-Android with MIT License 5 votes vote down vote up
@Override
public PostList loadDataFromNetwork() throws Exception {
    Log.d("PostListRequest", "Call web service " + generateUrl());
    HttpRequest request = getHttpRequestFactory().buildGetRequest(new GenericUrl(generateUrl()));
    request.setParser(new JacksonFactory().createJsonObjectParser());
    return request.execute().parseAs(getResultType());
}
 
Example 12
Source File: Authorizer.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
private static UserInfo getUserInfo(Credential credential) throws IOException {
    HttpRequest request = HTTP_TRANSPORT
        .createRequestFactory(credential)
        .buildGetRequest(new GenericUrl(USER_INFO_URI));
    request.getHeaders().setContentType("application/json");
    request.setParser(new JsonObjectParser(JSON_FACTORY));
    HttpResponse response = request.execute();
    return response.parseAs(UserInfo.class);
}
 
Example 13
Source File: ComputeCredential.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected TokenResponse executeRefreshToken() throws IOException {
  GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl());
  HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl);
  request.setParser(new JsonObjectParser(getJsonFactory()));
  request.getHeaders().set("Metadata-Flavor", "Google");
  return request.execute().parseAs(TokenResponse.class);
}
 
Example 14
Source File: DefaultCredentialProvider.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected TokenResponse executeRefreshToken() throws IOException {
  GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl());
  HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl);
  JsonObjectParser parser = new JsonObjectParser(getJsonFactory());
  request.setParser(parser);
  request.getHeaders().set("Metadata-Flavor", "Google");
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  int statusCode = response.getStatusCode();
  if (statusCode == HttpStatusCodes.STATUS_CODE_OK) {
    InputStream content = response.getContent();
    if (content == null) {
      // Throw explicitly rather than allow a later null reference as default mock
      // transports return success codes with empty contents.
      throw new IOException("Empty content from metadata token server request.");
    }
    return parser.parseAndClose(content, response.getContentCharset(), TokenResponse.class);
  }
  if (statusCode == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
    throw new IOException(String.format("Error code %s trying to get security access token from"
        + " Compute Engine metadata for the default service account. This may be because"
        + " the virtual machine instance does not have permission scopes specified.",
        statusCode));
  }
  throw new IOException(String.format("Unexpected Error code %s trying to get security access"
      + " token from Compute Engine metadata for the default service account: %s", statusCode,
      response.parseAsString()));
}
 
Example 15
Source File: AbstractGoogleClientRequest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/** Create a request suitable for use against this service. */
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
  Preconditions.checkArgument(uploader == null);
  Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
  String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
  final HttpRequest httpRequest = getAbstractGoogleClient()
      .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
  new MethodOverride().intercept(httpRequest);
  httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
  // custom methods may use POST with no content but require a Content-Length header
  if (httpContent == null && (requestMethod.equals(HttpMethods.POST)
      || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) {
    httpRequest.setContent(new EmptyContent());
  }
  httpRequest.getHeaders().putAll(requestHeaders);
  if (!disableGZipContent) {
    httpRequest.setEncoding(new GZipEncoding());
  }
  httpRequest.setResponseReturnRawInputStream(returnRawInputStream);
  final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
  httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {

    public void interceptResponse(HttpResponse response) throws IOException {
      if (responseInterceptor != null) {
        responseInterceptor.interceptResponse(response);
      }
      if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
        throw newExceptionOnError(response);
      }
    }
  });
  return httpRequest;
}
 
Example 16
Source File: SplunkHttpSinkTask.java    From kafka-connect-splunk with Apache License 2.0 4 votes vote down vote up
@Override
  public void start(Map<String, String> map) {
    this.config = new SplunkHttpSinkConnectorConfig(map);

    java.util.logging.Logger logger = java.util.logging.Logger.getLogger(HttpTransport.class.getName());
    logger.addHandler(new RequestLoggingHandler(log));
    if (this.config.curlLoggingEnabled) {
      logger.setLevel(Level.ALL);
    } else {
      logger.setLevel(Level.WARNING);
    }

    log.info("Starting...");

    NetHttpTransport.Builder transportBuilder = new NetHttpTransport.Builder();

    if (!this.config.validateCertificates) {
      log.warn("Disabling ssl certificate verification.");
      try {
        transportBuilder.doNotValidateCertificate();
      } catch (GeneralSecurityException e) {
        throw new IllegalStateException("Exception thrown calling transportBuilder.doNotValidateCertificate()", e);
      }
    }

    if (this.config.hasTrustStorePath) {
      log.info("Loading trust store from {}.", this.config.trustStorePath);
      try (FileInputStream inputStream = new FileInputStream(this.config.trustStorePath)) {
        transportBuilder.trustCertificatesFromJavaKeyStore(inputStream, this.config.trustStorePassword);
      } catch (GeneralSecurityException | IOException ex) {
        throw new IllegalStateException("Exception thrown while setting up trust certificates.", ex);
      }
    }

    this.transport = transportBuilder.build();
    final String authHeaderValue = String.format("Splunk %s", this.config.authToken);
    final JsonObjectParser jsonObjectParser = new JsonObjectParser(jsonFactory);

    final String userAgent = String.format("kafka-connect-splunk/%s", version());
    final boolean curlLogging = this.config.curlLoggingEnabled;
    this.httpRequestInitializer = new HttpRequestInitializer() {
      @Override
      public void initialize(HttpRequest httpRequest) throws IOException {
        httpRequest.getHeaders().setAuthorization(authHeaderValue);
        httpRequest.getHeaders().setAccept(Json.MEDIA_TYPE);
        httpRequest.getHeaders().setUserAgent(userAgent);
        httpRequest.setParser(jsonObjectParser);
        httpRequest.setEncoding(new GZipEncoding());
        httpRequest.setThrowExceptionOnExecuteError(false);
        httpRequest.setConnectTimeout(config.connectTimeout);
        httpRequest.setReadTimeout(config.readTimeout);
        httpRequest.setCurlLoggingEnabled(curlLogging);
//        httpRequest.setLoggingEnabled(curlLogging);
      }
    };

    this.httpRequestFactory = this.transport.createRequestFactory(this.httpRequestInitializer);

    this.eventCollectorUrl = new GenericUrl();
    this.eventCollectorUrl.setRawPath("/services/collector/event");
    this.eventCollectorUrl.setPort(this.config.splunkPort);
    this.eventCollectorUrl.setHost(this.config.splunkHost);

    if (this.config.ssl) {
      this.eventCollectorUrl.setScheme("https");
    } else {
      this.eventCollectorUrl.setScheme("http");
    }

    log.info("Setting Splunk Http Event Collector Url to {}", this.eventCollectorUrl);
  }
 
Example 17
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 18
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 19
Source File: YouTubeSampleTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testParsing() throws IOException {
  final InputStream contents = getClass().getClassLoader().getResourceAsStream("youtube-search.json");
  Preconditions.checkNotNull(contents);
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
              result.setContentType(Json.MEDIA_TYPE);
              result.setContent(contents);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setParser(new JsonObjectParser(new GsonFactory()));
  HttpResponse response = request.execute();

  YouTubeSample.ListResponse listResponse = YouTubeSample.parseJson(response);
  assertEquals(5, listResponse.getPageInfo().getResultsPerPage());
  assertEquals(1000000, listResponse.getPageInfo().getTotalResults());
  assertEquals(5, listResponse.getSearchResults().size());
  for (YouTubeSample.SearchResult searchResult : listResponse.getSearchResults()) {
    assertEquals("youtube#searchResult", searchResult.getKind());
    assertNotNull(searchResult.getId());
    assertEquals("youtube#video", searchResult.getId().getKind());
    assertNotNull(searchResult.getId().getVideoId());
    YouTubeSample.Snippet snippet = searchResult.getSnippet();
    assertNotNull(snippet);
    assertNotNull(snippet.getChannelId());
    assertNotNull(snippet.getDescription());
    assertNotNull(snippet.getTitle());
    assertNotNull(snippet.getPublishedAt());
    Map<String, YouTubeSample.Thumbnail> thumbnails = snippet.getThumbnails();
    assertNotNull(thumbnails);

    for (Map.Entry<String, YouTubeSample.Thumbnail> entry : thumbnails.entrySet()) {
      assertNotNull(entry.getKey());
      YouTubeSample.Thumbnail thumbnail = entry.getValue();
      assertNotNull(thumbnail);
      assertNotNull(thumbnail.getUrl());
      assertNotNull(thumbnail.getWidth());
      assertNotNull(thumbnail.getHeight());
    }
  }
}
 
Example 20
Source File: BatchRequestTest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
private BatchRequest getBatchPopulatedWithRequests(boolean testServerError,
    boolean testAuthenticationError,
    boolean returnSuccessAuthenticatedContent,
    boolean testRedirect,
    boolean testBinary,
    boolean testMissingLength) throws IOException {
  transport = new MockTransport(testServerError,
      testAuthenticationError,
      testRedirect,
      testBinary,
      testMissingLength);
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, null, null).setApplicationName("Test Application")
      .build();
  MockGoogleClientRequest<String> jsonHttpRequest1 =
      new MockGoogleClientRequest<String>(client, METHOD1, URI_TEMPLATE1, null, String.class);
  MockGoogleClientRequest<String> jsonHttpRequest2 =
      new MockGoogleClientRequest<String>(client, METHOD2, URI_TEMPLATE2, null, String.class);
  credential = new MockCredential();

  ObjectParser parser =
      testBinary ? new ProtoObjectParser() : new JsonObjectParser(new JacksonFactory());
  BatchRequest batchRequest =
      new BatchRequest(transport, credential).setBatchUrl(new GenericUrl(TEST_BATCH_URL));
  HttpRequest request1 = jsonHttpRequest1.buildHttpRequest();
  request1.setParser(parser);
  HttpRequest request2 = jsonHttpRequest2.buildHttpRequest();
  request2.setParser(parser);
  if (testAuthenticationError) {
    request2.setUnsuccessfulResponseHandler(
        new MockUnsuccessfulResponseHandler(transport, returnSuccessAuthenticatedContent));
  }

  if (testBinary) {
    batchRequest.queue(request1, MockData.Class1.class, ErrorOutput.ErrorBody.class,
        new TestCallback1Adapter(callback1));
    batchRequest.queue(request2, MockData.Class2.class, ErrorOutput.ErrorBody.class,
        new TestCallback2Adapter(callback2));
  } else {
    batchRequest.queue(request1, MockDataClass1.class, GoogleJsonErrorContainer.class, callback1);
    batchRequest.queue(request2, MockDataClass2.class, GoogleJsonErrorContainer.class, callback2);
  }
  return batchRequest;
}