From 74556be57c9ab091843341018f51432f836d6b7d Mon Sep 17 00:00:00 2001 From: Cody Oss Date: Tue, 10 Dec 2019 10:36:58 -0700 Subject: [PATCH 1/5] feat: support chunked transfer encoding Currently any time HttpRequest works with encoded data it encodes the data twice. Once for the actaul stream and once for checking the length of the stream. Instead, when there is encoding just don't set the content length. This will cause the underlying transports, with a few tweaks, to use Transfer-Encoding: chunked. Fixes #648 --- .../http/apache/v2/ApacheHttpRequest.java | 24 ++--- .../http/apache/v2/ApacheHttpTransport.java | 94 +++++++++---------- .../client/http/apache/v2/ContentEntity.java | 4 +- .../client/http/apache/v2/package-info.java | 2 - .../http/apache/v2/ApacheHttpRequestTest.java | 45 +++++++++ .../apache/v2/ApacheHttpTransportTest.java | 57 +++++------ .../api/client/findbugs/package-info.java | 34 ++++--- .../api/client/json/gson/GsonParserTest.java | 15 ++- .../json/jackson2/JacksonParserTest.java | 15 ++- .../test/json/AbstractJsonParserTest.java | 15 ++- .../java/com/google/api/client/xml/Xml.java | 8 +- .../google/api/client/http/GenericUrl.java | 47 ++++++---- .../google/api/client/http/HttpRequest.java | 19 ++-- .../google/api/client/http/HttpResponse.java | 3 +- .../api/client/http/UrlEncodedParser.java | 27 +++--- .../client/http/apache/ApacheHttpRequest.java | 10 +- .../http/apache/ApacheHttpTransport.java | 4 +- .../client/http/javanet/NetHttpRequest.java | 5 + .../json/webtoken/JsonWebSignature.java | 11 +-- .../client/json/webtoken/JsonWebToken.java | 8 +- .../http/javanet/MockHttpURLConnection.java | 4 + .../util/store/FileDataStoreFactory.java | 56 +++++------ .../client/http/ConsumingInputStreamTest.java | 4 +- .../api/client/http/HttpRequestTest.java | 17 ++-- .../client/http/HttpRequestTracingTest.java | 80 +++++++++------- .../api/client/http/HttpResponseTest.java | 22 +++-- .../api/client/http/OpenCensusUtilsTest.java | 1 - .../http/javanet/NetHttpRequestTest.java | 36 ++++++- .../json/webtoken/JsonWebSignatureTest.java | 13 +-- .../google/api/client/util/DateTimeTest.java | 8 +- .../api/client/util/GenericDataTest.java | 5 +- .../google/api/client/util/IOUtilsTest.java | 1 - 32 files changed, 387 insertions(+), 307 deletions(-) create mode 100644 google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpRequestTest.java diff --git a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpRequest.java b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpRequest.java index 29bd61ee7..7743bf4b5 100644 --- a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpRequest.java +++ b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpRequest.java @@ -23,9 +23,7 @@ import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpRequestBase; -/** - * @author Yaniv Inbar - */ +/** @author Yaniv Inbar */ final class ApacheHttpRequest extends LowLevelHttpRequest { private final HttpClient httpClient; @@ -38,11 +36,12 @@ final class ApacheHttpRequest extends LowLevelHttpRequest { this.httpClient = httpClient; this.request = request; // disable redirects as google-http-client handles redirects - this.requestConfig = RequestConfig.custom() - .setRedirectsEnabled(false) - .setNormalizeUri(false) - // TODO(chingor): configure in HttpClientBuilder when available - .setStaleConnectionCheckEnabled(false); + this.requestConfig = + RequestConfig.custom() + .setRedirectsEnabled(false) + .setNormalizeUri(false) + // TODO(chingor): configure in HttpClientBuilder when available + .setStaleConnectionCheckEnabled(false); } @Override @@ -52,19 +51,22 @@ public void addHeader(String name, String value) { @Override public void setTimeout(int connectTimeout, int readTimeout) throws IOException { - requestConfig.setConnectTimeout(connectTimeout) - .setSocketTimeout(readTimeout); + requestConfig.setConnectTimeout(connectTimeout).setSocketTimeout(readTimeout); } @Override public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { - Preconditions.checkArgument(request instanceof HttpEntityEnclosingRequest, + Preconditions.checkArgument( + request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); + if (getContentLength() == -1) { + entity.setChunked(true); + } ((HttpEntityEnclosingRequest) request).setEntity(entity); } request.setConfig(requestConfig.build()); 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/ApacheHttpRequestTest.java b/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpRequestTest.java new file mode 100644 index 000000000..61e78182a --- /dev/null +++ b/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpRequestTest.java @@ -0,0 +1,45 @@ +package com.google.api.client.http.apache.v2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.google.api.client.http.ByteArrayContent; +import com.google.api.client.http.HttpContent; +import com.google.api.client.http.InputStreamContent; +import com.google.api.client.testing.http.apache.MockHttpClient; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import org.junit.Test; + +public class ApacheHttpRequestTest { + + @Test + public void testContentLengthSet() throws Exception { + HttpExtensionMethod base = new HttpExtensionMethod("POST", "http://www.google.com"); + ApacheHttpRequest request = new ApacheHttpRequest(new MockHttpClient(), base); + HttpContent content = + new ByteArrayContent("text/plain", "sample".getBytes(StandardCharsets.UTF_8)); + request.setStreamingContent(content); + request.setContentLength(content.getLength()); + request.execute(); + + assertFalse(base.getEntity().isChunked()); + assertEquals(6, base.getEntity().getContentLength()); + } + + @Test + public void testChunked() throws Exception { + byte[] buf = new byte[300]; + Arrays.fill(buf, (byte) ' '); + HttpExtensionMethod base = new HttpExtensionMethod("POST", "http://www.google.com"); + ApacheHttpRequest request = new ApacheHttpRequest(new MockHttpClient(), base); + HttpContent content = new InputStreamContent("text/plain", new ByteArrayInputStream(buf)); + request.setStreamingContent(content); + request.execute(); + + assertTrue(base.getEntity().isChunked()); + assertEquals(-1, base.getEntity().getContentLength()); + } +} 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 e6ca850ce..b336f3016 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 @@ -34,7 +34,6 @@ import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; -import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.http.Header; @@ -126,7 +125,8 @@ private void subtestUnsupportedRequestsWithContent(ApacheHttpRequest request, St fail("expected " + IllegalArgumentException.class); } catch (IllegalArgumentException e) { // expected - assertEquals(e.getMessage(), + assertEquals( + e.getMessage(), "Apache HTTP client does not support " + method + " requests with content."); } } @@ -142,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"); @@ -163,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"); @@ -225,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/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/GenericUrl.java b/google-http-client/src/main/java/com/google/api/client/http/GenericUrl.java index 68c5ea6c3..efd9bfedb 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/GenericUrl.java +++ b/google-http-client/src/main/java/com/google/api/client/http/GenericUrl.java @@ -81,10 +81,10 @@ public class GenericUrl extends GenericData { private String fragment; /** - * If true, the URL string originally given is used as is (without encoding, decoding and - * escaping) whenever referenced; otherwise, part of the URL string may be encoded or decoded as - * deemed appropriate or necessary. - */ + * If true, the URL string originally given is used as is (without encoding, decoding and + * escaping) whenever referenced; otherwise, part of the URL string may be encoded or decoded as + * deemed appropriate or necessary. + */ private boolean verbatim; public GenericUrl() {} @@ -112,20 +112,20 @@ public GenericUrl(String encodedUrl) { /** * Constructs from an encoded URL. * - *

Any known query parameters with pre-defined fields as data keys are parsed based on - * their data type. Any unrecognized query parameter are always parsed as a string. + *

Any known query parameters with pre-defined fields as data keys are parsed based on their + * data type. Any unrecognized query parameter are always parsed as a string. * *

Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}. * * @param encodedUrl encoded URL, including any existing query parameters that should be parsed - * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and escaping) + * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and + * escaping) * @throws IllegalArgumentException if URL has a syntax error */ public GenericUrl(String encodedUrl, boolean verbatim) { this(parseURL(encodedUrl), verbatim); } - /** * Constructs from a URI. * @@ -140,7 +140,8 @@ public GenericUrl(URI uri) { * Constructs from a URI. * * @param uri URI - * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and escaping) + * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and + * escaping) */ public GenericUrl(URI uri, boolean verbatim) { this( @@ -168,7 +169,8 @@ public GenericUrl(URL url) { * Constructs from a URL. * * @param url URL - * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and escaping) + * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and + * escaping) * @since 1.14 */ public GenericUrl(URL url, boolean verbatim) { @@ -209,7 +211,7 @@ private GenericUrl( UrlEncodedParser.parse(query, this); } this.userInfo = userInfo != null ? CharEscapers.decodeUri(userInfo) : null; - } + } } @Override @@ -567,10 +569,11 @@ public static List toPathParts(String encodedPath) { * * @param encodedPath slash-prefixed encoded path, for example {@code * "/m8/feeds/contacts/default/full"} - * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and escaping) - * @return path parts (decoded if not {@code verbatim}), with each part assumed to be preceded by a {@code '/'}, for example - * {@code "", "m8", "feeds", "contacts", "default", "full"}, or {@code null} for {@code null} - * or {@code ""} input + * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and + * escaping) + * @return path parts (decoded if not {@code verbatim}), with each part assumed to be preceded by + * a {@code '/'}, for example {@code "", "m8", "feeds", "contacts", "default", "full"}, or + * {@code null} for {@code null} or {@code ""} input */ public static List toPathParts(String encodedPath, boolean verbatim) { if (encodedPath == null || encodedPath.length() == 0) { @@ -608,13 +611,17 @@ private void appendRawPathFromParts(StringBuilder buf) { } /** Adds query parameters from the provided entrySet into the buffer. */ - static void addQueryParams(Set> entrySet, StringBuilder buf, boolean verbatim) { + static void addQueryParams( + Set> entrySet, StringBuilder buf, boolean verbatim) { // (similar to UrlEncodedContent) boolean first = true; for (Map.Entry nameValueEntry : entrySet) { Object value = nameValueEntry.getValue(); if (value != null) { - String name = verbatim ? nameValueEntry.getKey() : CharEscapers.escapeUriQuery(nameValueEntry.getKey()); + String name = + verbatim + ? nameValueEntry.getKey() + : CharEscapers.escapeUriQuery(nameValueEntry.getKey()); if (value instanceof Collection) { Collection collectionValue = (Collection) value; for (Object repeatedValue : collectionValue) { @@ -627,7 +634,8 @@ static void addQueryParams(Set> entrySet, StringBuilder bu } } - private static boolean appendParam(boolean first, StringBuilder buf, String name, Object value, boolean verbatim) { + private static boolean appendParam( + boolean first, StringBuilder buf, String name, Object value, boolean verbatim) { if (first) { first = false; buf.append('?'); @@ -635,7 +643,8 @@ private static boolean appendParam(boolean first, StringBuilder buf, String name buf.append('&'); } buf.append(name); - String stringValue = verbatim ? value.toString() : CharEscapers.escapeUriQuery(value.toString()); + String stringValue = + verbatim ? value.toString() : CharEscapers.escapeUriQuery(value.toString()); if (stringValue.length() != 0) { buf.append('=').append(stringValue); } 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 a2c01d425..4e47e0c74 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 @@ -15,7 +15,6 @@ package com.google.api.client.http; import com.google.api.client.util.Beta; -import com.google.api.client.util.IOUtils; import com.google.api.client.util.LoggingStreamingContent; import com.google.api.client.util.ObjectParser; import com.google.api.client.util.Preconditions; @@ -141,7 +140,7 @@ public final class HttpRequest { /** HTTP request URL. */ private GenericUrl url; - + /** Timeout in milliseconds to establish a connection or {@code 0} for an infinite timeout. */ private int connectTimeout = 20 * 1000; @@ -172,7 +171,7 @@ public final class HttpRequest { /** The {@link BackOffPolicy} to use between retry attempts or {@code null} for none. */ @Deprecated @Beta private BackOffPolicy backOffPolicy; - /** Whether to automatically follow redirects ({@code true} by default). */ + /** Whether to automatically follow redirects ({@code true} by default). */ private boolean followRedirects = true; /** Whether to use raw redirect URLs ({@code false} by default). */ @@ -698,15 +697,13 @@ public HttpRequest setFollowRedirects(boolean followRedirects) { return this; } - /** - * Return whether to use raw redirect URLs. - */ + /** Return whether to use raw redirect URLs. */ public boolean getUseRawRedirectUrls() { return useRawRedirectUrls; } /** - * Sets whether to use raw redirect URLs. + * Sets whether to use raw redirect URLs. * *

The default value is {@code false}. */ @@ -938,7 +935,7 @@ public HttpResponse execute() throws IOException { final boolean contentRetrySupported = streamingContent == null || content.retrySupported(); if (streamingContent != null) { final String contentEncoding; - final long contentLength; + long contentLength = -1; final String contentType = content.getType(); // log content if (loggable) { @@ -953,7 +950,6 @@ public HttpResponse execute() throws IOException { } else { contentEncoding = encoding.getName(); streamingContent = new HttpEncodingStreamingContent(streamingContent, encoding); - contentLength = contentRetrySupported ? IOUtils.computeLength(streamingContent) : -1; } // append content headers to log buffer if (loggable) { @@ -1222,13 +1218,14 @@ private static void addSpanAttribute(Span span, String key, String value) { span.putAttribute(key, AttributeValue.stringAttributeValue(value)); } } - + private static String getVersion() { String version = HttpRequest.class.getPackage().getImplementationVersion(); // in a non-packaged environment (local), there's no implementation version to read if (version == null) { // fall back to reading from a properties file - note this value is expected to be cached - try (InputStream inputStream = HttpRequest.class.getResourceAsStream("/google-http-client.properties")) { + try (InputStream inputStream = + HttpRequest.class.getResourceAsStream("/google-http-client.properties")) { if (inputStream != null) { 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 5273300f6..f15ad2945 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 @@ -336,7 +336,8 @@ 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)) { lowLevelResponseContent = new ConsumingInputStream(new GZIPInputStream(lowLevelResponseContent)); } 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 fb5ec5375..9352168a7 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 @@ -83,7 +83,7 @@ public class UrlEncodedParser implements ObjectParser { public static void parse(String content, Object data) { parse(content, data, true); } - + /** * Parses the given URL-encoded content into the given data object of data key name/value pairs * using {@link #parse(Reader, Object)}. @@ -92,7 +92,7 @@ public static void parse(String content, Object data) { * @param data data key name/value pairs * @param decodeEnabled flag that specifies whether decoding should be enabled. */ - public static void parse(String content, Object data, boolean decodeEnabled) { + public static void parse(String content, Object data, boolean decodeEnabled) { if (content == null) { return; } @@ -123,10 +123,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. @@ -138,10 +138,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 @@ -167,9 +166,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/ApacheHttpRequest.java b/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpRequest.java index b31b20594..156a5688d 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpRequest.java +++ b/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpRequest.java @@ -25,9 +25,7 @@ import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; -/** - * @author Yaniv Inbar - */ +/** @author Yaniv Inbar */ final class ApacheHttpRequest extends LowLevelHttpRequest { private final HttpClient httpClient; @@ -54,12 +52,16 @@ public void setTimeout(int connectTimeout, int readTimeout) throws IOException { @Override public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { - Preconditions.checkArgument(request instanceof HttpEntityEnclosingRequest, + Preconditions.checkArgument( + request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); + if (getContentLength() == -1) { + entity.setChunked(true); + } ((HttpEntityEnclosingRequest) request).setEntity(entity); } return new ApacheHttpResponse(request, httpClient.execute(request)); 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/http/javanet/NetHttpRequest.java b/google-http-client/src/main/java/com/google/api/client/http/javanet/NetHttpRequest.java index aa0d8e3e4..1d043472b 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/javanet/NetHttpRequest.java +++ b/google-http-client/src/main/java/com/google/api/client/http/javanet/NetHttpRequest.java @@ -49,6 +49,11 @@ public void addHeader(String name, String value) { connection.addRequestProperty(name, value); } + @VisibleForTesting + String getRequestProperty(String name) { + return connection.getRequestProperty(name); + } + @Override public void setTimeout(int connectTimeout, int readTimeout) { connection.setReadTimeout(readTimeout); 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 7e3990d40..da057d259 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 @@ -77,8 +77,7 @@ public JsonWebSignature( } /** - * Header as specified in - * Reserved + * Header as specified in Reserved * Header Parameter Names. */ public static class Header extends JsonWebToken.Header { @@ -304,8 +303,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 */ @@ -317,8 +316,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. 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/testing/http/javanet/MockHttpURLConnection.java b/google-http-client/src/main/java/com/google/api/client/testing/http/javanet/MockHttpURLConnection.java index 467f495f4..191129483 100644 --- a/google-http-client/src/main/java/com/google/api/client/testing/http/javanet/MockHttpURLConnection.java +++ b/google-http-client/src/main/java/com/google/api/client/testing/http/javanet/MockHttpURLConnection.java @@ -201,4 +201,8 @@ public String getHeaderField(String name) { List values = headers.get(name); return values == null ? null : values.get(0); } + + public int getChunckLength() { + return chunkLength; + } } 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 230af26e2..55012f3f3 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; @@ -52,8 +51,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() - .startsWith("WINDOWS"); + private static final boolean IS_WINDOWS = + StandardSystemProperty.OS_NAME.value().startsWith("WINDOWS"); /** Directory to store data. */ private final File dataDirectory; @@ -144,8 +143,10 @@ static void setPermissionsToOwnerOnly(File file) throws IOException { try { Files.setPosixFilePermissions(Paths.get(file.getAbsolutePath()), permissions); } catch (UnsupportedOperationException exception) { - LOGGER.warning("Unable to set permissions for " + file - + ", because you are running on a non-POSIX file system."); + LOGGER.warning( + "Unable to set permissions for " + + file + + ", because you are running on a non-POSIX file system."); } catch (SecurityException exception) { // ignored } catch (IllegalArgumentException exception) { @@ -155,35 +156,36 @@ static void setPermissionsToOwnerOnly(File file) throws IOException { static void setPermissionsToOwnerOnlyWindows(File file) throws IOException { Path path = Paths.get(file.getAbsolutePath()); - UserPrincipal owner = path.getFileSystem().getUserPrincipalLookupService() - .lookupPrincipalByName("OWNER@"); + UserPrincipal owner = + path.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("OWNER@"); // 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 view.setAcl(ImmutableList.of(entry)); 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 d55b5a0d4..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 @@ -20,7 +20,6 @@ import java.io.IOException; import java.io.InputStream; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.junit.Test; @@ -28,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/HttpRequestTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java index a76b63850..4bca43eca 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 @@ -31,10 +31,6 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; - -import java.util.regex.Pattern; -import junit.framework.TestCase; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; @@ -45,7 +41,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; - +import java.util.regex.Pattern; +import junit.framework.TestCase; import org.junit.Assert; /** @@ -990,7 +987,7 @@ public LowLevelHttpResponse execute() throws IOException { if (expectGZip) { assertEquals(HttpEncodingStreamingContent.class, getStreamingContent().getClass()); assertEquals("gzip", getContentEncoding()); - assertEquals(25, getContentLength()); + assertEquals(-1, getContentLength()); } else { assertFalse( getStreamingContent().getClass().equals(HttpEncodingStreamingContent.class)); @@ -1230,7 +1227,9 @@ public void testExecute_curlLogger() throws Exception { if (message.startsWith("curl")) { found = true; assertTrue(message.contains("curl -v --compressed -H 'Accept-Encoding: gzip'")); - assertTrue(message.contains("-H 'User-Agent: Google-HTTP-Java-Client/" + HttpRequest.VERSION + " (gzip)'")); + assertTrue( + message.contains( + "-H 'User-Agent: Google-HTTP-Java-Client/" + HttpRequest.VERSION + " (gzip)'")); assertTrue(message.contains("' -- 'http://google.com/#q=a'\"'\"'b'\"'\"'c'")); } } @@ -1261,7 +1260,9 @@ public void testExecute_curlLoggerWithContentEncoding() throws Exception { 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( + "-H 'Content-Type: text/plain; charset=UTF-8' -H 'Content-Encoding: gzip'")); assertTrue(message.contains("-d '@-' -- 'http://google.com/#q=a'\"'\"'b'\"'\"'c' << $$$")); } } 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 a3efdb305..b7a30606c 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 @@ -465,11 +465,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")); @@ -479,13 +482,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(); mockBytes = byteStream.toByteArray(); @@ -511,7 +513,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()); @@ -537,7 +540,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/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/http/javanet/NetHttpRequestTest.java b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java index d4118328e..687967bab 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java @@ -1,9 +1,8 @@ package com.google.api.client.http.javanet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; +import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.HttpContent; import com.google.api.client.http.InputStreamContent; import com.google.api.client.http.LowLevelHttpResponse; @@ -15,6 +14,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeoutException; import org.junit.Test; @@ -203,4 +203,34 @@ public void close() throws IOException { assertEquals("Error during close", e.getMessage()); } } + + @Test + public void testChunkedLengthSet() throws Exception { + MockHttpURLConnection connection = new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)); + connection.setRequestMethod("POST"); + NetHttpRequest request = new NetHttpRequest(connection); + InputStream is = NetHttpRequestTest.class.getClassLoader().getResourceAsStream("file.txt"); + HttpContent content = new InputStreamContent("text/plain", is); + request.setStreamingContent(content); + request.setContentEncoding("gzip"); + request.execute(); + + assertEquals(connection.getChunckLength(), 4096); + assertNull(request.getRequestProperty("Content-Length")); + } + + @Test + public void testChunkedLengthNotSet() throws Exception { + MockHttpURLConnection connection = new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)); + connection.setRequestMethod("POST"); + NetHttpRequest request = new NetHttpRequest(connection); + HttpContent content = + new ByteArrayContent("text/plain", "sample".getBytes(StandardCharsets.UTF_8)); + request.setStreamingContent(content); + request.setContentLength(content.getLength()); + request.execute(); + + assertEquals(connection.getChunckLength(), -1); + assertEquals("6", request.getRequestProperty("Content-Length")); + } } 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 8bff77f93..e7740a42a 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,16 +17,13 @@ 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 java.io.IOException; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.util.ArrayList; import java.util.List; - import javax.net.ssl.X509TrustManager; - import org.junit.Assert; import org.junit.Test; @@ -56,12 +53,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(); @@ -70,7 +67,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(); @@ -79,7 +76,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(); @@ -87,7 +84,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(); 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)); } } - From 286f84758f49e4b24a7c47a65413adf837edff6f Mon Sep 17 00:00:00 2001 From: Cody Oss Date: Tue, 10 Dec 2019 15:27:17 -0700 Subject: [PATCH 2/5] revert format changes --- .../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 | 57 ++++++----- .../api/client/findbugs/package-info.java | 34 +++---- .../api/client/json/gson/GsonParserTest.java | 15 +-- .../json/jackson2/JacksonParserTest.java | 15 +-- .../test/json/AbstractJsonParserTest.java | 15 +-- .../java/com/google/api/client/xml/Xml.java | 8 +- .../google/api/client/http/GenericUrl.java | 47 ++++------ .../google/api/client/http/HttpResponse.java | 3 +- .../api/client/http/UrlEncodedParser.java | 27 +++--- .../http/apache/ApacheHttpTransport.java | 4 +- .../json/webtoken/JsonWebSignature.java | 11 ++- .../client/json/webtoken/JsonWebToken.java | 8 +- .../util/store/FileDataStoreFactory.java | 56 ++++++----- .../client/http/ConsumingInputStreamTest.java | 4 +- .../client/http/HttpRequestTracingTest.java | 80 +++++++--------- .../api/client/http/HttpResponseTest.java | 22 ++--- .../api/client/http/OpenCensusUtilsTest.java | 1 + .../json/webtoken/JsonWebSignatureTest.java | 13 ++- .../google/api/client/util/DateTimeTest.java | 8 +- .../api/client/util/GenericDataTest.java | 5 +- .../google/api/client/util/IOUtilsTest.java | 1 + 24 files changed, 270 insertions(+), 264 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 02fb98a35..864dd072f 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,15 +38,19 @@ /** * 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 @@ -68,18 +72,20 @@ 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. - * - *

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

+ * 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

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

Settings: + * Creates a new instance of the Apache HTTP client that is used by the + * {@link #ApacheHttpTransport()} constructor. * + *

+ * Settings: + *

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

Settings: + * Creates a new Apache HTTP client builder that is used by the + * {@link #ApacheHttpTransport()} constructor. * + *

+ * Settings: + *

* * * @return new instance of the Apache HTTP client @@ -131,14 +139,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 451b67f2c..8fc11e6d8 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,7 +21,9 @@ 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 7ca1708ad..1909a2f75 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,4 +18,6 @@ * @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 b336f3016..e6ca850ce 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 @@ -34,6 +34,7 @@ import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.http.Header; @@ -125,8 +126,7 @@ private void subtestUnsupportedRequestsWithContent(ApacheHttpRequest request, St fail("expected " + IllegalArgumentException.class); } catch (IllegalArgumentException e) { // expected - assertEquals( - e.getMessage(), + assertEquals(e.getMessage(), "Apache HTTP client does not support " + method + " requests with content."); } } @@ -142,18 +142,16 @@ 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"); @@ -165,21 +163,17 @@ public HttpResponse execute( @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"); @@ -231,7 +225,10 @@ 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 83168807c..c22541fb6 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,26 +15,28 @@ /** * 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 aa5ed5aea..f79d4a5d6 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,16 +1,19 @@ /** * 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/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 ed185c7ab..92da03605 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,16 +1,19 @@ /** * 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 2a68c639c..ef641e868 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,16 +1,19 @@ /** * 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 1aa5a343b..4f9156d3c 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/GenericUrl.java b/google-http-client/src/main/java/com/google/api/client/http/GenericUrl.java index efd9bfedb..68c5ea6c3 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/GenericUrl.java +++ b/google-http-client/src/main/java/com/google/api/client/http/GenericUrl.java @@ -81,10 +81,10 @@ public class GenericUrl extends GenericData { private String fragment; /** - * If true, the URL string originally given is used as is (without encoding, decoding and - * escaping) whenever referenced; otherwise, part of the URL string may be encoded or decoded as - * deemed appropriate or necessary. - */ + * If true, the URL string originally given is used as is (without encoding, decoding and + * escaping) whenever referenced; otherwise, part of the URL string may be encoded or decoded as + * deemed appropriate or necessary. + */ private boolean verbatim; public GenericUrl() {} @@ -112,20 +112,20 @@ public GenericUrl(String encodedUrl) { /** * Constructs from an encoded URL. * - *

Any known query parameters with pre-defined fields as data keys are parsed based on their - * data type. Any unrecognized query parameter are always parsed as a string. + *

Any known query parameters with pre-defined fields as data keys are parsed based on + * their data type. Any unrecognized query parameter are always parsed as a string. * *

Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}. * * @param encodedUrl encoded URL, including any existing query parameters that should be parsed - * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and - * escaping) + * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and escaping) * @throws IllegalArgumentException if URL has a syntax error */ public GenericUrl(String encodedUrl, boolean verbatim) { this(parseURL(encodedUrl), verbatim); } + /** * Constructs from a URI. * @@ -140,8 +140,7 @@ public GenericUrl(URI uri) { * Constructs from a URI. * * @param uri URI - * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and - * escaping) + * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and escaping) */ public GenericUrl(URI uri, boolean verbatim) { this( @@ -169,8 +168,7 @@ public GenericUrl(URL url) { * Constructs from a URL. * * @param url URL - * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and - * escaping) + * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and escaping) * @since 1.14 */ public GenericUrl(URL url, boolean verbatim) { @@ -211,7 +209,7 @@ private GenericUrl( UrlEncodedParser.parse(query, this); } this.userInfo = userInfo != null ? CharEscapers.decodeUri(userInfo) : null; - } + } } @Override @@ -569,11 +567,10 @@ public static List toPathParts(String encodedPath) { * * @param encodedPath slash-prefixed encoded path, for example {@code * "/m8/feeds/contacts/default/full"} - * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and - * escaping) - * @return path parts (decoded if not {@code verbatim}), with each part assumed to be preceded by - * a {@code '/'}, for example {@code "", "m8", "feeds", "contacts", "default", "full"}, or - * {@code null} for {@code null} or {@code ""} input + * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and escaping) + * @return path parts (decoded if not {@code verbatim}), with each part assumed to be preceded by a {@code '/'}, for example + * {@code "", "m8", "feeds", "contacts", "default", "full"}, or {@code null} for {@code null} + * or {@code ""} input */ public static List toPathParts(String encodedPath, boolean verbatim) { if (encodedPath == null || encodedPath.length() == 0) { @@ -611,17 +608,13 @@ private void appendRawPathFromParts(StringBuilder buf) { } /** Adds query parameters from the provided entrySet into the buffer. */ - static void addQueryParams( - Set> entrySet, StringBuilder buf, boolean verbatim) { + static void addQueryParams(Set> entrySet, StringBuilder buf, boolean verbatim) { // (similar to UrlEncodedContent) boolean first = true; for (Map.Entry nameValueEntry : entrySet) { Object value = nameValueEntry.getValue(); if (value != null) { - String name = - verbatim - ? nameValueEntry.getKey() - : CharEscapers.escapeUriQuery(nameValueEntry.getKey()); + String name = verbatim ? nameValueEntry.getKey() : CharEscapers.escapeUriQuery(nameValueEntry.getKey()); if (value instanceof Collection) { Collection collectionValue = (Collection) value; for (Object repeatedValue : collectionValue) { @@ -634,8 +627,7 @@ static void addQueryParams( } } - private static boolean appendParam( - boolean first, StringBuilder buf, String name, Object value, boolean verbatim) { + private static boolean appendParam(boolean first, StringBuilder buf, String name, Object value, boolean verbatim) { if (first) { first = false; buf.append('?'); @@ -643,8 +635,7 @@ private static boolean appendParam( buf.append('&'); } buf.append(name); - String stringValue = - verbatim ? value.toString() : CharEscapers.escapeUriQuery(value.toString()); + String stringValue = verbatim ? value.toString() : CharEscapers.escapeUriQuery(value.toString()); if (stringValue.length() != 0) { buf.append('=').append(stringValue); } 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 f15ad2945..5273300f6 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 @@ -336,8 +336,7 @@ 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)) { lowLevelResponseContent = new ConsumingInputStream(new GZIPInputStream(lowLevelResponseContent)); } 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 9352168a7..fb5ec5375 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 @@ -83,7 +83,7 @@ public class UrlEncodedParser implements ObjectParser { public static void parse(String content, Object data) { parse(content, data, true); } - + /** * Parses the given URL-encoded content into the given data object of data key name/value pairs * using {@link #parse(Reader, Object)}. @@ -92,7 +92,7 @@ public static void parse(String content, Object data) { * @param data data key name/value pairs * @param decodeEnabled flag that specifies whether decoding should be enabled. */ - public static void parse(String content, Object data, boolean decodeEnabled) { + public static void parse(String content, Object data, boolean decodeEnabled) { if (content == null) { return; } @@ -123,10 +123,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. @@ -138,9 +138,10 @@ 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 @@ -166,13 +167,9 @@ 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 890bdf2f2..ce5e59d51 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/webtoken/JsonWebSignature.java b/google-http-client/src/main/java/com/google/api/client/json/webtoken/JsonWebSignature.java index da057d259..7e3990d40 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 @@ -77,7 +77,8 @@ public JsonWebSignature( } /** - * Header as specified in Reserved + * Header as specified in + * Reserved * Header Parameter Names. */ public static class Header extends JsonWebToken.Header { @@ -303,8 +304,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 */ @@ -316,8 +317,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. 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 bfcf63fe9..f68450190 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,7 +47,8 @@ public JsonWebToken(Header header, Payload payload) { } /** - * Header as specified in JWT Header. + * Header as specified in + * JWT Header. */ public static class Header extends GenericJson { @@ -114,8 +115,9 @@ 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/store/FileDataStoreFactory.java b/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java index 55012f3f3..230af26e2 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,6 +16,7 @@ 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; @@ -51,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().startsWith("WINDOWS"); + private static final boolean IS_WINDOWS = StandardSystemProperty.OS_NAME.value() + .startsWith("WINDOWS"); /** Directory to store data. */ private final File dataDirectory; @@ -143,10 +144,8 @@ static void setPermissionsToOwnerOnly(File file) throws IOException { try { Files.setPosixFilePermissions(Paths.get(file.getAbsolutePath()), permissions); } catch (UnsupportedOperationException exception) { - LOGGER.warning( - "Unable to set permissions for " - + file - + ", because you are running on a non-POSIX file system."); + LOGGER.warning("Unable to set permissions for " + file + + ", because you are running on a non-POSIX file system."); } catch (SecurityException exception) { // ignored } catch (IllegalArgumentException exception) { @@ -156,36 +155,35 @@ static void setPermissionsToOwnerOnly(File file) throws IOException { static void setPermissionsToOwnerOnlyWindows(File file) throws IOException { Path path = Paths.get(file.getAbsolutePath()); - UserPrincipal owner = - path.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("OWNER@"); + UserPrincipal owner = path.getFileSystem().getUserPrincipalLookupService() + .lookupPrincipalByName("OWNER@"); // 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 view.setAcl(ImmutableList.of(entry)); 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 afcdf2bf5..d55b5a0d4 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 @@ -20,6 +20,7 @@ import java.io.IOException; import java.io.InputStream; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.junit.Test; @@ -27,8 +28,7 @@ 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/HttpRequestTracingTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java index d2d2df5d1..5d89f0350 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,12 +13,6 @@ */ 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; @@ -31,12 +25,19 @@ 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(); @@ -59,12 +60,13 @@ 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 @@ -86,11 +88,8 @@ 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()); @@ -98,19 +97,16 @@ 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(); @@ -137,25 +133,21 @@ 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 b7a30606c..a3efdb305 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 @@ -465,14 +465,11 @@ 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")); @@ -482,12 +479,13 @@ public void testGetContent_gzipEncoding_finishReadingWithUppercaseContentEncodin } } - 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(); mockBytes = byteStream.toByteArray(); @@ -513,8 +511,7 @@ 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()); @@ -540,8 +537,7 @@ 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/OpenCensusUtilsTest.java b/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java index 480d10150..8fa8624eb 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,6 +14,7 @@ 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 e7740a42a..8bff77f93 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,13 +17,16 @@ 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 java.io.IOException; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.util.ArrayList; import java.util.List; + import javax.net.ssl.X509TrustManager; + import org.junit.Assert; import org.junit.Test; @@ -53,12 +56,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(); @@ -67,7 +70,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(); @@ -76,7 +79,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(); @@ -84,7 +87,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(); 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 ce7d2b027..785ab40d5 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,13 +224,15 @@ 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 52b2b9a0a..c1d3872c0 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,10 +15,13 @@ 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 42166ae5d..4d3503544 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,3 +53,4 @@ public void testIsSymbolicLink_true() throws IOException { assertTrue(IOUtils.isSymbolicLink(file2)); } } + From ad1629f4d8dc125e0ee0f0318534898db0277d99 Mon Sep 17 00:00:00 2001 From: Cody Oss Date: Tue, 10 Dec 2019 15:28:08 -0700 Subject: [PATCH 3/5] fix pr comments --- .../http/apache/v2/ApacheHttpRequestTest.java | 14 ++++++++++++++ .../http/javanet/MockHttpURLConnection.java | 2 +- .../client/http/javanet/NetHttpRequestTest.java | 4 ++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpRequestTest.java b/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpRequestTest.java index 61e78182a..74c97244a 100644 --- a/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpRequestTest.java +++ b/google-http-client-apache-v2/src/test/java/com/google/api/client/http/apache/v2/ApacheHttpRequestTest.java @@ -1,3 +1,17 @@ +/* + * 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 + * + * 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.http.apache.v2; import static org.junit.Assert.assertEquals; diff --git a/google-http-client/src/main/java/com/google/api/client/testing/http/javanet/MockHttpURLConnection.java b/google-http-client/src/main/java/com/google/api/client/testing/http/javanet/MockHttpURLConnection.java index 191129483..2fba28b48 100644 --- a/google-http-client/src/main/java/com/google/api/client/testing/http/javanet/MockHttpURLConnection.java +++ b/google-http-client/src/main/java/com/google/api/client/testing/http/javanet/MockHttpURLConnection.java @@ -202,7 +202,7 @@ public String getHeaderField(String name) { return values == null ? null : values.get(0); } - public int getChunckLength() { + public int getChunkLength() { return chunkLength; } } diff --git a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java index 687967bab..da598b285 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java @@ -215,7 +215,7 @@ public void testChunkedLengthSet() throws Exception { request.setContentEncoding("gzip"); request.execute(); - assertEquals(connection.getChunckLength(), 4096); + assertEquals(connection.getChunkLength(), 4096); assertNull(request.getRequestProperty("Content-Length")); } @@ -230,7 +230,7 @@ public void testChunkedLengthNotSet() throws Exception { request.setContentLength(content.getLength()); request.execute(); - assertEquals(connection.getChunckLength(), -1); + assertEquals(connection.getChunkLength(), -1); assertEquals("6", request.getRequestProperty("Content-Length")); } } From fcc043c178b9416aecf9ef8803699b42cd0bd42f Mon Sep 17 00:00:00 2001 From: Cody Oss Date: Tue, 10 Dec 2019 16:58:33 -0700 Subject: [PATCH 4/5] fix --- .../com/google/api/client/http/apache/v2/ApacheHttpRequest.java | 2 +- .../com/google/api/client/http/apache/ApacheHttpRequest.java | 2 +- .../com/google/api/client/http/javanet/NetHttpRequestTest.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpRequest.java b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpRequest.java index 7743bf4b5..ae2aac763 100644 --- a/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpRequest.java +++ b/google-http-client-apache-v2/src/main/java/com/google/api/client/http/apache/v2/ApacheHttpRequest.java @@ -57,7 +57,7 @@ public void setTimeout(int connectTimeout, int readTimeout) throws IOException { @Override public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { - Preconditions.checkArgument( + Preconditions.checkState( request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); diff --git a/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpRequest.java b/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpRequest.java index 156a5688d..355acfcd0 100644 --- a/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpRequest.java +++ b/google-http-client/src/main/java/com/google/api/client/http/apache/ApacheHttpRequest.java @@ -52,7 +52,7 @@ public void setTimeout(int connectTimeout, int readTimeout) throws IOException { @Override public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { - Preconditions.checkArgument( + Preconditions.checkState( request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); diff --git a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java index da598b285..ae3606ca5 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java @@ -215,7 +215,7 @@ public void testChunkedLengthSet() throws Exception { request.setContentEncoding("gzip"); request.execute(); - assertEquals(connection.getChunkLength(), 4096); + assertEquals(4096, connection.getChunkLength()); assertNull(request.getRequestProperty("Content-Length")); } From 8573744cba0c0b9e81b9d04a0d3e6d25df3ce250 Mon Sep 17 00:00:00 2001 From: Cody Oss Date: Mon, 16 Dec 2019 10:09:40 -0700 Subject: [PATCH 5/5] refacor test for checkState --- .../api/client/http/apache/v2/ApacheHttpTransportTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 e6ca850ce..e9b93e9be 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 @@ -34,7 +34,6 @@ import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; -import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.http.Header; @@ -123,8 +122,8 @@ private void subtestUnsupportedRequestsWithContent(ApacheHttpRequest request, St throws IOException { try { execute(request); - fail("expected " + IllegalArgumentException.class); - } catch (IllegalArgumentException e) { + fail("expected " + IllegalStateException.class); + } catch (IllegalStateException e) { // expected assertEquals(e.getMessage(), "Apache HTTP client does not support " + method + " requests with content.");