From 0a73a4628b6ec4420db6b9cdbcc68899f3807c5b Mon Sep 17 00:00:00 2001 From: Mike DaCosta Date: Fri, 19 Jun 2020 10:29:31 -0700 Subject: [PATCH] fix: restore the thread's interrupted status after catching InterruptedException (#1005) (#1006) * fix: reset the thread's interrupt bit after catching InterruptedException (#1005) * - Updated code comment to: Mark thread as interrupted since we cannot throw InterruptedException here. - Also setting thread interrupted in HttpBackOffUnsuccessfulResponseHandler. - Added tests for both HttpBackOffIOExceptionHandler and HttpBackOffUnsuccessfulResponseHandler. * Fix bad merge * formatted files with "mvn clean com.coveo:fmt-maven-plugin:format" Co-authored-by: Mike DaCosta --- .../http/apache/v2/ApacheHttpTransport.java | 94 +++++++++---------- .../client/http/apache/v2/ContentEntity.java | 4 +- .../client/http/apache/v2/package-info.java | 2 - .../apache/v2/ApacheHttpTransportTest.java | 56 ++++++----- .../api/client/findbugs/package-info.java | 34 ++++--- .../api/client/json/gson/GsonParserTest.java | 15 ++- .../client/json/jackson2/JacksonFactory.java | 4 +- .../json/jackson2/JacksonParserTest.java | 15 ++- .../test/json/AbstractJsonParserTest.java | 15 ++- .../java/com/google/api/client/xml/Xml.java | 8 +- .../http/HttpBackOffIOExceptionHandler.java | 2 + ...ttpBackOffUnsuccessfulResponseHandler.java | 3 +- .../client/http/HttpIOExceptionHandler.java | 1 + .../google/api/client/http/HttpRequest.java | 3 +- .../google/api/client/http/HttpResponse.java | 10 +- .../api/client/http/MultipartContent.java | 6 +- .../google/api/client/http/UriTemplate.java | 8 +- .../api/client/http/UrlEncodedParser.java | 23 +++-- .../http/apache/ApacheHttpTransport.java | 4 +- .../google/api/client/json/JsonString.java | 4 +- .../api/client/json/webtoken/DerEncoder.java | 6 +- .../json/webtoken/JsonWebSignature.java | 47 ++++++---- .../client/json/webtoken/JsonWebToken.java | 8 +- .../com/google/api/client/util/PemReader.java | 4 +- .../api/client/util/escape/CharEscapers.java | 59 ++++++------ .../client/util/escape/PercentEscaper.java | 46 +++++---- .../util/store/FileDataStoreFactory.java | 54 +++++------ .../client/http/ConsumingInputStreamTest.java | 3 +- .../HttpBackOffIOExpcetionHandlerTest.java | 33 +++++++ ...ackOffUnsuccessfulResponseHandlerTest.java | 34 +++++++ .../api/client/http/HttpRequestTest.java | 3 +- .../client/http/HttpRequestTracingTest.java | 80 +++++++++------- .../api/client/http/HttpResponseTest.java | 22 +++-- .../api/client/http/MultipartContentTest.java | 80 +++++++++------- .../api/client/http/OpenCensusUtilsTest.java | 1 - .../json/webtoken/JsonWebSignatureTest.java | 39 ++++---- .../google/api/client/util/DateTimeTest.java | 8 +- .../api/client/util/GenericDataTest.java | 5 +- .../google/api/client/util/IOUtilsTest.java | 1 - .../util/escape/PercentEscaperTest.java | 5 +- 40 files changed, 465 insertions(+), 384 deletions(-) diff --git a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpTransport.java b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpTransport.java index 864dd072f..02fb98a35 100644 --- a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpTransport.java +++ b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpTransport.java @@ -38,19 +38,15 @@ /** * Thread-safe HTTP transport based on the Apache HTTP Client library. * - *

- * Implementation is thread-safe, as long as any parameter modification to the - * {@link #getHttpClient() Apache HTTP Client} is only done at initialization time. For maximum - * efficiency, applications should use a single globally-shared instance of the HTTP transport. - *

+ *

Implementation is thread-safe, as long as any parameter modification to the {@link + * #getHttpClient() Apache HTTP Client} is only done at initialization time. For maximum efficiency, + * applications should use a single globally-shared instance of the HTTP transport. * - *

- * Default settings are specified in {@link #newDefaultHttpClient()}. Use the - * {@link #ApacheHttpTransport(HttpClient)} constructor to override the Apache HTTP Client used. - * Please read the Default settings are specified in {@link #newDefaultHttpClient()}. Use the {@link + * #ApacheHttpTransport(HttpClient)} constructor to override the Apache HTTP Client used. Please + * read the Apache HTTP * Client connection management tutorial for more complex configuration options. - *

* * @since 1.30 * @author Yaniv Inbar @@ -72,20 +68,18 @@ public ApacheHttpTransport() { /** * Constructor that allows an alternative Apache HTTP client to be used. * - *

- * Note that in the previous version, we overrode several settings. However, we are no longer able - * to do so. - *

+ *

Note that in the previous version, we overrode several settings. However, we are no longer + * able to do so. + * + *

If you choose to provide your own Apache HttpClient implementation, be sure that * - *

If you choose to provide your own Apache HttpClient implementation, be sure that

* * * @param httpClient Apache HTTP client to use - * * @since 1.30 */ public ApacheHttpTransport(HttpClient httpClient) { @@ -93,20 +87,19 @@ public ApacheHttpTransport(HttpClient httpClient) { } /** - * Creates a new instance of the Apache HTTP client that is used by the - * {@link #ApacheHttpTransport()} constructor. + * Creates a new instance of the Apache HTTP client that is used by the {@link + * #ApacheHttpTransport()} constructor. + * + *

Settings: * - *

- * Settings: - *

* * * @return new instance of the Apache HTTP client @@ -117,20 +110,19 @@ public static HttpClient newDefaultHttpClient() { } /** - * Creates a new Apache HTTP client builder that is used by the - * {@link #ApacheHttpTransport()} constructor. + * Creates a new Apache HTTP client builder that is used by the {@link #ApacheHttpTransport()} + * constructor. + * + *

Settings: * - *

- * Settings: - *

* * * @return new instance of the Apache HTTP client @@ -139,14 +131,14 @@ public static HttpClient newDefaultHttpClient() { public static HttpClientBuilder newDefaultHttpClientBuilder() { return HttpClientBuilder.create() - .useSystemProperties() - .setSSLSocketFactory(SSLConnectionSocketFactory.getSocketFactory()) - .setMaxConnTotal(200) - .setMaxConnPerRoute(20) - .setConnectionTimeToLive(-1, TimeUnit.MILLISECONDS) - .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) - .disableRedirectHandling() - .disableAutomaticRetries(); + .useSystemProperties() + .setSSLSocketFactory(SSLConnectionSocketFactory.getSocketFactory()) + .setMaxConnTotal(200) + .setMaxConnPerRoute(20) + .setConnectionTimeToLive(-1, TimeUnit.MILLISECONDS) + .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) + .disableRedirectHandling() + .disableAutomaticRetries(); } @Override diff --git a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ContentEntity.java b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ContentEntity.java index 8fc11e6d8..451b67f2c 100644 --- a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ContentEntity.java +++ b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ContentEntity.java @@ -21,9 +21,7 @@ import java.io.OutputStream; import org.apache.http.entity.AbstractHttpEntity; -/** - * @author Yaniv Inbar - */ +/** @author Yaniv Inbar */ final class ContentEntity extends AbstractHttpEntity { /** Content length or less than zero if not known. */ diff --git a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/package-info.java b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/package-info.java index 1909a2f75..7ca1708ad 100644 --- a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/package-info.java +++ b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/package-info.java @@ -18,6 +18,4 @@ * @since 1.30 * @author Yaniv Inbar */ - package com.google.api.client.http.apache.v2; - diff --git a/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpTransportTest.java b/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpTransportTest.java index e9b93e9be..880e7fdb6 100644 --- a/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpTransportTest.java +++ b/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpTransportTest.java @@ -125,7 +125,8 @@ private void subtestUnsupportedRequestsWithContent(ApacheHttpRequest request, St fail("expected " + IllegalStateException.class); } catch (IllegalStateException e) { // expected - assertEquals(e.getMessage(), + assertEquals( + e.getMessage(), "Apache HTTP client does not support " + method + " requests with content."); } } @@ -141,16 +142,18 @@ private void execute(ApacheHttpRequest request) throws IOException { @Test public void testRequestShouldNotFollowRedirects() throws IOException { final AtomicInteger requestsAttempted = new AtomicInteger(0); - HttpRequestExecutor requestExecutor = new HttpRequestExecutor() { - @Override - public HttpResponse execute(HttpRequest request, HttpClientConnection connection, - HttpContext context) throws IOException, HttpException { - HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 302, null); - response.addHeader("location", "https://google.com/path"); - requestsAttempted.incrementAndGet(); - return response; - } - }; + HttpRequestExecutor requestExecutor = + new HttpRequestExecutor() { + @Override + public HttpResponse execute( + HttpRequest request, HttpClientConnection connection, HttpContext context) + throws IOException, HttpException { + HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 302, null); + response.addHeader("location", "https://google.com/path"); + requestsAttempted.incrementAndGet(); + return response; + } + }; HttpClient client = HttpClients.custom().setRequestExecutor(requestExecutor).build(); ApacheHttpTransport transport = new ApacheHttpTransport(client); ApacheHttpRequest request = transport.buildRequest("GET", "https://google.com"); @@ -162,17 +165,21 @@ public HttpResponse execute(HttpRequest request, HttpClientConnection connection @Test public void testRequestCanSetHeaders() { final AtomicBoolean interceptorCalled = new AtomicBoolean(false); - HttpClient client = HttpClients.custom().addInterceptorFirst(new HttpRequestInterceptor() { - @Override - public void process(HttpRequest request, HttpContext context) - throws HttpException, IOException { - Header header = request.getFirstHeader("foo"); - assertNotNull("Should have found header", header); - assertEquals("bar", header.getValue()); - interceptorCalled.set(true); - throw new IOException("cancelling request"); - } - }).build(); + HttpClient client = + HttpClients.custom() + .addInterceptorFirst( + new HttpRequestInterceptor() { + @Override + public void process(HttpRequest request, HttpContext context) + throws HttpException, IOException { + Header header = request.getFirstHeader("foo"); + assertNotNull("Should have found header", header); + assertEquals("bar", header.getValue()); + interceptorCalled.set(true); + throw new IOException("cancelling request"); + } + }) + .build(); ApacheHttpTransport transport = new ApacheHttpTransport(client); ApacheHttpRequest request = transport.buildRequest("GET", "https://google.com"); @@ -224,10 +231,7 @@ public void handle(HttpExchange httpExchange) throws IOException { GenericUrl testUrl = new GenericUrl("http://localhost/foo//bar"); testUrl.setPort(server.getAddress().getPort()); com.google.api.client.http.HttpResponse response = - transport - .createRequestFactory() - .buildGetRequest(testUrl) - .execute(); + transport.createRequestFactory().buildGetRequest(testUrl).execute(); assertEquals(200, response.getStatusCode()); assertEquals("/foo//bar", response.parseAsString()); } diff --git a/google-http-client-findbugs/src/main/java/com/google/api/client/findbugs/package-info.java b/google-http-client-findbugs/src/main/java/com/google/api/client/findbugs/package-info.java index c22541fb6..83168807c 100644 --- a/google-http-client-findbugs/src/main/java/com/google/api/client/findbugs/package-info.java +++ b/google-http-client-findbugs/src/main/java/com/google/api/client/findbugs/package-info.java @@ -15,28 +15,26 @@ /** * Findbugs package which supports custom Google APIs Client library findbugs Plugins. * - * Usage on pom.xml: + *

Usage on pom.xml: * *

-  <plugin>
-    <groupId>org.codehaus.mojo</groupId>
-    <artifactId>findbugs-maven-plugin</artifactId>
-    ...
-    <configuration>
-      <plugins>
-        <plugin>
-          <groupId>com.google.http-client</groupId>
-          <artifactId>google-http-client-findbugs</artifactId>
-          <version>${project.http.version}</version>
-        </plugin>
-       </plugins>
-    </configuration>
-    ...
-  </plugin>
+ * <plugin>
+ * <groupId>org.codehaus.mojo</groupId>
+ * <artifactId>findbugs-maven-plugin</artifactId>
+ * ...
+ * <configuration>
+ * <plugins>
+ * <plugin>
+ * <groupId>com.google.http-client</groupId>
+ * <artifactId>google-http-client-findbugs</artifactId>
+ * <version>${project.http.version}</version>
+ * </plugin>
+ * </plugins>
+ * </configuration>
+ * ...
+ * </plugin>
  * 
* * @author Eyal Peled */ - package com.google.api.client.findbugs; - diff --git a/google-http-client-gson/src/test/java/com/google/api/client/json/gson/GsonParserTest.java b/google-http-client-gson/src/test/java/com/google/api/client/json/gson/GsonParserTest.java index f79d4a5d6..aa5ed5aea 100644 --- a/google-http-client-gson/src/test/java/com/google/api/client/json/gson/GsonParserTest.java +++ b/google-http-client-gson/src/test/java/com/google/api/client/json/gson/GsonParserTest.java @@ -1,19 +1,16 @@ /** * Copyright 2019 Google LLC * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + *

https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ - package com.google.api.client.json.gson; import com.google.api.client.json.JsonFactory; diff --git a/google-http-client-jackson2/src/main/java/com/google/api/client/json/jackson2/JacksonFactory.java b/google-http-client-jackson2/src/main/java/com/google/api/client/json/jackson2/JacksonFactory.java index 8028d63c6..dba08c363 100644 --- a/google-http-client-jackson2/src/main/java/com/google/api/client/json/jackson2/JacksonFactory.java +++ b/google-http-client-jackson2/src/main/java/com/google/api/client/json/jackson2/JacksonFactory.java @@ -29,8 +29,8 @@ /** * Low-level JSON library implementation based on Jackson 2. * - *

Implementation is thread-safe. For maximum efficiency, - * applications should use a single globally-shared instance of the JSON factory. + *

Implementation is thread-safe. For maximum efficiency, applications should use a single + * globally-shared instance of the JSON factory. * * @since 1.11 * @author Yaniv Inbar diff --git a/google-http-client-jackson2/src/test/java/com/google/api/client/json/jackson2/JacksonParserTest.java b/google-http-client-jackson2/src/test/java/com/google/api/client/json/jackson2/JacksonParserTest.java index 92da03605..ed185c7ab 100644 --- a/google-http-client-jackson2/src/test/java/com/google/api/client/json/jackson2/JacksonParserTest.java +++ b/google-http-client-jackson2/src/test/java/com/google/api/client/json/jackson2/JacksonParserTest.java @@ -1,19 +1,16 @@ /** * Copyright 2019 Google LLC * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + *

https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ - package com.google.api.client.json.jackson2; import com.google.api.client.json.JsonFactory; diff --git a/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonParserTest.java b/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonParserTest.java index ef641e868..2a68c639c 100644 --- a/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonParserTest.java +++ b/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonParserTest.java @@ -1,19 +1,16 @@ /** * Copyright 2019 Google LLC * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + *

https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ - package com.google.api.client.test.json; import com.google.api.client.json.GenericJson; diff --git a/google-http-client-xml/src/main/java/com/google/api/client/xml/Xml.java b/google-http-client-xml/src/main/java/com/google/api/client/xml/Xml.java index 4f9156d3c..1aa5a343b 100644 --- a/google-http-client-xml/src/main/java/com/google/api/client/xml/Xml.java +++ b/google-http-client-xml/src/main/java/com/google/api/client/xml/Xml.java @@ -195,10 +195,10 @@ public boolean stopAfterEndTag(String namespace, String localName) { /** * Parses an XML element using the given XML pull parser into the given destination object. * - *

Requires the current event be {@link XmlPullParser#START_TAG} (skipping any initial - * {@link XmlPullParser#START_DOCUMENT}) of the element being parsed. At normal parsing - * completion, the current event will either be {@link XmlPullParser#END_TAG} of the element being - * parsed, or the {@link XmlPullParser#START_TAG} of the requested {@code atom:entry}. + *

Requires the current event be {@link XmlPullParser#START_TAG} (skipping any initial {@link + * XmlPullParser#START_DOCUMENT}) of the element being parsed. At normal parsing completion, the + * current event will either be {@link XmlPullParser#END_TAG} of the element being parsed, or the + * {@link XmlPullParser#START_TAG} of the requested {@code atom:entry}. * * @param parser XML pull parser * @param destination optional destination object to parser into or {@code null} to ignore XML diff --git a/google-http-client/src/main/java/com/google/api/client/http/HttpBackOffIOExceptionHandler.java b/google-http-client/src/main/java/com/google/api/client/http/HttpBackOffIOExceptionHandler.java index 253cc613e..a0874841f 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/HttpBackOffIOExceptionHandler.java +++ b/google-http-client/src/main/java/com/google/api/client/http/HttpBackOffIOExceptionHandler.java @@ -97,6 +97,8 @@ public boolean handleIOException(HttpRequest request, boolean supportsRetry) thr try { return BackOffUtils.next(sleeper, backOff); } catch (InterruptedException exception) { + // Mark thread as interrupted since we cannot throw InterruptedException here. + Thread.currentThread().interrupt(); return false; } } diff --git a/google-http-client/src/main/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandler.java b/google-http-client/src/main/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandler.java index 5e1ae2cc6..cc44c6136 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandler.java +++ b/google-http-client/src/main/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandler.java @@ -128,7 +128,8 @@ public boolean handleResponse(HttpRequest request, HttpResponse response, boolea try { return BackOffUtils.next(sleeper, backOff); } catch (InterruptedException exception) { - // ignore + // Mark thread as interrupted since we cannot throw InterruptedException here. + Thread.currentThread().interrupt(); } } return false; diff --git a/google-http-client/src/main/java/com/google/api/client/http/HttpIOExceptionHandler.java b/google-http-client/src/main/java/com/google/api/client/http/HttpIOExceptionHandler.java index f37cfef5e..0b0b877d0 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/HttpIOExceptionHandler.java +++ b/google-http-client/src/main/java/com/google/api/client/http/HttpIOExceptionHandler.java @@ -35,6 +35,7 @@ * try { * return BackOffUtils.next(sleeper, backOff); * } catch (InterruptedException exception) { + * Thread.currentThread().interrupt(); * return false; * } * } diff --git a/google-http-client/src/main/java/com/google/api/client/http/HttpRequest.java b/google-http-client/src/main/java/com/google/api/client/http/HttpRequest.java index 9124e4906..a521c5397 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/HttpRequest.java +++ b/google-http-client/src/main/java/com/google/api/client/http/HttpRequest.java @@ -1223,7 +1223,8 @@ private static String getVersion() { // attempt to read the library's version from a properties file generated during the build // this value should be read and cached for later use String version = "unknown-version"; - try (InputStream inputStream = HttpRequest.class.getResourceAsStream("/google-http-client.properties")) { + try (InputStream inputStream = + HttpRequest.class.getResourceAsStream("/google-http-client.properties")) { if (inputStream != null) { final Properties properties = new Properties(); properties.load(inputStream); diff --git a/google-http-client/src/main/java/com/google/api/client/http/HttpResponse.java b/google-http-client/src/main/java/com/google/api/client/http/HttpResponse.java index 276ce0e74..2df92d4c4 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/HttpResponse.java +++ b/google-http-client/src/main/java/com/google/api/client/http/HttpResponse.java @@ -159,8 +159,8 @@ public final class HttpResponse { } /** - * Returns an {@link HttpMediaType} object parsed from {@link #contentType}, or {@code null} if - * if {@link #contentType} cannot be parsed or {@link #contentType} is {@code null}. + * Returns an {@link HttpMediaType} object parsed from {@link #contentType}, or {@code null} if if + * {@link #contentType} cannot be parsed or {@link #contentType} is {@code null}. */ private static HttpMediaType parseMediaType(String contentType) { if (contentType == null) { @@ -352,12 +352,14 @@ public InputStream getContent() throws IOException { // gzip encoding (wrap content with GZipInputStream) if (!returnRawInputStream && this.contentEncoding != null) { String oontentencoding = this.contentEncoding.trim().toLowerCase(Locale.ENGLISH); - if (CONTENT_ENCODING_GZIP.equals(oontentencoding) || CONTENT_ENCODING_XGZIP.equals(oontentencoding)) { + if (CONTENT_ENCODING_GZIP.equals(oontentencoding) + || CONTENT_ENCODING_XGZIP.equals(oontentencoding)) { // Wrap the original stream in a ConsumingInputStream before passing it to // GZIPInputStream. The GZIPInputStream leaves content unconsumed in the original // stream (it almost always leaves the last chunk unconsumed in chunked responses). // ConsumingInputStream ensures that any unconsumed bytes are read at close. - // GZIPInputStream.close() --> ConsumingInputStream.close() --> exhaust(ConsumingInputStream) + // GZIPInputStream.close() --> ConsumingInputStream.close() --> + // exhaust(ConsumingInputStream) lowLevelResponseContent = new GZIPInputStream(new ConsumingInputStream(lowLevelResponseContent)); } diff --git a/google-http-client/src/main/java/com/google/api/client/http/MultipartContent.java b/google-http-client/src/main/java/com/google/api/client/http/MultipartContent.java index 43a58b446..35a59cf6f 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/MultipartContent.java +++ b/google-http-client/src/main/java/com/google/api/client/http/MultipartContent.java @@ -32,9 +32,9 @@ * and RFC 2046: Multipurpose Internet * Mail Extensions: The Multipart/mixed (primary) subtype. * - *

By default the media type is {@code "multipart/related; boundary=__END_OF_PART____"}, but this - * may be customized by calling {@link #setMediaType(HttpMediaType)}, {@link #getMediaType()}, or - * {@link #setBoundary(String)}. + *

By default the media type is {@code "multipart/related; boundary=__END_OF_PART____"}, but this may be customized by calling {@link #setMediaType(HttpMediaType)}, {@link + * #getMediaType()}, or {@link #setBoundary(String)}. * *

Implementation is not thread-safe. * diff --git a/google-http-client/src/main/java/com/google/api/client/http/UriTemplate.java b/google-http-client/src/main/java/com/google/api/client/http/UriTemplate.java index 61071db68..6a1e2e23c 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/UriTemplate.java +++ b/google-http-client/src/main/java/com/google/api/client/http/UriTemplate.java @@ -104,8 +104,8 @@ private enum CompositeOutput { * @param explodeJoiner the delimiter used to join composite values. * @param requiresVarAssignment denotes whether or not the expanded template should contain an * assignment with the variable - * @param reservedExpansion reserved expansion allows percent-encoded triplets and characters in the - * reserved set + * @param reservedExpansion reserved expansion allows percent-encoded triplets and characters in + * the reserved set */ CompositeOutput( Character propertyPrefix, @@ -149,8 +149,8 @@ int getVarNameStartIndex() { } /** - * Encodes the specified value. If reserved expansion is turned on, then percent-encoded triplets and - * characters are allowed in the reserved set. + * Encodes the specified value. If reserved expansion is turned on, then percent-encoded + * triplets and characters are allowed in the reserved set. * * @param value the string to be encoded * @return the encoded string diff --git a/google-http-client/src/main/java/com/google/api/client/http/UrlEncodedParser.java b/google-http-client/src/main/java/com/google/api/client/http/UrlEncodedParser.java index 14c3238f7..6c432e672 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/UrlEncodedParser.java +++ b/google-http-client/src/main/java/com/google/api/client/http/UrlEncodedParser.java @@ -124,10 +124,10 @@ public static void parse(String content, Object data, boolean decodeEnabled) { * @param data data key name/value pairs * @since 1.14 */ - public static void parse(Reader reader, Object data) throws IOException { - parse(reader, data, true); - } - + public static void parse(Reader reader, Object data) throws IOException { + parse(reader, data, true); + } + /** * Parses the given URL-encoded content into the given data object of data key name/value pairs, * including support for repeating data key names. @@ -139,10 +139,9 @@ public static void parse(Reader reader, Object data) throws IOException { * They are parsed the same as "primitive" fields, except that the generic type parameter of the * collection is used as the {@link Class} parameter. * - *

If there is no declared field for an input parameter name, it is ignored unless the - * input {@code data} parameter is a {@link Map}. If it is a map, the parameter value is - * stored either as a string, or as a {@link ArrayList}<String> in the case of repeated - * parameters. + *

If there is no declared field for an input parameter name, it is ignored unless the input + * {@code data} parameter is a {@link Map}. If it is a map, the parameter value is stored either + * as a string, or as a {@link ArrayList}<String> in the case of repeated parameters. * * @param reader URL-encoded reader * @param data data key name/value pairs @@ -168,9 +167,13 @@ public static void parse(Reader reader, Object data, boolean decodeEnabled) thro // falls through case '&': // parse name/value pair - String name = decodeEnabled ? CharEscapers.decodeUri(nameWriter.toString()) : nameWriter.toString(); + String name = + decodeEnabled ? CharEscapers.decodeUri(nameWriter.toString()) : nameWriter.toString(); if (name.length() != 0) { - String stringValue = decodeEnabled ? CharEscapers.decodeUri(valueWriter.toString()) : valueWriter.toString(); + String stringValue = + decodeEnabled + ? CharEscapers.decodeUri(valueWriter.toString()) + : valueWriter.toString(); // get the field from the type information FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo != null) { diff --git a/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpTransport.java b/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpTransport.java index ce5e59d51..890bdf2f2 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpTransport.java +++ b/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpTransport.java @@ -74,8 +74,8 @@ * * @since 1.0 * @author Yaniv Inbar - * @deprecated Please use com.google.api.client.http.apache.v2.ApacheHttpTransport provided by - * the com.google.http-client:google-http-client-apache-v2 artifact. + * @deprecated Please use com.google.api.client.http.apache.v2.ApacheHttpTransport provided by the + * com.google.http-client:google-http-client-apache-v2 artifact. */ @Deprecated public final class ApacheHttpTransport extends HttpTransport { diff --git a/google-http-client/src/main/java/com/google/api/client/json/JsonString.java b/google-http-client/src/main/java/com/google/api/client/json/JsonString.java index 68b3b2f9c..2d0a2ba70 100644 --- a/google-http-client/src/main/java/com/google/api/client/json/JsonString.java +++ b/google-http-client/src/main/java/com/google/api/client/json/JsonString.java @@ -40,8 +40,8 @@ * * * - *

However, if instead the JSON content uses a JSON String to store the value, one needs to use the - * {@link JsonString} annotation. For example: + *

However, if instead the JSON content uses a JSON String to store the value, one needs to use + * the {@link JsonString} annotation. For example: * *

  * 
diff --git a/google-http-client/src/main/java/com/google/api/client/json/webtoken/DerEncoder.java b/google-http-client/src/main/java/com/google/api/client/json/webtoken/DerEncoder.java
index ce7c42f12..7d3b465b4 100644
--- a/google-http-client/src/main/java/com/google/api/client/json/webtoken/DerEncoder.java
+++ b/google-http-client/src/main/java/com/google/api/client/json/webtoken/DerEncoder.java
@@ -17,16 +17,14 @@
 package com.google.api.client.json.webtoken;
 
 import com.google.api.client.util.Preconditions;
-
 import java.math.BigInteger;
 import java.util.Arrays;
 
 /**
  * Utilities for re-encoding a signature byte array with DER encoding.
  *
- * 

Note: that this is not a general purpose encoder and currently only - * handles 512 bit signatures. ES256 verification algorithms expect the - * signature bytes in DER encoding. + *

Note: that this is not a general purpose encoder and currently only handles 512 bit + * signatures. ES256 verification algorithms expect the signature bytes in DER encoding. */ public class DerEncoder { private static byte DER_TAG_SIGNATURE_OBJECT = 0x30; diff --git a/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebSignature.java b/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebSignature.java index aa21dbe2e..4886b7927 100644 --- a/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebSignature.java +++ b/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebSignature.java @@ -23,14 +23,12 @@ import com.google.api.client.util.StringUtils; import java.io.ByteArrayInputStream; import java.io.IOException; -import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; -import java.security.Signature; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; @@ -78,8 +76,7 @@ public JsonWebSignature( } /** - * Header as specified in - * Reserved + * Header as specified in Reserved * Header Parameter Names. */ public static class Header extends JsonWebToken.Header { @@ -305,8 +302,8 @@ public Header setX509Certificates(List x509Certificates) { } /** - * Returns an array listing the header parameter names that define extensions used in - * the JWS header that MUST be understood and processed or {@code null} for none. + * Returns an array listing the header parameter names that define extensions used in the JWS + * header that MUST be understood and processed or {@code null} for none. * * @since 1.16 */ @@ -318,8 +315,8 @@ public final List getCritical() { } /** - * Sets the header parameter names that define extensions used in the - * JWS header that MUST be understood and processed or {@code null} for none. + * Sets the header parameter names that define extensions used in the JWS header that MUST be + * understood and processed or {@code null} for none. * *

Overriding is only supported for the purpose of calling the super implementation and * changing the return type, but nothing else. @@ -350,8 +347,8 @@ public Header getHeader() { /** * Verifies the signature of the content. * - *

Currently only {@code "RS256"} and {@code "ES256"} algorithms are verified, but others may be added in the - * future. For any other algorithm it returns {@code false}. + *

Currently only {@code "RS256"} and {@code "ES256"} algorithms are verified, but others may + * be added in the future. For any other algorithm it returns {@code false}. * * @param publicKey public key * @return whether the algorithm is recognized and it is verified @@ -360,9 +357,17 @@ public Header getHeader() { public final boolean verifySignature(PublicKey publicKey) throws GeneralSecurityException { String algorithm = getHeader().getAlgorithm(); if ("RS256".equals(algorithm)) { - return SecurityUtils.verify(SecurityUtils.getSha256WithRsaSignatureAlgorithm(), publicKey, signatureBytes, signedContentBytes); + return SecurityUtils.verify( + SecurityUtils.getSha256WithRsaSignatureAlgorithm(), + publicKey, + signatureBytes, + signedContentBytes); } else if ("ES256".equals(algorithm)) { - return SecurityUtils.verify(SecurityUtils.getEs256SignatureAlgorithm(), publicKey, DerEncoder.encode(signatureBytes), signedContentBytes); + return SecurityUtils.verify( + SecurityUtils.getEs256SignatureAlgorithm(), + publicKey, + DerEncoder.encode(signatureBytes), + signedContentBytes); } else { return false; } @@ -372,8 +377,8 @@ public final boolean verifySignature(PublicKey publicKey) throws GeneralSecurity * {@link Beta}
* Verifies the signature of the content using the certificate chain embedded in the signature. * - *

Currently only {@code "RS256"} and {@code "ES256"} algorithms are verified, but others may be added in the - * future. For any other algorithm it returns {@code null}. + *

Currently only {@code "RS256"} and {@code "ES256"} algorithms are verified, but others may + * be added in the future. For any other algorithm it returns {@code null}. * *

The leaf certificate of the certificate chain must be an SSL server certificate. * @@ -392,9 +397,19 @@ public final X509Certificate verifySignature(X509TrustManager trustManager) } String algorithm = getHeader().getAlgorithm(); if ("RS256".equals(algorithm)) { - return SecurityUtils.verify(SecurityUtils.getSha256WithRsaSignatureAlgorithm(), trustManager, x509Certificates, signatureBytes, signedContentBytes); + return SecurityUtils.verify( + SecurityUtils.getSha256WithRsaSignatureAlgorithm(), + trustManager, + x509Certificates, + signatureBytes, + signedContentBytes); } else if ("ES256".equals(algorithm)) { - return SecurityUtils.verify(SecurityUtils.getEs256SignatureAlgorithm(), trustManager, x509Certificates, DerEncoder.encode(signatureBytes), signedContentBytes); + return SecurityUtils.verify( + SecurityUtils.getEs256SignatureAlgorithm(), + trustManager, + x509Certificates, + DerEncoder.encode(signatureBytes), + signedContentBytes); } else { return null; } diff --git a/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebToken.java b/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebToken.java index f68450190..bfcf63fe9 100644 --- a/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebToken.java +++ b/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebToken.java @@ -47,8 +47,7 @@ public JsonWebToken(Header header, Payload payload) { } /** - * Header as specified in - * JWT Header. + * Header as specified in JWT Header. */ public static class Header extends GenericJson { @@ -115,9 +114,8 @@ public Header clone() { } /** - * Payload as specified in - * Reserved Claim - * Names. + * Payload as specified in Reserved + * Claim Names. */ public static class Payload extends GenericJson { diff --git a/google-http-client/src/main/java/com/google/api/client/util/PemReader.java b/google-http-client/src/main/java/com/google/api/client/util/PemReader.java index 607d80de0..a1f06a3bc 100644 --- a/google-http-client/src/main/java/com/google/api/client/util/PemReader.java +++ b/google-http-client/src/main/java/com/google/api/client/util/PemReader.java @@ -36,7 +36,9 @@ * *

Limitations: * - *

    + *

    + * + *

      *
    • Assumes the PEM file section content is not encrypted and cannot handle the case of any * headers inside the BEGIN and END tag. *
    • It also ignores any attributes associated with any PEM file section. diff --git a/google-http-client/src/main/java/com/google/api/client/util/escape/CharEscapers.java b/google-http-client/src/main/java/com/google/api/client/util/escape/CharEscapers.java index 9d61f8af0..4350f2711 100644 --- a/google-http-client/src/main/java/com/google/api/client/util/escape/CharEscapers.java +++ b/google-http-client/src/main/java/com/google/api/client/util/escape/CharEscapers.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2010 Google Inc. +* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ +* +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software distributed under the License +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +* or implied. See the License for the specific language governing permissions and limitations under +* the License. +*/ package com.google.api.client.util.escape; @@ -46,12 +46,11 @@ public final class CharEscapers { /** * Escapes the string value so it can be safely included in application/x-www-form-urlencoded - * data. This is not appropriate for generic URI escaping. In particular it encodes - * the space character as a plus sign instead of percent escaping it, in - * contravention of the URI specification. - * For details on application/x-www-form-urlencoded encoding see the - * see HTML 4 - * specification, section 17.13.4.1. + * data. This is not appropriate for generic URI escaping. In particular it encodes the space + * character as a plus sign instead of percent escaping it, in contravention of the URI + * specification. For details on application/x-www-form-urlencoded encoding see the see HTML 4 specification, + * section 17.13.4.1. * *

      When encoding a String, the following rules apply: * @@ -80,11 +79,11 @@ public final class CharEscapers { public static String escapeUri(String value) { return APPLICATION_X_WWW_FORM_URLENCODED.escape(value); } - - /** - * Escapes the string value so it can be safely included in any part of a URI. - * For details on escaping URIs, - * see RFC 3986 - section 2.4. + + /** + * Escapes the string value so it can be safely included in any part of a URI. For details on + * escaping URIs, see RFC 3986 - section + * 2.4. * *

      When encoding a String, the following rules apply: * @@ -108,11 +107,11 @@ public static String escapeUriConformant(String value) { } /** - * Decodes application/x-www-form-urlencoded strings. The UTF-8 character set determines - * what characters are represented by any consecutive sequences of the form "%XX". + * Decodes application/x-www-form-urlencoded strings. The UTF-8 character set determines what + * characters are represented by any consecutive sequences of the form "%XX". * - *

      This replaces each occurrence of '+' with a space, ' '. This method should not be used - * for non-application/x-www-form-urlencoded strings such as host and path. + *

      This replaces each occurrence of '+' with a space, ' '. This method should not be used for + * non-application/x-www-form-urlencoded strings such as host and path. * * @param uri a percent-encoded US-ASCII string * @return a string without any percent escapes or plus signs @@ -127,9 +126,9 @@ public static String decodeUri(String uri) { } /** - * Decodes the path component of a URI. This does not - * convert + into spaces (the behavior of {@link java.net.URLDecoder#decode(String, String)}). This - * method transforms URI encoded values into their decoded symbols. + * Decodes the path component of a URI. This does not convert + into spaces (the behavior of + * {@link java.net.URLDecoder#decode(String, String)}). This method transforms URI encoded values + * into their decoded symbols. * *

      e.g. {@code decodePath("%3Co%3E")} returns {@code ""} * diff --git a/google-http-client/src/main/java/com/google/api/client/util/escape/PercentEscaper.java b/google-http-client/src/main/java/com/google/api/client/util/escape/PercentEscaper.java index 84f635cdc..3866265a3 100644 --- a/google-http-client/src/main/java/com/google/api/client/util/escape/PercentEscaper.java +++ b/google-http-client/src/main/java/com/google/api/client/util/escape/PercentEscaper.java @@ -16,8 +16,7 @@ /** * A {@code UnicodeEscaper} that escapes some set of Java characters using the URI percent encoding - * scheme. The set of safe characters (those which remain unescaped) is specified on - * construction. + * scheme. The set of safe characters (those which remain unescaped) is specified on construction. * *

      For details on escaping URIs for use in web pages, see RFC 3986 - section 2.4 and The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the * same. *

    • Any additionally specified safe characters remain the same. - *
    • If {@code plusForSpace} is true, the space character " " is converted into a plus - * sign "+". - *
    • All other characters are converted into one or more bytes using UTF-8 encoding. Each - * byte is then represented by the 3-character string "%XY", where "XY" is the two-digit, + *
    • If {@code plusForSpace} is true, the space character " " is converted into a plus sign "+". + *
    • All other characters are converted into one or more bytes using UTF-8 encoding. Each byte + * is then represented by the 3-character string "%XY", where "XY" is the two-digit, * uppercase, hexadecimal representation of the byte value. *
    * - *

    RFC 3986 defines the set of unreserved characters as "-", "_", "~", and "." - * It goes on to state: + *

    RFC 3986 defines the set of unreserved characters as "-", "_", "~", and "." It goes on to + * state: * - *

    URIs that differ in the replacement of an unreserved character with - its corresponding percent-encoded US-ASCII octet are equivalent: they - identify the same resource. However, URI comparison implementations - do not always perform normalization prior to comparison (see Section - 6). For consistency, percent-encoded octets in the ranges of ALPHA - (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period (%2E), - underscore (%5F), or tilde (%7E) should not be created by URI - producers and, when found in a URI, should be decoded to their - corresponding unreserved characters by URI normalizers. + *

    URIs that differ in the replacement of an unreserved character with its corresponding + * percent-encoded US-ASCII octet are equivalent: they identify the same resource. However, URI + * comparison implementations do not always perform normalization prior to comparison (see Section + * 6). For consistency, percent-encoded octets in the ranges of ALPHA (%41-%5A and %61-%7A), DIGIT + * (%30-%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should not be created by + * URI producers and, when found in a URI, should be decoded to their corresponding unreserved + * characters by URI normalizers. * *

    Note: This escaper produces uppercase hexadecimal sequences. From RFC 3986:
    @@ -103,10 +99,10 @@ public class PercentEscaper extends UnicodeEscaper { * escaped. */ private final boolean[] safeOctets; - + /** - * Constructs a URI escaper with the specified safe characters. The space - * character is escaped to %20 in accordance with the URI specification. + * Constructs a URI escaper with the specified safe characters. The space character is escaped to + * %20 in accordance with the URI specification. * * @param safeChars a non null string specifying additional safe characters for this escaper (the * ranges 0..9, a..z and A..Z are always safe and should not be specified here) @@ -117,9 +113,9 @@ public PercentEscaper(String safeChars) { } /** - * Constructs a URI escaper that converts all but the specified safe characters - * into hexadecimal percent escapes. Optionally space characters can be converted into - * a plus sign {@code +} instead of {@code %20}. and optional handling of the space + * Constructs a URI escaper that converts all but the specified safe characters into hexadecimal + * percent escapes. Optionally space characters can be converted into a plus sign {@code +} + * instead of {@code %20}. and optional handling of the space * * @param safeChars a non null string specifying additional safe characters for this escaper. The * ranges 0..9, a..z and A..Z are always safe and should not be specified here. @@ -127,8 +123,8 @@ public PercentEscaper(String safeChars) { * @throws IllegalArgumentException if safeChars includes characters that are always safe or * characters that must always be escaped * @deprecated use {@code PercentEscaper(String safeChars)} instead which is the same as invoking - * this method with plusForSpace set to false. Escaping spaces as plus signs does not - * conform to the URI specification. + * this method with plusForSpace set to false. Escaping spaces as plus signs does not conform + * to the URI specification. */ @Deprecated public PercentEscaper(String safeChars, boolean plusForSpace) { diff --git a/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java b/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java index 838dcb5dd..a39356ff5 100644 --- a/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java +++ b/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java @@ -16,7 +16,6 @@ import com.google.api.client.util.IOUtils; import com.google.api.client.util.Maps; - import com.google.common.base.StandardSystemProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -43,8 +42,8 @@ /** * Thread-safe file implementation of a credential store. * - *

    For security purposes, the file's permissions are set such that the - * file is only accessible by the file's owner. + *

    For security purposes, the file's permissions are set such that the file is only accessible by + * the file's owner. * * @since 1.16 * @author Yaniv Inbar @@ -53,8 +52,8 @@ public class FileDataStoreFactory extends AbstractDataStoreFactory { private static final Logger LOGGER = Logger.getLogger(FileDataStoreFactory.class.getName()); - private static final boolean IS_WINDOWS = StandardSystemProperty.OS_NAME.value() - .toLowerCase(Locale.ENGLISH).startsWith("windows"); + private static final boolean IS_WINDOWS = + StandardSystemProperty.OS_NAME.value().toLowerCase(Locale.ENGLISH).startsWith("windows"); /** Directory to store data. */ private final File dataDirectory; @@ -151,35 +150,37 @@ private static void setPermissionsToOwnerOnly(File file) throws IOException { private static void setPermissionsToOwnerOnlyWindows(File file) throws IOException { Path path = Paths.get(file.getAbsolutePath()); - FileOwnerAttributeView fileAttributeView = Files.getFileAttributeView(path, FileOwnerAttributeView.class); + FileOwnerAttributeView fileAttributeView = + Files.getFileAttributeView(path, FileOwnerAttributeView.class); UserPrincipal owner = fileAttributeView.getOwner(); // get view AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class); // All available entries - Set permissions = ImmutableSet.of( - AclEntryPermission.APPEND_DATA, - AclEntryPermission.DELETE, - AclEntryPermission.DELETE_CHILD, - AclEntryPermission.READ_ACL, - AclEntryPermission.READ_ATTRIBUTES, - AclEntryPermission.READ_DATA, - AclEntryPermission.READ_NAMED_ATTRS, - AclEntryPermission.SYNCHRONIZE, - AclEntryPermission.WRITE_ACL, - AclEntryPermission.WRITE_ATTRIBUTES, - AclEntryPermission.WRITE_DATA, - AclEntryPermission.WRITE_NAMED_ATTRS, - AclEntryPermission.WRITE_OWNER - ); + Set permissions = + ImmutableSet.of( + AclEntryPermission.APPEND_DATA, + AclEntryPermission.DELETE, + AclEntryPermission.DELETE_CHILD, + AclEntryPermission.READ_ACL, + AclEntryPermission.READ_ATTRIBUTES, + AclEntryPermission.READ_DATA, + AclEntryPermission.READ_NAMED_ATTRS, + AclEntryPermission.SYNCHRONIZE, + AclEntryPermission.WRITE_ACL, + AclEntryPermission.WRITE_ATTRIBUTES, + AclEntryPermission.WRITE_DATA, + AclEntryPermission.WRITE_NAMED_ATTRS, + AclEntryPermission.WRITE_OWNER); // create ACL to give owner everything - AclEntry entry = AclEntry.newBuilder() - .setType(AclEntryType.ALLOW) - .setPrincipal(owner) - .setPermissions(permissions) - .build(); + AclEntry entry = + AclEntry.newBuilder() + .setType(AclEntryType.ALLOW) + .setPrincipal(owner) + .setPermissions(permissions) + .build(); // Overwrite the ACL with only this permission try { @@ -187,6 +188,5 @@ private static void setPermissionsToOwnerOnlyWindows(File file) throws IOExcepti } catch (SecurityException ex) { throw new IOException("Unable to set permissions for " + file, ex); } - } } diff --git a/google-http-client/src/test/java/com/google/api/client/http/ConsumingInputStreamTest.java b/google-http-client/src/test/java/com/google/api/client/http/ConsumingInputStreamTest.java index 33a48dce1..afcdf2bf5 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/ConsumingInputStreamTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/ConsumingInputStreamTest.java @@ -27,7 +27,8 @@ public class ConsumingInputStreamTest { @Test public void testClose_drainsBytesOnClose() throws IOException { - MockInputStream mockInputStream = new MockInputStream("abc123".getBytes(StandardCharsets.UTF_8)); + MockInputStream mockInputStream = + new MockInputStream("abc123".getBytes(StandardCharsets.UTF_8)); InputStream consumingInputStream = new ConsumingInputStream(mockInputStream); assertEquals(6, mockInputStream.getBytesToRead()); diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffIOExpcetionHandlerTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffIOExpcetionHandlerTest.java index db4fcdc54..ae0ae125f 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffIOExpcetionHandlerTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffIOExpcetionHandlerTest.java @@ -17,7 +17,9 @@ import com.google.api.client.testing.util.MockBackOff; import com.google.api.client.testing.util.MockSleeper; import com.google.api.client.util.BackOff; +import com.google.api.client.util.Sleeper; import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; import junit.framework.TestCase; /** @@ -46,4 +48,35 @@ public void subsetHandle(long count, long millis, boolean retrySupported, BackOf } assertEquals(count, sleeper.getCount()); } + + public void testHandleIOException_returnsFalseAndThreadRemainsInterrupted_whenSleepIsInterrupted() + throws Exception { + final AtomicBoolean stillInterrupted = new AtomicBoolean(false); + Thread runningThread = + new Thread() { + @Override + public void run() { + HttpBackOffIOExceptionHandler testTarget = + new HttpBackOffIOExceptionHandler( + new MockBackOff() + .setBackOffMillis(Long.MAX_VALUE) // Sleep until we interrupt it. + .setMaxTries(1)) + .setSleeper( + Sleeper.DEFAULT); // Needs to be a real sleeper so we can interrupt it. + + try { + testTarget.handleIOException(null, /* retrySupported= */ true); + } catch (Exception ignored) { + } + stillInterrupted.set(Thread.currentThread().isInterrupted()); + } + }; + runningThread.start(); + // Give runningThread some time to start. + Thread.sleep(500L); + runningThread.interrupt(); + runningThread.join(); + + assertTrue(stillInterrupted.get()); + } } diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandlerTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandlerTest.java index 7393ae318..afe9ff65d 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandlerTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandlerTest.java @@ -18,7 +18,9 @@ import com.google.api.client.testing.util.MockBackOff; import com.google.api.client.testing.util.MockSleeper; import com.google.api.client.util.BackOff; +import com.google.api.client.util.Sleeper; import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; import junit.framework.TestCase; /** @@ -67,4 +69,36 @@ private void subsetHandleResponse( } assertEquals(count, sleeper.getCount()); } + + public void testHandleResponse_returnsFalseAndThreadRemainsInterrupted_whenSleepIsInterrupted() + throws Exception { + final AtomicBoolean stillInterrupted = new AtomicBoolean(false); + Thread runningThread = + new Thread() { + @Override + public void run() { + HttpBackOffUnsuccessfulResponseHandler testTarget = + new HttpBackOffUnsuccessfulResponseHandler( + new MockBackOff() + .setBackOffMillis(Long.MAX_VALUE) // Sleep until we interrupt it. + .setMaxTries(1)) + .setSleeper( + Sleeper.DEFAULT) // Needs to be a real sleeper so we can interrupt it. + .setBackOffRequired(BackOffRequired.ALWAYS); + + try { + testTarget.handleResponse(null, null, /* retrySupported= */ true); + } catch (Exception ignored) { + } + stillInterrupted.set(Thread.currentThread().isInterrupted()); + } + }; + runningThread.start(); + // Give runningThread some time to start. + Thread.sleep(500L); + runningThread.interrupt(); + runningThread.join(); + + assertTrue(stillInterrupted.get()); + } } diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java index bb47e98d7..d78cd8c89 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java @@ -1275,7 +1275,6 @@ public void testVersion_matchesAcceptablePatterns() throws Exception { String version = HttpRequest.VERSION; assertTrue( String.format("the loaded version '%s' did not match the acceptable pattern", version), - version.matches(acceptableVersionPattern) - ); + version.matches(acceptableVersionPattern)); } } diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java index 5d89f0350..d2d2df5d1 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java @@ -13,6 +13,12 @@ */ package com.google.api.client.http; +import static com.google.api.client.http.OpenCensusUtils.SPAN_NAME_HTTP_REQUEST_EXECUTE; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; @@ -25,19 +31,12 @@ import io.opencensus.trace.config.TraceParams; import io.opencensus.trace.export.SpanData; import io.opencensus.trace.samplers.Samplers; +import java.io.IOException; +import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.io.IOException; -import java.util.List; - -import static com.google.api.client.http.OpenCensusUtils.SPAN_NAME_HTTP_REQUEST_EXECUTE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - public class HttpRequestTracingTest { private static final TestHandler testHandler = new TestHandler(); @@ -60,13 +59,12 @@ public void teardownTestTracer() { @Test(timeout = 20_000L) public void executeCreatesSpan() throws IOException { - MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse() - .setStatusCode(200); - HttpTransport transport = new MockHttpTransport.Builder() - .setLowLevelHttpResponse(mockResponse) - .build(); - HttpRequest request = new HttpRequestFactory(transport, null) - .buildGetRequest(new GenericUrl("https://google.com/")); + MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse().setStatusCode(200); + HttpTransport transport = + new MockHttpTransport.Builder().setLowLevelHttpResponse(mockResponse).build(); + HttpRequest request = + new HttpRequestFactory(transport, null) + .buildGetRequest(new GenericUrl("https://google.com/")); request.execute(); // This call blocks - we set a timeout on this test to ensure we don't wait forever @@ -88,8 +86,11 @@ public void executeCreatesSpan() throws IOException { // Ensure we have 2 message events, SENT and RECEIVED assertEquals(2, span.getMessageEvents().getEvents().size()); - assertEquals(MessageEvent.Type.SENT, span.getMessageEvents().getEvents().get(0).getEvent().getType()); - assertEquals(MessageEvent.Type.RECEIVED, span.getMessageEvents().getEvents().get(1).getEvent().getType()); + assertEquals( + MessageEvent.Type.SENT, span.getMessageEvents().getEvents().get(0).getEvent().getType()); + assertEquals( + MessageEvent.Type.RECEIVED, + span.getMessageEvents().getEvents().get(1).getEvent().getType()); // Ensure we record the span status as OK assertEquals(Status.OK, span.getStatus()); @@ -97,16 +98,19 @@ public void executeCreatesSpan() throws IOException { @Test(timeout = 20_000L) public void executeExceptionCreatesSpan() throws IOException { - HttpTransport transport = new MockHttpTransport.Builder() - .setLowLevelHttpRequest(new MockLowLevelHttpRequest() { - @Override - public LowLevelHttpResponse execute() throws IOException { - throw new IOException("some IOException"); - } - }) - .build(); - HttpRequest request = new HttpRequestFactory(transport, null) - .buildGetRequest(new GenericUrl("https://google.com/")); + HttpTransport transport = + new MockHttpTransport.Builder() + .setLowLevelHttpRequest( + new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + throw new IOException("some IOException"); + } + }) + .build(); + HttpRequest request = + new HttpRequestFactory(transport, null) + .buildGetRequest(new GenericUrl("https://google.com/")); try { request.execute(); @@ -133,21 +137,25 @@ public LowLevelHttpResponse execute() throws IOException { // Ensure we have 2 message events, SENT and RECEIVED assertEquals(1, span.getMessageEvents().getEvents().size()); - assertEquals(MessageEvent.Type.SENT, span.getMessageEvents().getEvents().get(0).getEvent().getType()); + assertEquals( + MessageEvent.Type.SENT, span.getMessageEvents().getEvents().get(0).getEvent().getType()); // Ensure we record the span status as UNKNOWN - assertEquals(Status.UNKNOWN, span.getStatus()); } + assertEquals(Status.UNKNOWN, span.getStatus()); + } void assertAttributeEquals(SpanData span, String attributeName, String expectedValue) { Object attributeValue = span.getAttributes().getAttributeMap().get(attributeName); assertNotNull("expected span to contain attribute: " + attributeName, attributeValue); assertTrue(attributeValue instanceof AttributeValue); - String value = ((AttributeValue) attributeValue).match( - Functions.returnToString(), - Functions.returnToString(), - Functions.returnToString(), - Functions.returnToString(), - Functions.returnNull()); + String value = + ((AttributeValue) attributeValue) + .match( + Functions.returnToString(), + Functions.returnToString(), + Functions.returnToString(), + Functions.returnToString(), + Functions.returnNull()); assertEquals(expectedValue, value); } } diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpResponseTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpResponseTest.java index 57b400e40..267d13caa 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpResponseTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpResponseTest.java @@ -544,11 +544,14 @@ public void testGetContent_gzipEncoding_finishReading() throws IOException { do_testGetContent_gzipEncoding_finishReading("gzip"); } - public void testGetContent_gzipEncoding_finishReadingWithUppercaseContentEncoding() throws IOException { + public void testGetContent_gzipEncoding_finishReadingWithUppercaseContentEncoding() + throws IOException { do_testGetContent_gzipEncoding_finishReading("GZIP"); } - public void testGetContent_gzipEncoding_finishReadingWithDifferentDefaultLocaleAndUppercaseContentEncoding() throws IOException { + public void + testGetContent_gzipEncoding_finishReadingWithDifferentDefaultLocaleAndUppercaseContentEncoding() + throws IOException { Locale originalDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.forLanguageTag("tr-TR")); @@ -558,13 +561,12 @@ public void testGetContent_gzipEncoding_finishReadingWithDifferentDefaultLocaleA } } - private void do_testGetContent_gzipEncoding_finishReading(String contentEncoding) throws IOException { + private void do_testGetContent_gzipEncoding_finishReading(String contentEncoding) + throws IOException { byte[] dataToCompress = "abcd".getBytes(StandardCharsets.UTF_8); byte[] mockBytes; - try ( - ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length); - GZIPOutputStream zipStream = new GZIPOutputStream((byteStream)) - ) { + try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length); + GZIPOutputStream zipStream = new GZIPOutputStream((byteStream))) { zipStream.write(dataToCompress); zipStream.close(); @@ -596,7 +598,8 @@ public LowLevelHttpResponse execute() throws IOException { HttpRequest request = transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL); HttpResponse response = request.execute(); - try (TestableByteArrayInputStream output = (TestableByteArrayInputStream) mockResponse.getContent()) { + try (TestableByteArrayInputStream output = + (TestableByteArrayInputStream) mockResponse.getContent()) { assertFalse(output.isClosed()); assertEquals("abcd", response.parseAsString()); assertTrue(output.isClosed()); @@ -624,7 +627,8 @@ public LowLevelHttpResponse execute() throws IOException { }; } }; - HttpRequest request = transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL); + HttpRequest request = + transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL); // If gzip was used on this response, an exception would be thrown HttpResponse response = request.execute(); assertEquals("abcd", response.parseAsString()); diff --git a/google-http-client/src/test/java/com/google/api/client/http/MultipartContentTest.java b/google-http-client/src/test/java/com/google/api/client/http/MultipartContentTest.java index 14e0e5990..ed3ec5e53 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/MultipartContentTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/MultipartContentTest.java @@ -33,9 +33,14 @@ public class MultipartContentTest extends TestCase { private static final String HEADERS = headers("application/json; charset=UTF-8", "foo"); private static String headers(String contentType, String value) { - return "Content-Length: " + value.length() + CRLF - + "Content-Type: " + contentType + CRLF - + "content-transfer-encoding: binary" + CRLF; + return "Content-Length: " + + value.length() + + CRLF + + "Content-Type: " + + contentType + + CRLF + + "content-transfer-encoding: binary" + + CRLF; } public void testRandomContent() throws Exception { @@ -46,19 +51,26 @@ public void testRandomContent() throws Exception { assertTrue(boundaryString.endsWith("__")); assertEquals("multipart/related; boundary=" + boundaryString, content.getType()); - final String[][] VALUES = new String[][] { - {"Hello world", "text/plain"}, - {"Hi", "application/xml"}, - {"{x:1,y:2}", "application/json"} - }; + final String[][] VALUES = + new String[][] { + {"Hello world", "text/plain"}, + {"Hi", "application/xml"}, + {"{x:1,y:2}", "application/json"} + }; StringBuilder expectedStringBuilder = new StringBuilder(); - for (String[] valueTypePair: VALUES) { + 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); + 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 @@ -72,31 +84,30 @@ public void testRandomContent() throws Exception { public void testContent() throws Exception { subtestContent("--" + BOUNDARY + "--" + CRLF, null); subtestContent( - "--" + BOUNDARY + CRLF - + HEADERS + CRLF - + "foo" + CRLF - + "--" + BOUNDARY + "--" + CRLF, - null, + "--" + BOUNDARY + CRLF + HEADERS + CRLF + "foo" + CRLF + "--" + BOUNDARY + "--" + CRLF, + null, "foo"); subtestContent( - "--" + BOUNDARY + CRLF - + HEADERS + CRLF - + "foo" + CRLF - + "--" + BOUNDARY + CRLF - + HEADERS + CRLF - + "bar" + CRLF - + "--" + BOUNDARY + "--" + CRLF, - null, + "--" + BOUNDARY + CRLF + HEADERS + CRLF + "foo" + CRLF + "--" + BOUNDARY + CRLF + HEADERS + + CRLF + "bar" + CRLF + "--" + BOUNDARY + "--" + CRLF, + null, "foo", "bar"); subtestContent( - "--myboundary" + CRLF - + HEADERS + CRLF - + "foo" + CRLF - + "--myboundary" + CRLF - + HEADERS + CRLF - + "bar" + CRLF - + "--myboundary--" + CRLF, + "--myboundary" + + CRLF + + HEADERS + + CRLF + + "foo" + + CRLF + + "--myboundary" + + CRLF + + HEADERS + + CRLF + + "bar" + + CRLF + + "--myboundary--" + + CRLF, "myboundary", "foo", "bar"); @@ -105,7 +116,8 @@ public void testContent() throws Exception { private void subtestContent(String expectedContent, String boundaryString, String... contents) throws Exception { // multipart content - MultipartContent content = new MultipartContent(boundaryString == null ? BOUNDARY : boundaryString); + MultipartContent content = + new MultipartContent(boundaryString == null ? BOUNDARY : boundaryString); for (String contentValue : contents) { content.addPart( new MultipartContent.Part(ByteArrayContent.fromString(CONTENT_TYPE, contentValue))); diff --git a/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java b/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java index 8fa8624eb..480d10150 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java @@ -14,7 +14,6 @@ package com.google.api.client.http; - import io.opencensus.trace.Annotation; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.BlankSpan; diff --git a/google-http-client/src/test/java/com/google/api/client/json/webtoken/JsonWebSignatureTest.java b/google-http-client/src/test/java/com/google/api/client/json/webtoken/JsonWebSignatureTest.java index 9a02c0750..78fb06def 100644 --- a/google-http-client/src/test/java/com/google/api/client/json/webtoken/JsonWebSignatureTest.java +++ b/google-http-client/src/test/java/com/google/api/client/json/webtoken/JsonWebSignatureTest.java @@ -17,7 +17,8 @@ import com.google.api.client.testing.json.MockJsonFactory; import com.google.api.client.testing.json.webtoken.TestCertificates; import com.google.api.client.testing.util.SecurityTestUtils; - +import com.google.api.client.util.Base64; +import com.google.api.client.util.StringUtils; import java.io.IOException; import java.math.BigInteger; import java.security.AlgorithmParameters; @@ -35,11 +36,7 @@ import java.security.spec.InvalidParameterSpecException; import java.util.ArrayList; import java.util.List; - import javax.net.ssl.X509TrustManager; - -import com.google.api.client.util.Base64; -import com.google.api.client.util.StringUtils; import org.junit.Assert; import org.junit.Test; @@ -69,12 +66,12 @@ public void testSign() throws Exception { } private X509Certificate verifyX509WithCaCert(TestCertificates.CertData caCert) - throws IOException, GeneralSecurityException { + throws IOException, GeneralSecurityException { JsonWebSignature signature = TestCertificates.getJsonWebSignature(); X509TrustManager trustManager = caCert.getTrustManager(); return signature.verifySignature(trustManager); } - + @Test public void testImmutableSignatureBytes() throws IOException { JsonWebSignature signature = TestCertificates.getJsonWebSignature(); @@ -83,7 +80,7 @@ public void testImmutableSignatureBytes() throws IOException { byte[] bytes2 = signature.getSignatureBytes(); Assert.assertNotEquals(bytes2[0], bytes[0]); } - + @Test public void testImmutableSignedContentBytes() throws IOException { JsonWebSignature signature = TestCertificates.getJsonWebSignature(); @@ -92,7 +89,7 @@ public void testImmutableSignedContentBytes() throws IOException { byte[] bytes2 = signature.getSignedContentBytes(); Assert.assertNotEquals(bytes2[0], bytes[0]); } - + @Test public void testImmutableCertificates() throws IOException { JsonWebSignature signature = TestCertificates.getJsonWebSignature(); @@ -100,7 +97,7 @@ public void testImmutableCertificates() throws IOException { certificates.set(0, "foo"); Assert.assertNotEquals("foo", signature.getHeader().getX509Certificates().get(0)); } - + @Test public void testImmutableCritical() throws IOException { JsonWebSignature signature = TestCertificates.getJsonWebSignature(); @@ -128,8 +125,10 @@ public void testVerifyX509WrongCa() throws Exception { Assert.assertNull(verifyX509WithCaCert(TestCertificates.BOGUS_CA_CERT)); } - private static final String ES256_CONTENT = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Im1wZjBEQSJ9.eyJhdWQiOiIvcHJvamVjdHMvNjUyNTYyNzc2Nzk4L2FwcHMvY2xvdWQtc2FtcGxlcy10ZXN0cy1waHAtaWFwIiwiZW1haWwiOiJjaGluZ29yQGdvb2dsZS5jb20iLCJleHAiOjE1ODQwNDc2MTcsImdvb2dsZSI6eyJhY2Nlc3NfbGV2ZWxzIjpbImFjY2Vzc1BvbGljaWVzLzUxODU1MTI4MDkyNC9hY2Nlc3NMZXZlbHMvcmVjZW50U2VjdXJlQ29ubmVjdERhdGEiLCJhY2Nlc3NQb2xpY2llcy81MTg1NTEyODA5MjQvYWNjZXNzTGV2ZWxzL3Rlc3ROb09wIiwiYWNjZXNzUG9saWNpZXMvNTE4NTUxMjgwOTI0L2FjY2Vzc0xldmVscy9ldmFwb3JhdGlvblFhRGF0YUZ1bGx5VHJ1c3RlZCJdfSwiaGQiOiJnb29nbGUuY29tIiwiaWF0IjoxNTg0MDQ3MDE3LCJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwic3ViIjoiYWNjb3VudHMuZ29vZ2xlLmNvbToxMTIxODE3MTI3NzEyMDE5NzI4OTEifQ"; - private static final String ES256_SIGNATURE = "yKNtdFY5EKkRboYNexBdfugzLhC3VuGyFcuFYA8kgpxMqfyxa41zkML68hYKrWu2kOBTUW95UnbGpsIi_u1fiA"; + private static final String ES256_CONTENT = + "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Im1wZjBEQSJ9.eyJhdWQiOiIvcHJvamVjdHMvNjUyNTYyNzc2Nzk4L2FwcHMvY2xvdWQtc2FtcGxlcy10ZXN0cy1waHAtaWFwIiwiZW1haWwiOiJjaGluZ29yQGdvb2dsZS5jb20iLCJleHAiOjE1ODQwNDc2MTcsImdvb2dsZSI6eyJhY2Nlc3NfbGV2ZWxzIjpbImFjY2Vzc1BvbGljaWVzLzUxODU1MTI4MDkyNC9hY2Nlc3NMZXZlbHMvcmVjZW50U2VjdXJlQ29ubmVjdERhdGEiLCJhY2Nlc3NQb2xpY2llcy81MTg1NTEyODA5MjQvYWNjZXNzTGV2ZWxzL3Rlc3ROb09wIiwiYWNjZXNzUG9saWNpZXMvNTE4NTUxMjgwOTI0L2FjY2Vzc0xldmVscy9ldmFwb3JhdGlvblFhRGF0YUZ1bGx5VHJ1c3RlZCJdfSwiaGQiOiJnb29nbGUuY29tIiwiaWF0IjoxNTg0MDQ3MDE3LCJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwic3ViIjoiYWNjb3VudHMuZ29vZ2xlLmNvbToxMTIxODE3MTI3NzEyMDE5NzI4OTEifQ"; + private static final String ES256_SIGNATURE = + "yKNtdFY5EKkRboYNexBdfugzLhC3VuGyFcuFYA8kgpxMqfyxa41zkML68hYKrWu2kOBTUW95UnbGpsIi_u1fiA"; // x, y values for keyId "mpf0DA" from https://www.gstatic.com/iap/verify/public_key-jwk private static final String GOOGLE_ES256_X = "fHEdeT3a6KaC1kbwov73ZwB_SiUHEyKQwUUtMCEn0aI"; @@ -139,13 +138,12 @@ private PublicKey buildEs256PublicKey(String x, String y) throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidKeySpecException { AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC"); parameters.init(new ECGenParameterSpec("secp256r1")); - ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec( - new ECPoint( - new BigInteger(1, Base64.decodeBase64(x)), - new BigInteger(1, Base64.decodeBase64(y)) - ), - parameters.getParameterSpec(ECParameterSpec.class) - ); + ECPublicKeySpec ecPublicKeySpec = + new ECPublicKeySpec( + new ECPoint( + new BigInteger(1, Base64.decodeBase64(x)), + new BigInteger(1, Base64.decodeBase64(y))), + parameters.getParameterSpec(ECParameterSpec.class)); KeyFactory keyFactory = KeyFactory.getInstance("EC"); return keyFactory.generatePublic(ecPublicKeySpec); } @@ -158,7 +156,8 @@ public void testVerifyES256() throws Exception { 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); + JsonWebSignature jsonWebSignature = + new JsonWebSignature(header, payload, signatureBytes, signedContentBytes); Assert.assertTrue(jsonWebSignature.verifySignature(publicKey)); } } diff --git a/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java b/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java index 785ab40d5..ce7d2b027 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java @@ -224,15 +224,13 @@ public void testParseRfc3339ToSecondsAndNanos() { assertParsedRfc3339( "2018-03-01T10:11:12.1000Z", SecondsAndNanos.ofSecondsAndNanos(1519899072L, 100000000)); } - + public void testEpoch() { - assertParsedRfc3339( - "1970-01-01T00:00:00.000Z", SecondsAndNanos.ofSecondsAndNanos(0, 0)); + assertParsedRfc3339("1970-01-01T00:00:00.000Z", SecondsAndNanos.ofSecondsAndNanos(0, 0)); } public void testOneSecondBeforeEpoch() { - assertParsedRfc3339( - "1969-12-31T23:59:59.000Z", SecondsAndNanos.ofSecondsAndNanos(-1, 0)); + assertParsedRfc3339("1969-12-31T23:59:59.000Z", SecondsAndNanos.ofSecondsAndNanos(-1, 0)); } private static void assertParsedRfc3339(String input, SecondsAndNanos expected) { diff --git a/google-http-client/src/test/java/com/google/api/client/util/GenericDataTest.java b/google-http-client/src/test/java/com/google/api/client/util/GenericDataTest.java index c1d3872c0..52b2b9a0a 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/GenericDataTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/GenericDataTest.java @@ -15,13 +15,10 @@ package com.google.api.client.util; import com.google.api.client.util.GenericData.Flags; - -import junit.framework.TestCase; - import java.util.ArrayList; import java.util.EnumSet; import java.util.List; - +import junit.framework.TestCase; import org.junit.Assert; /** diff --git a/google-http-client/src/test/java/com/google/api/client/util/IOUtilsTest.java b/google-http-client/src/test/java/com/google/api/client/util/IOUtilsTest.java index 4d3503544..42166ae5d 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/IOUtilsTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/IOUtilsTest.java @@ -53,4 +53,3 @@ public void testIsSymbolicLink_true() throws IOException { assertTrue(IOUtils.isSymbolicLink(file2)); } } - diff --git a/google-http-client/src/test/java/com/google/api/client/util/escape/PercentEscaperTest.java b/google-http-client/src/test/java/com/google/api/client/util/escape/PercentEscaperTest.java index 6b3e75085..fa8aeba9d 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/escape/PercentEscaperTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/escape/PercentEscaperTest.java @@ -26,11 +26,10 @@ public void testEscapeSpace() { String actual = escaper.escape("Hello there"); Assert.assertEquals("Hello%20there", actual); } - + @Test public void testEscapeSpaceDefault() { - PercentEscaper escaper = - new PercentEscaper(PercentEscaper.SAFE_PLUS_RESERVED_CHARS_URLENCODER); + PercentEscaper escaper = new PercentEscaper(PercentEscaper.SAFE_PLUS_RESERVED_CHARS_URLENCODER); String actual = escaper.escape("Hello there"); Assert.assertEquals("Hello%20there", actual); }