com.google.api.client.json.JsonObjectParser Java Examples

The following examples show how to use com.google.api.client.json.JsonObjectParser. 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 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 #2
Source File: GoogleCredential.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * {@link Beta} <br/>
 * Return a credential defined by a Json file.
 *
 * @param credentialStream the stream with the credential definition.
 * @param transport the transport for Http calls.
 * @param jsonFactory the factory for Json parsing and formatting.
 * @return the credential defined by the credentialStream.
 * @throws IOException if the credential cannot be created from the stream.
 */
@Beta
public static GoogleCredential fromStream(InputStream credentialStream, HttpTransport transport,
    JsonFactory jsonFactory) throws IOException {
  Preconditions.checkNotNull(credentialStream);
  Preconditions.checkNotNull(transport);
  Preconditions.checkNotNull(jsonFactory);

  JsonObjectParser parser = new JsonObjectParser(jsonFactory);
  GenericJson fileContents = parser.parseAndClose(
      credentialStream, OAuth2Utils.UTF_8, GenericJson.class);
  String fileType = (String) fileContents.get("type");
  if (fileType == null) {
    throw new IOException("Error reading credentials from stream, 'type' field not specified.");
  }
  if (USER_FILE_TYPE.equals(fileType)) {
    return fromStreamUser(fileContents, transport, jsonFactory);
  }
  if (SERVICE_ACCOUNT_FILE_TYPE.equals(fileType)) {
    return fromStreamServiceAccount(fileContents, transport, jsonFactory);
  }
  throw new IOException(String.format(
      "Error reading credentials from stream, 'type' value '%s' not recognized."
          + " Expecting '%s' or '%s'.",
      fileType, USER_FILE_TYPE, SERVICE_ACCOUNT_FILE_TYPE));
}
 
Example #3
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 #4
Source File: GerritApiTransportImpl.java    From copybara with Apache License 2.0 6 votes vote down vote up
/**
 * TODO(malcon): Consolidate GitHub and this one in one class
 */
private HttpRequestFactory getHttpRequestFactory(@Nullable UserPassword userPassword)
    throws RepoException, ValidationException {
  return httpTransport.createRequestFactory(
      request -> {
        request.setConnectTimeout((int) Duration.ofMinutes(1).toMillis());
        request.setReadTimeout((int) Duration.ofMinutes(1).toMillis());
        HttpHeaders httpHeaders = new HttpHeaders();
        if (userPassword != null) {
          httpHeaders.setBasicAuthentication(userPassword.getUsername(),
                                             userPassword.getPassword_BeCareful());
        }
        request.setHeaders(httpHeaders);
        request.setParser(new JsonObjectParser(JSON_FACTORY));
      });
}
 
Example #5
Source File: GitHubApiTransportImpl.java    From copybara with Apache License 2.0 6 votes vote down vote up
private HttpRequestFactory getHttpRequestFactory(
    @Nullable UserPassword userPassword, ImmutableListMultimap<String, String> headers) {
  return httpTransport.createRequestFactory(
      request -> {
        request.setConnectTimeout((int) Duration.ofMinutes(1).toMillis());
        request.setReadTimeout((int) Duration.ofMinutes(1).toMillis());
        HttpHeaders httpHeaders = new HttpHeaders();
        if (userPassword != null) {
          httpHeaders.setBasicAuthentication(userPassword.getUsername(),
              userPassword.getPassword_BeCareful());
        }
        for (Map.Entry<String, Collection<String>> header : headers.asMap().entrySet()) {
          httpHeaders.put(header.getKey(), header.getValue());
        }
        request.setHeaders(httpHeaders);
        request.setParser(new JsonObjectParser(JSON_FACTORY));
      });
}
 
Example #6
Source File: GoogleAuthTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException {
  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("application/json");
          result.setContent(content);
          result.setStatusCode(statusCode);
          return result;
        }
      };
    }
  };
  HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory()));
  GoogleAuth.configureErrorHandling(httpRequest);
  return httpRequest;
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: DailyMotionSample.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  try {
    DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
    final Credential credential = authorize();
    HttpRequestFactory requestFactory =
        HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
          @Override
          public void initialize(HttpRequest request) throws IOException {
            credential.initialize(request);
            request.setParser(new JsonObjectParser(JSON_FACTORY));
          }
        });
    run(requestFactory);
    // Success!
    return;
  } catch (IOException e) {
    System.err.println(e.getMessage());
  } catch (Throwable t) {
    t.printStackTrace();
  }
  System.exit(1);
}
 
Example #17
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testJsonObjectParser_inputStreamWrapped() throws Exception {
  JsonFactory factory = newFactory();
  JsonObjectParser parser =
      new JsonObjectParser.Builder(factory).setWrapperKeys(Collections.singleton("d")).build();
  Simple simple =
      parser.parseAndClose(
          new ByteArrayInputStream(StringUtils.getBytesUtf8(SIMPLE_WRAPPED)),
          Charsets.UTF_8,
          Simple.class);
  assertEquals("b", simple.a);
}
 
Example #18
Source File: CredentialFactory.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Override
protected TokenResponse executeRefreshToken() throws IOException {
  HttpRequest request =
      getTransport()
          .createRequestFactory(getRequestInitializer())
          .buildGetRequest(new GenericUrl(getTokenServerEncodedUrl()))
          .setParser(new JsonObjectParser(getJsonFactory()));
  request.getHeaders().set("Metadata-Flavor", "Google");
  return request.execute().parseAs(TokenResponse.class);
}
 
Example #19
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 #20
Source File: AbstractJsonParserTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParse_basic() throws IOException {
  JsonObjectParser parser = new JsonObjectParser(newJsonFactory());
  InputStream inputStream = new ByteArrayInputStream(TEST_JSON.getBytes(StandardCharsets.UTF_8));
  GenericJson json = parser.parseAndClose(inputStream, StandardCharsets.UTF_8, GenericJson.class);

  assertTrue(json.get("strValue") instanceof String);
  assertEquals("bar", json.get("strValue"));
  assertTrue(json.get("intValue") instanceof BigDecimal);
  assertEquals(new BigDecimal(123), json.get("intValue"));
  assertTrue(json.get("boolValue") instanceof Boolean);
  assertEquals(Boolean.FALSE, json.get("boolValue"));
}
 
Example #21
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 #22
Source File: AbstractGoogleJsonClient.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param transport HTTP transport
 * @param jsonFactory JSON factory
 * @param rootUrl root URL of the service
 * @param servicePath service path
 * @param httpRequestInitializer HTTP request initializer or {@code null} for none
 * @param legacyDataWrapper whether using the legacy data wrapper in responses
 */
protected Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl,
    String servicePath, HttpRequestInitializer httpRequestInitializer,
    boolean legacyDataWrapper) {
  super(transport, rootUrl, servicePath, new JsonObjectParser.Builder(
      jsonFactory).setWrapperKeys(
      legacyDataWrapper ? Arrays.asList("data", "error") : Collections.<String>emptySet())
      .build(), httpRequestInitializer);
}
 
Example #23
Source File: TokenResponseException.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link TokenResponseException}.
 *
 * <p>
 * If there is a JSON error response, it is parsed using {@link TokenErrorResponse}, which can be
 * inspected using {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 *
 * @param jsonFactory JSON factory
 * @param response HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static TokenResponseException from(JsonFactory jsonFactory, HttpResponse response) {
  HttpResponseException.Builder builder = new HttpResponseException.Builder(
      response.getStatusCode(), response.getStatusMessage(), response.getHeaders());
  // details
  Preconditions.checkNotNull(jsonFactory);
  TokenErrorResponse details = null;
  String detailString = null;
  String contentType = response.getContentType();
  try {
    if (!response.isSuccessStatusCode() && contentType != null && response.getContent() != null
        && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
      details = new JsonObjectParser(jsonFactory).parseAndClose(
          response.getContent(), response.getContentCharset(), TokenErrorResponse.class);
      detailString = details.toPrettyString();
    } else {
      detailString = response.parseAsString();
    }
  } catch (IOException exception) {
    // it would be bad to throw an exception while throwing an exception
    exception.printStackTrace();
  }
  // message
  StringBuilder message = HttpResponseException.computeMessageBuffer(response);
  if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
    message.append(StringUtils.LINE_SEPARATOR).append(detailString);
    builder.setContent(detailString);
  }
  builder.setMessage(message.toString());
  return new TokenResponseException(builder, details);
}
 
Example #24
Source File: QueryBuilder.java    From android-google-places with MIT License 5 votes vote down vote up
/**
 * @param transport
 * @return
 */
private static HttpRequestFactory createRequestFactory(final HttpTransport transport) {

	return transport.createRequestFactory(new HttpRequestInitializer() {
		public void initialize(HttpRequest request) {
			request.setHeaders(new HttpHeaders());
			request.setParser(new JsonObjectParser(new GsonFactory()));
		}
	});
}
 
Example #25
Source File: VaultEndpoint.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public VaultEndpoint(final VaultConfiguration conf, HttpTransport transport) throws VaultException {
  this.conf = conf;
  requestFactory = transport.createRequestFactory(
      new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) throws IOException {
          request.setParser(new JsonObjectParser(JSON_FACTORY));
          request.setHeaders(new HttpHeaders().set("X-Vault-Token", conf.getToken()));
          request.setReadTimeout(conf.getReadTimeout());
          request.setConnectTimeout(conf.getOpenTimeout());
        }
      }
  );
}
 
Example #26
Source File: UploadRequestTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadFile() throws IOException {
  InputStream inputStream = new ByteArrayInputStream(testJsonFile.getBytes("UTF-8"));
  UploadRequest upload =
      new JsonObjectParser(JacksonFactory.getDefaultInstance()).parseAndClose(
          new InputStreamReader(inputStream, defaultCharset()), UploadRequest.class);

  assertEquals("testSourceId", upload.sourceId);
  assertEquals(4, upload.requests.size());
  assertThat(upload.requests.get(0), instanceOf(DeleteRequest.class));
  assertThat(upload.requests.get(1), instanceOf(GetRequest.class));
  assertThat(upload.requests.get(2), instanceOf(IndexItemRequest.class));
  assertThat(upload.requests.get(3), instanceOf(IndexItemAndContentRequest.class));
}
 
Example #27
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testJsonObjectParser_readerWrapped() throws Exception {
  JsonFactory factory = newFactory();
  JsonObjectParser parser =
      new JsonObjectParser.Builder(factory).setWrapperKeys(Collections.singleton("d")).build();
  Simple simple = parser.parseAndClose(new StringReader(SIMPLE_WRAPPED), Simple.class);
  assertEquals("b", simple.a);
}
 
Example #28
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 #29
Source File: AbstractJsonParserTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParse_bigDecimal() throws IOException {
  JsonObjectParser parser = new JsonObjectParser(newJsonFactory());
  InputStream inputStream =
      new ByteArrayInputStream(TEST_JSON_BIG_DECIMAL.getBytes(StandardCharsets.UTF_8));
  GenericJson json = parser.parseAndClose(inputStream, StandardCharsets.UTF_8, GenericJson.class);

  assertTrue(json.get("bigDecimalValue") instanceof BigDecimal);
  assertEquals(new BigDecimal("1559341956102"), json.get("bigDecimalValue"));
}
 
Example #30
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testJsonObjectParser_inputStream() throws Exception {
  JsonFactory factory = newFactory();
  JsonObjectParser parser = new JsonObjectParser(factory);
  Simple simple =
      parser.parseAndClose(
          new ByteArrayInputStream(StringUtils.getBytesUtf8(SIMPLE)),
          Charsets.UTF_8,
          Simple.class);
  assertEquals("b", simple.a);
}