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

The following examples show how to use com.google.api.client.util.StringUtils. 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: TestCertificates.java    From google-http-java-client with 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 #2
Source File: NetHttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: NetHttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: HttpRequestTest.java    From google-http-java-client with 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 #5
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: MultipartContentTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: OAuthHmacSigner.java    From google-oauth-java-client with 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 #9
Source File: JsonWebSignature.java    From google-http-java-client with 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 #10
Source File: JsonWebSignature.java    From google-http-java-client with 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 #11
Source File: LenientTokenResponseException.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link LenientTokenResponseException}.
 * <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 readResponse an HTTP response that has already been read
 * @param responseContent the content String of the HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static LenientTokenResponseException from(JsonFactory jsonFactory,
        HttpResponse readResponse, String responseContent) {
    HttpResponseException.Builder builder = new HttpResponseException.Builder(
            readResponse.getStatusCode(), readResponse.getStatusMessage(),
            readResponse.getHeaders());
    // details
    Preconditions.checkNotNull(jsonFactory);
    TokenErrorResponse details = null;
    String detailString = null;
    String contentType = readResponse.getContentType();
    try {
        if (/* !response.isSuccessStatusCode() && */true
                && contentType != null
                && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
            details = readResponse
                    .getRequest()
                    .getParser()
                    .parseAndClose(new StringReader(responseContent), TokenErrorResponse.class);
            detailString = details.toPrettyString();
        } else {
            detailString = responseContent;
        }
    } catch (IOException exception) {
        // it would be bad to throw an exception while throwing an exception
        exception.printStackTrace();
    }
    // message
    StringBuilder message = HttpResponseException.computeMessageBuffer(readResponse);
    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 LenientTokenResponseException(builder, details);
}
 
Example #12
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecuteUnparsed_error() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          assertEquals("GET", method);
          assertEquals("https://www.googleapis.com/test/path/v1/tests/foo", url);
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
          result.setContentType(Json.MEDIA_TYPE);
          result.setContent(ERROR_CONTENT);
          return result;
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  try {
    request.put("testId", "foo");
    request.executeUnparsed();
    fail("expected " + HttpResponseException.class);
  } catch (HttpResponseException e) {
    // expected
    assertEquals("401" + StringUtils.LINE_SEPARATOR + ERROR_CONTENT, e.getMessage());
  }
}
 
Example #13
Source File: OAuthRsaSignerTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testComputeSignature() throws GeneralSecurityException {
  OAuthRsaSigner signer = new OAuthRsaSigner();
  KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
  keyPairGenerator.initialize(1024);
  signer.privateKey = keyPairGenerator.genKeyPair().getPrivate();
  byte[] expected = SecurityUtils.sign(
      SecurityUtils.getSha1WithRsaSignatureAlgorithm(), signer.privateKey,
      StringUtils.getBytesUtf8("foo"));
  assertEquals(Base64.encodeBase64String(expected), signer.computeSignature("foo"));
}
 
Example #14
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 #15
Source File: HttpRequestTest.java    From google-http-java-client with 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 #16
Source File: MockLowLevelHttpRequestTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: MockHttpUrlConnectionTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
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 #20
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);
}
 
Example #21
Source File: CryptoSigners.java    From firebase-admin-java with 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 #22
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 #23
Source File: GooglePublicKeysManager.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #24
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
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 + "{"));
}
 
Example #25
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFrom_detailsArbitraryXmlContent() throws Exception {
  HttpTransport transport = new ErrorTransport("<foo>", "application/atom+xml; charset=utf-8");
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  GoogleJsonResponseException ge =
      GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
  assertNull(ge.getDetails());
  assertTrue(
      ge.getMessage(), ge.getMessage().startsWith("403" + StringUtils.LINE_SEPARATOR + "<"));
}
 
Example #26
Source File: FirebaseTokenFactory.java    From firebase-admin-java with 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 #27
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
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 #28
Source File: HttpEncodingStreamingContentTest.java    From google-http-java-client with 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();
  HttpEncodingStreamingContent encodingContent =
      new HttpEncodingStreamingContent(content, encoding);
  encodingContent.writeTo(out);
  assertFalse(out.isClosed());
  Assert.assertArrayEquals(EXPECED_ZIPPED, out.getBuffer());
}
 
Example #29
Source File: GZipEncodingTest.java    From google-http-java-client with 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 #30
Source File: MultipartContentTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
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());
}