Java Code Examples for com.google.api.client.util.StringUtils

The following examples show how to use com.google.api.client.util.StringUtils. These examples are extracted from open source projects. 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 Project: google-http-java-client   Source File: JsonWebSignature.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses a JWS token into a parsed {@link JsonWebSignature}.
 *
 * @param tokenString JWS token string
 * @return parsed {@link JsonWebSignature}
 */
public JsonWebSignature parse(String tokenString) throws IOException {
  // split on the dots
  int firstDot = tokenString.indexOf('.');
  Preconditions.checkArgument(firstDot != -1);
  byte[] headerBytes = Base64.decodeBase64(tokenString.substring(0, firstDot));
  int secondDot = tokenString.indexOf('.', firstDot + 1);
  Preconditions.checkArgument(secondDot != -1);
  Preconditions.checkArgument(tokenString.indexOf('.', secondDot + 1) == -1);
  // decode the bytes
  byte[] payloadBytes = Base64.decodeBase64(tokenString.substring(firstDot + 1, secondDot));
  byte[] signatureBytes = Base64.decodeBase64(tokenString.substring(secondDot + 1));
  byte[] signedContentBytes = StringUtils.getBytesUtf8(tokenString.substring(0, secondDot));
  // parse the header and payload
  Header header =
      jsonFactory.fromInputStream(new ByteArrayInputStream(headerBytes), headerClass);
  Preconditions.checkArgument(header.getAlgorithm() != null);
  Payload payload =
      jsonFactory.fromInputStream(new ByteArrayInputStream(payloadBytes), payloadClass);
  return new JsonWebSignature(header, payload, signatureBytes, signedContentBytes);
}
 
Example 2
Source Project: google-http-java-client   Source File: JsonWebSignature.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Signs a given JWS header and payload based on the given private key using RSA and SHA-256 as
 * described in <a
 * href="http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-11#appendix-A.2">JWS using
 * RSA SHA-256</a>.
 *
 * @param privateKey private key
 * @param jsonFactory JSON factory
 * @param header JWS header
 * @param payload JWS payload
 * @return signed JWS string
 * @since 1.14 (since 1.7 as com.google.api.client.auth.jsontoken.RsaSHA256Signer)
 */
public static String signUsingRsaSha256(
    PrivateKey privateKey,
    JsonFactory jsonFactory,
    JsonWebSignature.Header header,
    JsonWebToken.Payload payload)
    throws GeneralSecurityException, IOException {
  String content =
      Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header))
          + "."
          + Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(payload));
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  byte[] signature =
      SecurityUtils.sign(
          SecurityUtils.getSha256WithRsaSignatureAlgorithm(), privateKey, contentBytes);
  return content + "." + Base64.encodeBase64URLSafeString(signature);
}
 
Example 3
Source Project: google-http-java-client   Source File: TestCertificates.java    License: Apache License 2.0 6 votes vote down vote up
public static JsonWebSignature getJsonWebSignature() throws IOException {
  if (jsonWebSignature == null) {
    JsonWebSignature.Header header = new JsonWebSignature.Header();
    header.setAlgorithm("RS256");
    List<String> certificates = Lists.newArrayList();
    certificates.add(FOO_BAR_COM_CERT.getBase64Der());
    certificates.add(CA_CERT.getBase64Der());
    header.setX509Certificates(certificates);
    JsonWebToken.Payload payload = new JsonWebToken.Payload();
    payload.set("foo", "bar");
    int firstDot = JWS_SIGNATURE.indexOf('.');
    int secondDot = JWS_SIGNATURE.indexOf('.', firstDot + 1);
    byte[] signatureBytes = Base64.decodeBase64(JWS_SIGNATURE.substring(secondDot + 1));
    byte[] signedContentBytes = StringUtils.getBytesUtf8(JWS_SIGNATURE.substring(0, secondDot));
    JsonWebSignature signature =
        new JsonWebSignature(header, payload, signatureBytes, signedContentBytes);
    jsonWebSignature = signature;
  }
  return jsonWebSignature;
}
 
Example 4
private void subtestContent(String expectedContent, String boundaryString, String... contents)
    throws Exception {
  // multipart content
  MultipartContent content =
      new MultipartContent(boundaryString == null ? BOUNDARY : boundaryString);
  for (String contentValue : contents) {
    content.addPart(
        new MultipartContent.Part(ByteArrayContent.fromString(CONTENT_TYPE, contentValue)));
  }
  if (boundaryString != null) {
    content.setBoundary(boundaryString);
  }
  // write to string
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  content.writeTo(out);
  assertEquals(expectedContent, out.toString(Charsets.UTF_8.name()));
  assertEquals(StringUtils.getBytesUtf8(expectedContent).length, content.getLength());
  assertEquals(
      boundaryString == null
          ? "multipart/related; boundary=" + BOUNDARY
          : "multipart/related; boundary=" + boundaryString,
      content.getType());
}
 
Example 5
public void testAbruptTerminationIsNoticedWithContentLength() throws Exception {
  String incompleteBody = "" + "Fixed size body test.\r\n" + "Incomplete response.";
  byte[] buf = StringUtils.getBytesUtf8(incompleteBody);
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL))
          .setResponseCode(200)
          .addHeader("Content-Length", "205")
          .setInputStream(new ByteArrayInputStream(buf));
  connection.setRequestMethod("GET");
  NetHttpRequest request = new NetHttpRequest(connection);
  setContent(request, null, "");
  NetHttpResponse response = (NetHttpResponse) (request.execute());

  InputStream in = response.getContent();
  boolean thrown = false;
  try {
    while (in.read() != -1) {
      // This space is intentionally left blank.
    }
  } catch (IOException ioe) {
    thrown = true;
  }
  assertTrue(thrown);
}
 
Example 6
public void testAbruptTerminationIsNoticedWithContentLengthWithReadToBuf() throws Exception {
  String incompleteBody = "" + "Fixed size body test.\r\n" + "Incomplete response.";
  byte[] buf = StringUtils.getBytesUtf8(incompleteBody);
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL))
          .setResponseCode(200)
          .addHeader("Content-Length", "205")
          .setInputStream(new ByteArrayInputStream(buf));
  connection.setRequestMethod("GET");
  NetHttpRequest request = new NetHttpRequest(connection);
  setContent(request, null, "");
  NetHttpResponse response = (NetHttpResponse) (request.execute());

  InputStream in = response.getContent();
  boolean thrown = false;
  try {
    while (in.read(new byte[100]) != -1) {
      // This space is intentionally left blank.
    }
  } catch (IOException ioe) {
    thrown = true;
  }
  assertTrue(thrown);
}
 
Example 7
public void subtestGetContent(int responseCode) throws IOException {
  NetHttpResponse response =
      new NetHttpResponse(
          new MockHttpURLConnection(null)
              .setResponseCode(responseCode)
              .setInputStream(new ByteArrayInputStream(StringUtils.getBytesUtf8(VALID_RESPONSE)))
              .setErrorStream(
                  new ByteArrayInputStream(StringUtils.getBytesUtf8(ERROR_RESPONSE))));
  InputStream is = response.getContent();
  byte[] buf = new byte[100];
  int bytes = 0, n = 0;
  while ((n = is.read(buf)) != -1) {
    bytes += n;
  }
  if (responseCode < 400) {
    assertEquals(VALID_RESPONSE, new String(buf, 0, bytes, Charset.forName("UTF-8")));
  } else {
    assertEquals(ERROR_RESPONSE, new String(buf, 0, bytes, Charset.forName("UTF-8")));
  }
}
 
Example 8
public void subtestGetContentWithShortRead(int responseCode) throws IOException {
  NetHttpResponse response =
      new NetHttpResponse(
          new MockHttpURLConnection(null)
              .setResponseCode(responseCode)
              .setInputStream(new ByteArrayInputStream(StringUtils.getBytesUtf8(VALID_RESPONSE)))
              .setErrorStream(
                  new ByteArrayInputStream(StringUtils.getBytesUtf8(ERROR_RESPONSE))));
  InputStream is = response.getContent();
  byte[] buf = new byte[100];
  int bytes = 0, b = 0;
  while ((b = is.read()) != -1) {
    buf[bytes++] = (byte) b;
  }
  if (responseCode < 400) {
    assertEquals(VALID_RESPONSE, new String(buf, 0, bytes, Charset.forName("UTF-8")));
  } else {
    assertEquals(ERROR_RESPONSE, new String(buf, 0, bytes, Charset.forName("UTF-8")));
  }
}
 
Example 9
Source Project: google-http-java-client   Source File: HttpRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testExecute_redirectWithIncorrectContentRetryableSetting() throws Exception {
  // TODO(yanivi): any way we can warn user about this?
  RedirectTransport fakeTransport = new RedirectTransport();
  String contentValue = "hello";
  fakeTransport.expectedContent = new String[] {contentValue, ""};
  byte[] bytes = StringUtils.getBytesUtf8(contentValue);
  InputStreamContent content =
      new InputStreamContent(
          new HttpMediaType("text/plain").setCharsetParameter(Charsets.UTF_8).build(),
          new ByteArrayInputStream(bytes));
  content.setRetrySupported(true);
  HttpRequest request =
      fakeTransport
          .createRequestFactory()
          .buildPostRequest(HttpTesting.SIMPLE_GENERIC_URL, content);
  HttpResponse resp = request.execute();
  assertEquals(200, resp.getStatusCode());
  assertEquals(2, fakeTransport.lowLevelExecCalls);
}
 
Example 10
Source Project: google-oauth-java-client   Source File: OAuthHmacSigner.java    License: Apache License 2.0 6 votes vote down vote up
public String computeSignature(String signatureBaseString) throws GeneralSecurityException {
  // compute key
  StringBuilder keyBuf = new StringBuilder();
  String clientSharedSecret = this.clientSharedSecret;
  if (clientSharedSecret != null) {
    keyBuf.append(OAuthParameters.escape(clientSharedSecret));
  }
  keyBuf.append('&');
  String tokenSharedSecret = this.tokenSharedSecret;
  if (tokenSharedSecret != null) {
    keyBuf.append(OAuthParameters.escape(tokenSharedSecret));
  }
  String key = keyBuf.toString();
  // sign
  SecretKey secretKey = new SecretKeySpec(StringUtils.getBytesUtf8(key), "HmacSHA1");
  Mac mac = Mac.getInstance("HmacSHA1");
  mac.init(secretKey);
  return Base64.encodeBase64String(mac.doFinal(StringUtils.getBytesUtf8(signatureBaseString)));
}
 
Example 11
Source Project: firebase-admin-java   Source File: FirebaseTokenFactory.java    License: Apache License 2.0 5 votes vote down vote up
private String signPayload(JsonWebSignature.Header header,
    FirebaseCustomAuthToken.Payload payload) throws IOException {
  String headerString = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header));
  String payloadString = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(payload));
  String content = headerString + "." + payloadString;
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  String signature = Base64.encodeBase64URLSafeString(signer.sign(contentBytes));
  return content + "." + signature;
}
 
Example 12
Source Project: firebase-admin-java   Source File: CryptoSigners.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a {@link CryptoSigner} instance for the given Firebase app. Follows the protocol
 * documented at go/firebase-admin-sign.
 */
public static CryptoSigner getCryptoSigner(FirebaseApp firebaseApp) throws IOException {
  GoogleCredentials credentials = ImplFirebaseTrampolines.getCredentials(firebaseApp);

  // If the SDK was initialized with a service account, use it to sign bytes.
  if (credentials instanceof ServiceAccountCredentials) {
    return new ServiceAccountCryptoSigner((ServiceAccountCredentials) credentials);
  }

  FirebaseOptions options = firebaseApp.getOptions();
  HttpRequestFactory requestFactory = options.getHttpTransport().createRequestFactory(
      new FirebaseRequestInitializer(firebaseApp));
  JsonFactory jsonFactory = options.getJsonFactory();

  // If the SDK was initialized with a service account email, use it with the IAM service
  // to sign bytes.
  String serviceAccountId = options.getServiceAccountId();
  if (!Strings.isNullOrEmpty(serviceAccountId)) {
    return new IAMCryptoSigner(requestFactory, jsonFactory, serviceAccountId);
  }

  // If the SDK was initialized with some other credential type that supports signing
  // (e.g. GAE credentials), use it to sign bytes.
  if (credentials instanceof ServiceAccountSigner) {
    return new ServiceAccountCryptoSigner((ServiceAccountSigner) credentials);
  }

  // Attempt to discover a service account email from the local Metadata service. Use it
  // with the IAM service to sign bytes.
  HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(METADATA_SERVICE_URL));
  request.getHeaders().set("Metadata-Flavor", "Google");
  HttpResponse response = request.execute();
  try {
    byte[] output = ByteStreams.toByteArray(response.getContent());
    serviceAccountId = StringUtils.newStringUtf8(output).trim();
    return new IAMCryptoSigner(requestFactory, jsonFactory, serviceAccountId);
  } finally {
    response.disconnect();
  }
}
 
Example 13
Source Project: styx   Source File: GoogleIdTokenAuth.java    License: Apache License 2.0 5 votes vote down vote up
private String getServiceAccountIdTokenUsingAccessToken(GoogleCredentials credentials,
                                                        String serviceAccount, String targetAudience)
    throws IOException {
  final String tokenServerUrl = "https://oauth2.googleapis.com/token";
  final Header header = jwtHeader();
  final JsonWebToken.Payload payload = jwtPayload(
      targetAudience, serviceAccount, tokenServerUrl);
  final Iam iam = new Iam.Builder(httpTransport, JSON_FACTORY,
      new HttpCredentialsAdapter(withScopes(credentials, IamScopes.all()))).build();
  final String content = Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(header)) + "."
                         + Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(payload));
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  final SignBlobResponse signResponse;
  try {
    signResponse = iam.projects().serviceAccounts()
        .signBlob("projects/-/serviceAccounts/" + serviceAccount, new SignBlobRequest()
            .encodeBytesToSign(contentBytes))
        .execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 403) {
      throw new IOException(
          "Unable to sign request for id token, missing Service Account Token Creator role for self on "
          + serviceAccount + " or IAM api not enabled?", e);
    }
    throw e;
  }
  final String assertion = content + "." + signResponse.getSignature();
  final TokenRequest request = new TokenRequest(
      httpTransport, JSON_FACTORY,
      new GenericUrl(tokenServerUrl),
      "urn:ietf:params:oauth:grant-type:jwt-bearer");
  request.put("assertion", assertion);
  final TokenResponse tokenResponse = request.execute();
  return (String) tokenResponse.get("id_token");
}
 
Example 14
Source Project: nomulus   Source File: IcannHttpReporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess() throws Exception {
  IcannHttpReporter reporter = createReporter();
  reporter.send(FAKE_PAYLOAD, "test-transactions-201706.csv");

  assertThat(mockRequest.getUrl()).isEqualTo("https://fake-transactions.url/test/2017-06");
  Map<String, List<String>> headers = mockRequest.getHeaders();
  String userPass = "test_ry:fakePass";
  String expectedAuth =
      String.format("Basic %s", Base64.encodeBase64String(StringUtils.getBytesUtf8(userPass)));
  assertThat(headers.get("authorization")).containsExactly(expectedAuth);
  assertThat(headers.get("content-type")).containsExactly(CSV_UTF_8.toString());
}
 
Example 15
Source Project: nomulus   Source File: IcannHttpReporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_internationalTld() throws Exception {
  IcannHttpReporter reporter = createReporter();
  reporter.send(FAKE_PAYLOAD, "xn--abc123-transactions-201706.csv");

  assertThat(mockRequest.getUrl()).isEqualTo("https://fake-transactions.url/xn--abc123/2017-06");
  Map<String, List<String>> headers = mockRequest.getHeaders();
  String userPass = "xn--abc123_ry:fakePass";
  String expectedAuth =
      String.format("Basic %s", Base64.encodeBase64String(StringUtils.getBytesUtf8(userPass)));
  assertThat(headers.get("authorization")).containsExactly(expectedAuth);
  assertThat(headers.get("content-type")).containsExactly(CSV_UTF_8.toString());
}
 
Example 16
@Test
public void testVerifyES256() throws Exception {
  PublicKey publicKey = buildEs256PublicKey(GOOGLE_ES256_X, GOOGLE_ES256_Y);
  JsonWebSignature.Header header = new JsonWebSignature.Header();
  header.setAlgorithm("ES256");
  JsonWebSignature.Payload payload = new JsonWebToken.Payload();
  byte[] signatureBytes = Base64.decodeBase64(ES256_SIGNATURE);
  byte[] signedContentBytes = StringUtils.getBytesUtf8(ES256_CONTENT);
  JsonWebSignature jsonWebSignature =
      new JsonWebSignature(header, payload, signatureBytes, signedContentBytes);
  Assert.assertTrue(jsonWebSignature.verifySignature(publicKey));
}
 
Example 17
public void testRandomContent() throws Exception {
  MultipartContent content = new MultipartContent();
  String boundaryString = content.getBoundary();
  assertNotNull(boundaryString);
  assertTrue(boundaryString.startsWith(BOUNDARY));
  assertTrue(boundaryString.endsWith("__"));
  assertEquals("multipart/related; boundary=" + boundaryString, content.getType());

  final String[][] VALUES =
      new String[][] {
        {"Hello world", "text/plain"},
        {"<xml>Hi</xml>", "application/xml"},
        {"{x:1,y:2}", "application/json"}
      };
  StringBuilder expectedStringBuilder = new StringBuilder();
  for (String[] valueTypePair : VALUES) {
    String contentValue = valueTypePair[0];
    String contentType = valueTypePair[1];
    content.addPart(
        new MultipartContent.Part(ByteArrayContent.fromString(contentType, contentValue)));
    expectedStringBuilder
        .append("--")
        .append(boundaryString)
        .append(CRLF)
        .append(headers(contentType, contentValue))
        .append(CRLF)
        .append(contentValue)
        .append(CRLF);
  }
  expectedStringBuilder.append("--").append(boundaryString).append("--").append(CRLF);
  // write to string
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  content.writeTo(out);
  String expectedContent = expectedStringBuilder.toString();
  assertEquals(expectedContent, out.toString(Charsets.UTF_8.name()));
  assertEquals(StringUtils.getBytesUtf8(expectedContent).length, content.getLength());
}
 
Example 18
Source Project: google-http-java-client   Source File: GZipEncodingTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test() throws IOException {
  GZipEncoding encoding = new GZipEncoding();
  ByteArrayStreamingContent content =
      new ByteArrayStreamingContent(StringUtils.getBytesUtf8("oooooooooooooooooooooooooooo"));
  TestableByteArrayOutputStream out = new TestableByteArrayOutputStream();
  encoding.encode(content, out);
  assertFalse(out.isClosed());
  Assert.assertArrayEquals(EXPECED_ZIPPED, out.getBuffer());
}
 
Example 19
public void test() throws IOException {
  GZipEncoding encoding = new GZipEncoding();
  ByteArrayStreamingContent content =
      new ByteArrayStreamingContent(StringUtils.getBytesUtf8("oooooooooooooooooooooooooooo"));
  TestableByteArrayOutputStream out = new TestableByteArrayOutputStream();
  HttpEncodingStreamingContent encodingContent =
      new HttpEncodingStreamingContent(content, encoding);
  encodingContent.writeTo(out);
  assertFalse(out.isClosed());
  Assert.assertArrayEquals(EXPECED_ZIPPED, out.getBuffer());
}
 
Example 20
public void testExecute_methodUnchanged() throws Exception {
  String body = "Arbitrary body";
  byte[] buf = StringUtils.getBytesUtf8(body);
  for (String method : METHODS) {
    HttpURLConnection connection =
        new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL))
            .setResponseCode(200)
            .setInputStream(new ByteArrayInputStream(buf));
    connection.setRequestMethod(method);
    NetHttpRequest request = new NetHttpRequest(connection);
    setContent(request, "text/html", "");
    request.execute().getContent().close();
    assertEquals(method, connection.getRequestMethod());
  }
}
 
Example 21
public void testSkippingBytes() throws IOException {
  MockHttpURLConnection connection =
      new MockHttpURLConnection(null)
          .setResponseCode(200)
          .setInputStream(new ByteArrayInputStream(StringUtils.getBytesUtf8("0123456789")))
          .addHeader("Content-Length", "10");
  NetHttpResponse response = new NetHttpResponse(connection);
  InputStream is = response.getContent();
  // read 1 byte, then skip 9 (to EOF)
  assertEquals('0', is.read());
  assertEquals(9, is.skip(9));
  // expect EOF, not an exception
  assertEquals(-1, is.read());
}
 
Example 22
Source Project: google-http-java-client   Source File: HttpRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testExecute_curlLoggerWithContentEncoding() throws Exception {
  LogRecordingHandler recorder = new LogRecordingHandler();
  HttpTransport.LOGGER.setLevel(Level.CONFIG);
  HttpTransport.LOGGER.addHandler(recorder);

  String contentValue = "hello";
  byte[] bytes = StringUtils.getBytesUtf8(contentValue);
  InputStreamContent content =
      new InputStreamContent(
          new HttpMediaType("text/plain").setCharsetParameter(Charsets.UTF_8).build(),
          new ByteArrayInputStream(bytes));

  new MockHttpTransport()
      .createRequestFactory()
      .buildPostRequest(new GenericUrl("http://google.com/#q=a'b'c"), content)
      .setEncoding(new GZipEncoding())
      .execute();

  boolean found = false;
  for (String message : recorder.messages()) {
    if (message.startsWith("curl")) {
      found = true;
      assertTrue(message.contains("curl -v --compressed -X POST -H 'Accept-Encoding: gzip'"));
      assertTrue(message.contains("-H 'User-Agent: " + HttpRequest.USER_AGENT_SUFFIX + "'"));
      assertTrue(
          message.contains(
              "-H 'Content-Type: text/plain; charset=UTF-8' -H 'Content-Encoding: gzip'"));
      assertTrue(message.contains("-d '@-' -- 'http://google.com/#q=a'\"'\"'b'\"'\"'c' << $$$"));
    }
  }
  assertTrue(found);
}
 
Example 23
public void subtestGetContentAsString(String expected, String content) throws Exception {
  MockLowLevelHttpRequest request = new MockLowLevelHttpRequest();
  if (content != null) {
    byte[] bytes = StringUtils.getBytesUtf8(content);
    request.setStreamingContent(new ByteArrayStreamingContent(bytes));
  }
  assertEquals(expected, request.getContentAsString());
}
 
Example 24
public void testSetInputStreamAndInputStreamImmutable() throws IOException {
  MockHttpURLConnection connection = new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL));
  connection.setInputStream(new ByteArrayInputStream(StringUtils.getBytesUtf8(RESPONSE_BODY)));
  connection.setInputStream(new ByteArrayInputStream(StringUtils.getBytesUtf8("override")));
  byte[] buf = new byte[10];
  InputStream in = connection.getInputStream();
  int n = 0, bytes = 0;
  while ((n = in.read(buf)) != -1) {
    bytes += n;
  }
  assertEquals(RESPONSE_BODY, new String(buf, 0, bytes));
}
 
Example 25
public final void testGenerateEntry() throws Exception {
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  JsonGenerator generator = newFactory().createJsonGenerator(out, Charsets.UTF_8);
  Entry entry = new Entry();
  entry.title = "foo";
  generator.serialize(entry);
  generator.flush();
  assertEquals(JSON_ENTRY, StringUtils.newStringUtf8(out.toByteArray()));
}
 
Example 26
public final void testGenerateFeed() throws Exception {
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  JsonGenerator generator = newFactory().createJsonGenerator(out, Charsets.UTF_8);
  Feed feed = new Feed();
  Entry entryFoo = new Entry();
  entryFoo.title = "foo";
  Entry entryBar = new Entry();
  entryBar.title = "bar";
  feed.entries = new ArrayList<Entry>();
  feed.entries.add(entryFoo);
  feed.entries.add(entryBar);
  generator.serialize(feed);
  generator.flush();
  assertEquals(JSON_FEED, StringUtils.newStringUtf8(out.toByteArray()));
}
 
Example 27
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);
}
 
Example 28
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 29
/**
 * Forces a refresh of the public certificates downloaded from {@link #getPublicCertsEncodedUrl}.
 *
 * <p>
 * This method is automatically called from {@link #getPublicKeys()} if the public keys have not
 * yet been initialized or if the expiration time is very close, so normally this doesn't need to
 * be called. Only call this method to explicitly force the public keys to be updated.
 * </p>
 */
public GooglePublicKeysManager refresh() throws GeneralSecurityException, IOException {
  lock.lock();
  try {
    publicKeys = new ArrayList<PublicKey>();
    // HTTP request to public endpoint
    CertificateFactory factory = SecurityUtils.getX509CertificateFactory();
    HttpResponse certsResponse = transport.createRequestFactory()
        .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute();
    expirationTimeMilliseconds =
        clock.currentTimeMillis() + getCacheTimeInSec(certsResponse.getHeaders()) * 1000;
    // parse each public key in the JSON response
    JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent());
    JsonToken currentToken = parser.getCurrentToken();
    // token is null at start, so get next token
    if (currentToken == null) {
      currentToken = parser.nextToken();
    }
    Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT);
    try {
      while (parser.nextToken() != JsonToken.END_OBJECT) {
        parser.nextToken();
        String certValue = parser.getText();
        X509Certificate x509Cert = (X509Certificate) factory.generateCertificate(
            new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue)));
        publicKeys.add(x509Cert.getPublicKey());
      }
      publicKeys = Collections.unmodifiableList(publicKeys);
    } finally {
      parser.close();
    }
    return this;
  } finally {
    lock.unlock();
  }
}
 
Example 30
public void testFrom_withDetails() throws Exception {
  HttpTransport transport = new ErrorTransport();
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  GoogleJsonResponseException ge =
      GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
  assertEquals(GoogleJsonErrorTest.ERROR, GoogleJsonErrorTest.FACTORY.toString(ge.getDetails()));
  assertTrue(
      ge.getMessage(), ge.getMessage().startsWith("403" + StringUtils.LINE_SEPARATOR + "{"));
}