You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2020/10/13 15:48:53 UTC
[juneau] branch master updated: Remove deprecated code.
This is an automated email from the ASF dual-hosted git repository.
jamesbognar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/juneau.git
The following commit(s) were added to refs/heads/master by this push:
new b7f18f3 Remove deprecated code.
b7f18f3 is described below
commit b7f18f3c975faa6c0f3ed4adf82bca24e9adc2a7
Author: JamesBognar <ja...@salesforce.com>
AuthorDate: Tue Oct 13 11:48:47 2020 -0400
Remove deprecated code.
---
.../juneau/rest/client/AllowAllRedirects.java | 33 -
.../org/apache/juneau/rest/client/DateHeader.java | 45 -
.../org/apache/juneau/rest/client/HttpMethod.java | 62 -
.../apache/juneau/rest/client/NameValuePairs.java | 96 -
.../apache/juneau/rest/client/ResponsePattern.java | 135 -
.../org/apache/juneau/rest/client/RestCall.java | 2524 ---------------
.../juneau/rest/client/RestCallException.java | 249 --
.../apache/juneau/rest/client/RestCallHandler.java | 68 -
.../juneau/rest/client/RestCallInterceptor.java | 64 -
.../apache/juneau/rest/client/RestCallLogger.java | 130 -
.../org/apache/juneau/rest/client/RestClient.java | 1544 ---------
.../juneau/rest/client/RestClientBuilder.java | 3274 --------------------
.../juneau/rest/client/RestRequestEntity.java | 97 -
.../org/apache/juneau/rest/client/RetryOn.java | 69 -
.../rest/client/SerializedNameValuePair.java | 80 -
.../juneau/rest/client/SimpleX509TrustManager.java | 69 -
.../rest/client/mock/MockHttpClientConnection.java | 123 -
.../mock/MockHttpClientConnectionManager.java | 82 -
.../juneau/rest/client/mock/package-info.java | 18 -
.../apache/juneau/rest/client/package-info.java | 18 -
20 files changed, 8780 deletions(-)
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/AllowAllRedirects.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/AllowAllRedirects.java
deleted file mode 100644
index ef25685..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/AllowAllRedirects.java
+++ /dev/null
@@ -1,33 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import org.apache.http.impl.client.*;
-
-/**
- * Redirect strategy that allows for redirects on any request type, not just <c>GET</c> or <c>HEAD</c>.
- *
- * <ul class='notes'>
- * <li>
- * This class is similar to <c>org.apache.http.impl.client.LaxRedirectStrategy</c>
- * in Apache HttpClient 4.2, but also allows for redirects on <c>PUTs</c> and <c>DELETEs</c>.
- * </ul>
- */
-@Deprecated
-public class AllowAllRedirects extends DefaultRedirectStrategy {
-
- @Override /* DefaultRedirectStrategy */
- protected boolean isRedirectable(final String method) {
- return true;
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/DateHeader.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/DateHeader.java
deleted file mode 100644
index a4101ad..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/DateHeader.java
+++ /dev/null
@@ -1,45 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import java.util.Date;
-
-import org.apache.http.client.utils.*;
-import org.apache.http.message.BasicHeader;
-
-/**
- * Convenience class for setting date headers in RFC2616 format.
- *
- * <p>
- * Equivalent to the following code:
- * <p class='bcode w800'>
- * Header h = <jk>new</jk> Header(name, DateUtils.<jsm>formatDate</jsm>(value));
- * </p>
- *
- * @deprecated Use {@link org.apache.juneau.http.header.Date}
- */
-@Deprecated
-public final class DateHeader extends BasicHeader {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * Creates a date request property in RFC2616 format.
- *
- * @param name The header name.
- * @param value The header value.
- */
- public DateHeader(String name, Date value) {
- super(name, DateUtils.formatDate(value));
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/HttpMethod.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/HttpMethod.java
deleted file mode 100644
index 9dcff9b..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/HttpMethod.java
+++ /dev/null
@@ -1,62 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-/**
- * Enumeration of HTTP methods.
- */
-@Deprecated
-public enum HttpMethod {
-
- /** HTTP GET */
- GET(false),
-
- /** HTTP PUT */
- PUT(true),
-
- /** HTTP POST */
- POST(true),
-
- /** HTTP DELETE */
- DELETE(false),
-
- /** HTTP OPTIONS */
- OPTIONS(false),
-
- /** HTTP HEAD */
- HEAD(false),
-
- /** HTTP TRACE */
- TRACE(false),
-
- /** HTTP CONNECT */
- CONNECT(false),
-
- /** HTTP MOVE */
- MOVE(false);
-
- private boolean hasContent;
-
- HttpMethod(boolean hasContent) {
- this.hasContent = hasContent;
- }
-
- /**
- * Returns whether this HTTP method normally has content.
- *
- * @return <jk>true</jk> if this HTTP method normally has content.
- */
- public boolean hasContent() {
- return hasContent;
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/NameValuePairs.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/NameValuePairs.java
deleted file mode 100644
index 1870f1d..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/NameValuePairs.java
+++ /dev/null
@@ -1,96 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import static org.apache.juneau.internal.StringUtils.*;
-
-import java.util.*;
-
-import org.apache.http.*;
-import org.apache.http.client.entity.*;
-import org.apache.http.message.*;
-import org.apache.juneau.httppart.*;
-import org.apache.juneau.oapi.*;
-import org.apache.juneau.urlencoding.*;
-
-/**
- * Convenience class for constructing instances of <c>List<NameValuePair></c> for the
- * {@link UrlEncodedFormEntity} class.
- *
- * <p>
- * Instances of this method can be passed directly to the {@link RestClient#doPost(Object, Object)} method or
- * {@link RestCall#body(Object)} methods to perform URL-encoded form posts.
- *
- * <h5 class='section'>Example:</h5>
- * <p class='bcode w800'>
- * NameValuePairs params = <jk>new</jk> NameValuePairs()
- * .append(<js>"j_username"</js>, user)
- * .append(<js>"j_password"</js>, pw);
- * restClient.doPost(url, params).run();
- * </p>
- *
- * @deprecated Use {@link org.apache.juneau.http.NameValuePairSupplier}
- */
-@Deprecated
-public final class NameValuePairs extends LinkedList<NameValuePair> {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * Appends the specified pair to the end of this list.
- *
- * @param pair The pair to append to this list.
- * @return This object (for method chaining).
- */
- public NameValuePairs append(NameValuePair pair) {
- super.add(pair);
- return this;
- }
-
- /**
- * Appends the specified name/value pair to the end of this list.
- *
- * <p>
- * The value is simply converted to a string using <c>toString()</c>, or <js>"null"</js> if <jk>null</jk>.
- *
- * @param name The pair name.
- * @param value The pair value.
- * @return This object (for method chaining).
- */
- public NameValuePairs append(String name, Object value) {
- super.add(new BasicNameValuePair(name, stringify(value)));
- return this;
- }
-
- /**
- * Appends the specified name/value pair to the end of this list.
- *
- * <p>
- * The value is converted to UON notation using the {@link UrlEncodingSerializer} defined on the client.
- *
- * @param name The pair name.
- * @param value The pair value.
- * @param serializer
- * The serializer to use for serializing the value to a string value.
- * @param schema
- * The schema object that defines the format of the output.
- * <br>If <jk>null</jk>, defaults to the schema defined on the parser.
- * <br>If that's also <jk>null</jk>, defaults to {@link HttpPartSchema#DEFAULT}.
- * <br>Only used if serializer is schema-aware (e.g. {@link OpenApiSerializer}).
- * @return This object (for method chaining).
- */
- public NameValuePairs append(String name, Object value, HttpPartSerializer serializer, HttpPartSchema schema) {
- super.add(new SerializedNameValuePair(name, value, serializer, schema));
- return this;
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/ResponsePattern.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/ResponsePattern.java
deleted file mode 100644
index ca4d511..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/ResponsePattern.java
+++ /dev/null
@@ -1,135 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import java.io.*;
-import java.util.regex.*;
-
-/**
- * Used to find regular expression matches in REST responses made through {@link RestCall}.
- *
- * <p>
- * Response patterns are applied to REST calls through the {@link RestCall#responsePattern(ResponsePattern)} method.
- *
- * <h5 class='section'>Example:</h5>
- *
- * This example shows how to use a response pattern finder to find and capture patterns for <js>"x=number"</js> and
- * <js>"y=string"</js> from a response body.
- * <p class='bcode w800'>
- * <jk>final</jk> List<Number> xList = <jk>new</jk> ArrayList<Number>();
- * <jk>final</jk> List<String> yList = <jk>new</jk> ArrayList<String>();
- *
- * restClient.doGet(<jsf>URL</jsf>)
- * .addResponsePattern(
- * <jk>new</jk> ResponsePattern(<js>"x=(\\d+)"</js>) {
- * <ja>@Override</ja>
- * <jk>public void</jk> onMatch(RestCall restCall, Matcher m) <jk>throws</jk> RestCallException {
- * xList.add(Integer.<jsm>parseInt</jsm>(m.group(1)));
- * }
- * <ja>@Override</ja>
- * <jk>public void</jk> onNoMatch(RestCall restCall) <jk>throws</jk> RestCallException {
- * <jk>throw new</jk> RestCallException(<js>"No X's found!"</js>);
- * }
- * }
- * )
- * .addResponsePattern(
- * <jk>new</jk> ResponsePattern(<js>"y=(\\S+)"</js>) {
- * <ja>@Override</ja>
- * <jk>public void</jk> onMatch(RestCall restCall, Matcher m) <jk>throws</jk> RestCallException {
- * yList.add(m.group(1));
- * }
- * <ja>@Override</ja>
- * <jk>public void</jk> onNoMatch(RestCall restCall) <jk>throws</jk> RestCallException {
- * <jk>throw new</jk> RestCallException(<js>"No Y's found!"</js>);
- * }
- * }
- * )
- * .run();
- * </p>
- *
- * <ul class='notes'>
- * <li>
- * Using response patterns does not affect the functionality of any of the other methods
- * used to retrieve the response such as {@link RestCall#getResponseAsString()} or {@link RestCall#getResponse(Class)}.
- * <br>HOWEVER, if you want to retrieve the entire text of the response from inside the match methods, use
- * {@link RestCall#getCapturedResponse()} since this method will not absorb the response for those other methods.
- * <li>
- * Response pattern methods are NOT executed if a REST exception occurs during the request.
- * <li>
- * The {@link RestCall#successPattern(String)} and {@link RestCall#failurePattern(String)} methods use instances
- * of this class to throw {@link RestCallException RestCallExceptions} when success patterns are not found or
- * failure patterns are found.
- * <li>
- * {@link ResponsePattern} objects are reusable and thread-safe.
- * </ul>
- *
- * @deprecated Use new methods provided on {@link org.apache.juneau.rest.client2.RestResponse} class.
- */
-@Deprecated
-public abstract class ResponsePattern {
-
- private Pattern pattern;
-
- /**
- * Constructor.
- *
- * @param pattern Regular expression pattern.
- */
- public ResponsePattern(String pattern) {
- this.pattern = Pattern.compile(pattern);
- }
-
- void match(RestCall rc) throws RestCallException {
- try {
- Matcher m = pattern.matcher(rc.getCapturedResponse());
- boolean found = false;
- while (m.find()) {
- onMatch(rc, m);
- found = true;
- }
- if (! found)
- onNoMatch(rc);
- } catch (IOException e) {
- throw new RestCallException(e);
- }
- }
-
- /**
- * Returns the pattern passed in through the constructor.
- *
- * @return The pattern passed in through the constructor.
- */
- protected String getPattern() {
- return pattern.pattern();
- }
-
- /**
- * Instances can override this method to handle when a regular expression pattern matches on the output.
- *
- * <p>
- * This method is called once for every pattern match that occurs in the response text.
- *
- * @param rc The {@link RestCall} that this pattern finder is being used on.
- * @param m The regular expression {@link Matcher}. Can be used to retrieve group matches in the pattern.
- * @throws RestCallException Instances can throw an exception if a failure condition is detected.
- */
- public void onMatch(RestCall rc, Matcher m) throws RestCallException {}
-
- /**
- * Instances can override this method to handle when a regular expression pattern doesn't match on the output.
- *
- * @param rc The {@link RestCall} that this pattern finder is being used on.
- * @throws RestCallException Instances can throw an exception if a failure condition is detected.
- */
- public void onNoMatch(RestCall rc) throws RestCallException {}
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCall.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCall.java
deleted file mode 100644
index 27e17e4..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCall.java
+++ /dev/null
@@ -1,2524 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import static org.apache.juneau.internal.IOUtils.*;
-import static org.apache.juneau.internal.StringUtils.*;
-import static org.apache.juneau.httppart.HttpPartType.*;
-import static org.apache.http.HttpStatus.*;
-
-import java.io.*;
-import java.lang.reflect.*;
-import java.lang.reflect.Proxy;
-import java.net.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.logging.*;
-import java.util.regex.*;
-
-import org.apache.http.*;
-import org.apache.http.Header;
-import org.apache.http.client.*;
-import org.apache.http.client.config.*;
-import org.apache.http.client.entity.*;
-import org.apache.http.client.methods.*;
-import org.apache.http.client.utils.*;
-import org.apache.http.conn.*;
-import org.apache.http.entity.*;
-import org.apache.http.entity.ContentType;
-import org.apache.http.impl.client.*;
-import org.apache.http.util.*;
-import org.apache.juneau.*;
-import org.apache.juneau.collections.*;
-import org.apache.juneau.encoders.*;
-import org.apache.juneau.http.*;
-import org.apache.juneau.http.annotation.*;
-import org.apache.juneau.httppart.*;
-import org.apache.juneau.httppart.bean.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.oapi.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.parser.ParseException;
-import org.apache.juneau.reflect.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.utils.*;
-
-/**
- * Represents a connection to a remote REST resource.
- *
- * <p>
- * Instances of this class are created by the various {@code doX()} methods on the {@link RestClient} class.
- *
- * <p>
- * This class uses only Java standard APIs. Requests can be built up using a fluent interface with method chaining,
- * like so...
- * <p class='bcode w800'>
- * RestClient client = <jk>new</jk> RestClient();
- * RestCall c = client.doPost(<jsf>URL</jsf>).setInput(o).setHeader(x,y);
- * MyBean b = c.getResponse(MyBean.<jk>class</jk>);
- * </p>
- *
- * <p>
- * The actual connection and request/response transaction occurs when calling one of the <c>getResponseXXX()</c>
- * methods.
- *
- * <ul class='seealso'>
- * <li class='link'>{@doc juneau-rest-client}
- * </ul>
- *
- * @deprecated Use {@link org.apache.juneau.rest.client2.RestRequest} class.
- */
-@Deprecated
-@SuppressWarnings({ "unchecked" })
-public final class RestCall extends BeanSession implements Closeable {
-
- private static final ContentType TEXT_PLAIN = ContentType.create("text/plain");
-
- private final RestClient client; // The client that created this call.
- private final HttpRequestBase request; // The request.
- private HttpResponse response; // The response.
- private List<RestCallInterceptor> interceptors = new ArrayList<>(); // Used for intercepting and altering requests.
-
- private boolean isConnected = false; // connect() has been called.
- private boolean allowRedirectsOnPosts;
- private int retries = 1;
- private int redirectOnPostsTries = 5;
- private long retryInterval = -1;
- private RetryOn retryOn;
- private boolean ignoreErrors;
- private boolean byLines = false;
- private TeeWriter writers = new TeeWriter();
- private StringWriter capturedResponseWriter;
- private String capturedResponse;
- private TeeOutputStream outputStreams = new TeeOutputStream();
- private boolean isClosed = false;
- private boolean isFailed = false;
- private Object input;
- private boolean hasInput; // input() was called, even if it's setting 'null'.
- private Serializer serializer;
- private Parser parser;
- private HttpPartSerializer partSerializer;
- private HttpPartParser partParser;
- private HttpPartSchema requestBodySchema, responseBodySchema;
- private URIBuilder uriBuilder;
- private NameValuePairs formData;
- private boolean softClose = false; // If true, don't consume response and set isClosed flag, but do call listeners.
-
- /**
- * Constructs a REST call with the specified method name.
- *
- * @param client The client that created this request.
- * @param request The wrapped Apache HTTP client request object.
- * @param uri The URI for this call.
- * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt.
- */
- protected RestCall(RestClient client, HttpRequestBase request, URI uri) throws RestCallException {
- super(client, BeanSessionArgs.DEFAULT);
- this.client = client;
- this.request = request;
- for (RestCallInterceptor i : this.client.interceptors)
- interceptor(i);
- this.retryOn = client.retryOn;
- this.retries = client.retries;
- this.retryInterval = client.retryInterval;
- this.serializer = client.serializer;
- this.parser = client.parser;
- this.partSerializer = client.getPartSerializer();
- this.partParser = client.getPartParser();
- uriBuilder = new URIBuilder(uri);
- }
-
- /**
- * Sets the URI for this call.
- *
- * <p>
- * Can be any of the following types:
- * <ul>
- * <li>{@link URI}
- * <li>{@link URL}
- * <li>{@link URIBuilder}
- * <li>Anything else converted to a string using {@link Object#toString()}.
- * </ul>
- *
- * <p>
- * Relative URL strings will be interpreted as relative to the root URL defined on the client.
- *
- * @param uri
- * The URI to use for this call.
- * This overrides the URI passed in from the client.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid URI syntax detected.
- */
- public RestCall uri(Object uri) throws RestCallException {
- try {
- if (uri != null)
- uriBuilder = new URIBuilder(client.toURI(uri));
- return this;
- } catch (URISyntaxException e) {
- throw new RestCallException(e);
- }
- }
-
- /**
- * Sets the URI scheme.
- *
- * @param scheme The new URI host.
- * @return This object (for method chaining).
- */
- public RestCall scheme(String scheme) {
- uriBuilder.setScheme(scheme);
- return this;
- }
-
- /**
- * Sets the URI host.
- *
- * @param host The new URI host.
- * @return This object (for method chaining).
- */
- public RestCall host(String host) {
- uriBuilder.setHost(host);
- return this;
- }
-
- /**
- * Sets the URI port.
- *
- * @param port The new URI port.
- * @return This object (for method chaining).
- */
- public RestCall port(int port) {
- uriBuilder.setPort(port);
- return this;
- }
-
- /**
- * Adds a query parameter to the URI query.
- *
- * @param name
- * The parameter name.
- * Can be null/blank/* if the value is a {@link Map}, {@link String}, {@link NameValuePairs}, or bean.
- * @param value
- * The parameter value converted to a string using UON notation.
- * Can also be {@link Map}, {@link String}, {@link NameValuePairs}, or bean if the name is null/blank/*.
- * If a {@link String} and the name is null/blank/*, then calls {@link URIBuilder#setCustomQuery(String)}.
- * @param skipIfEmpty Don't add the pair if the value is empty.
- * @param serializer
- * The serializer to use for serializing the value to a string value.
- * If <jk>null</jk>, then the URL-encoding serializer defined on the client is used.
- * @param schema
- * The schema object that defines the format of the output.
- * <br>If <jk>null</jk>, defaults to the schema defined on the serializer.
- * <br>If that's also <jk>null</jk>, defaults to {@link HttpPartSchema#DEFAULT}.
- * <br>Only used if serializer is schema-aware (e.g. {@link OpenApiSerializer}).
- * @return This object (for method chaining).
- * @throws RestCallException Error occurred.
- */
- public RestCall query(String name, Object value, boolean skipIfEmpty, HttpPartSerializer serializer, HttpPartSchema schema) throws RestCallException {
- if (serializer == null)
- serializer = client.getPartSerializer();
- if (schema == null)
- schema = HttpPartSchema.DEFAULT;
- boolean isMulti = isEmpty(name) || "*".equals(name) || value instanceof NameValuePairs;
- if (! isMulti) {
- if (canAdd(value, schema, skipIfEmpty))
- try {
- uriBuilder.addParameter(name, serializer.createPartSession(null).serialize(QUERY, schema, value));
- } catch (SchemaValidationException e) {
- throw new RestCallException(e, "Validation error on request query parameter ''{0}''=''{1}''", name, value);
- } catch (SerializeException e) {
- throw new RestCallException(e, "Serialization error on request query parameter ''{0}''", name);
- }
- } else if (value instanceof NameValuePairs) {
- for (NameValuePair p : (NameValuePairs)value) {
- String n = p.getName();
- String v = p.getValue();
- HttpPartSchema s = schema.getProperty(n);
- if (canAdd(v, s, skipIfEmpty))
- query(n, v, skipIfEmpty, serializer, s);
- }
- } else if (value instanceof Map) {
- for (Map.Entry<String,Object> p : ((Map<String,Object>) value).entrySet()) {
- String n = p.getKey();
- Object v = p.getValue();
- HttpPartSchema s = schema.getProperty(n);
- if (canAdd(v, s, skipIfEmpty))
- query(n, v, skipIfEmpty, serializer, s);
- }
- } else if (isBean(value)) {
- return query(name, toBeanMap(value), skipIfEmpty, serializer, schema);
- } else if (value instanceof Reader || value instanceof InputStream) {
- try {
- uriBuilder.setCustomQuery(read(value));
- } catch (IOException e) {
- throw new RestCallException(e);
- }
- } else if (value instanceof CharSequence) {
- String s = value.toString();
- if (isNotEmpty(s))
- uriBuilder.setCustomQuery(s);
- } else {
- throw new RestCallException("Invalid name ''{0}'' passed to query(name,value,skipIfEmpty) for data type ''{1}''", name, className(value));
- }
- return this;
- }
-
- /**
- * Adds a query parameter to the URI query.
- *
- * @param name The parameter name.
- * @param value The parameter value converted to a string using UON notation.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall query(String name, Object value) throws RestCallException {
- return query(name, value, false, null, null);
- }
-
- /**
- * Adds query parameters to the URI query.
- *
- * @param params The parameters. Values are converted to a string using UON notation.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall query(Map<String,Object> params) throws RestCallException {
- return query(null, params);
- }
-
- /**
- * Adds a query parameter to the URI query if the parameter value is not <jk>null</jk> or an empty string.
- *
- * <p>
- * NE = "not empty"
- *
- * @param name The parameter name.
- * @param value The parameter value converted to a string using UON notation.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall queryIfNE(String name, Object value) throws RestCallException {
- return query(name, value, true, null, null);
- }
-
- /**
- * Adds query parameters to the URI for any parameters that aren't null/empty.
- *
- * <p>
- * NE = "not empty"
- *
- * @param params The parameters. Values are converted to a string using UON notation.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall queryIfNE(Map<String,Object> params) throws RestCallException {
- return query(null, params, true, null, null);
- }
-
- /**
- * Sets a custom URI query.
- *
- * @param query The new URI query string.
- * @return This object (for method chaining).
- */
- public RestCall query(String query) {
- uriBuilder.setCustomQuery(query);
- return this;
- }
-
- /**
- * Adds a form data pair to this request to perform a URL-encoded form post.
- *
- * @param name
- * The parameter name.
- * Can be null/blank/* if the value is a {@link Map}, {@link NameValuePairs}, or bean.
- * @param value
- * The parameter value converted to a string using UON notation.
- * Can also be {@link Map}, {@link NameValuePairs}, or bean if the name is null/blank/*.
- * @param skipIfEmpty Don't add the pair if the value is empty.
- * @param serializer
- * The serializer to use for serializing the value to a string value.
- * If <jk>null</jk>, then the URL-encoding serializer defined on the client is used.
- * @param schema
- * The schema object that defines the format of the output.
- * <br>If <jk>null</jk>, defaults to the schema defined on the serializer.
- * <br>If that's also <jk>null</jk>, defaults to {@link HttpPartSchema#DEFAULT}.
- * <br>Only used if serializer is schema-aware (e.g. {@link OpenApiSerializer}).
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall formData(String name, Object value, boolean skipIfEmpty, HttpPartSerializer serializer, HttpPartSchema schema) throws RestCallException {
- if (formData == null)
- formData = new NameValuePairs();
- if (serializer == null)
- serializer = client.getPartSerializer();
- if (schema == null)
- schema = HttpPartSchema.DEFAULT;
- boolean isMulti = isEmpty(name) || "*".equals(name) || value instanceof NameValuePairs;
- if (! isMulti) {
- if (canAdd(value, schema, skipIfEmpty))
- formData.add(new SerializedNameValuePair(name, value, serializer, schema));
- } else if (value instanceof NameValuePairs) {
- for (NameValuePair p : (NameValuePairs)value) {
- String n = p.getName();
- String v = p.getValue();
- HttpPartSchema s = schema.getProperty(n);
- if (canAdd(v, s, skipIfEmpty))
- formData.add(p);
- }
- } else if (value instanceof Map) {
- for (Map.Entry<String,Object> p : ((Map<String,Object>) value).entrySet()) {
- String n = p.getKey();
- Object v = p.getValue();
- HttpPartSchema s = schema.getProperty(n);
- if (canAdd(v, s, skipIfEmpty))
- formData(n, v, skipIfEmpty, serializer, s);
- }
- } else if (isBean(value)) {
- return formData(name, toBeanMap(value), skipIfEmpty, serializer, schema);
- } else if (value instanceof Reader || value instanceof InputStream) {
- contentType("application/x-www-form-urlencoded");
- body(value);
- } else if (value instanceof CharSequence) {
- try {
- contentType("application/x-www-form-urlencoded");
- body(new StringEntity(value.toString()));
- } catch (UnsupportedEncodingException e) {}
- } else {
- throw new BasicRuntimeException("Invalid name ''{0}'' passed to formData(name,value,skipIfEmpty) for data type ''{1}''", name, className(value));
- }
- return this;
- }
-
- /**
- * Adds a form data pair to this request to perform a URL-encoded form post.
- *
- * @param name
- * The parameter name.
- * Can be null/blank if the value is a {@link Map} or {@link NameValuePairs}.
- * @param value
- * The parameter value converted to a string using UON notation.
- * Can also be a {@link Map} or {@link NameValuePairs}.
- * @return This object (for method chaining).
- * @throws RestCallException If name was null/blank and value wasn't a {@link Map} or {@link NameValuePairs}.
- */
- public RestCall formData(String name, Object value) throws RestCallException {
- return formData(name, value, false, null, null);
- }
-
- /**
- * Adds form data pairs to this request to perform a URL-encoded form post.
- *
- * @param nameValuePairs The name-value pairs of the request.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall formData(NameValuePairs nameValuePairs) throws RestCallException {
- return formData(null, nameValuePairs);
- }
-
- /**
- * Adds form data pairs to this request to perform a URL-encoded form post.
- *
- * @param params The parameters. Values are converted to a string using UON notation.
- * @return This object (for method chaining).
- * @throws RestCallException If name was null/blank and value wasn't a {@link Map} or {@link NameValuePairs}.
- */
- public RestCall formData(Map<String,Object> params) throws RestCallException {
- return formData(null, params);
- }
-
- /**
- * Adds a form data pair to the request if the parameter value is not <jk>null</jk> or an empty string.
- *
- * <p>
- * NE = "not empty"
- *
- * @param name The parameter name.
- * @param value The parameter value converted to a string using UON notation.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall formDataIfNE(String name, Object value) throws RestCallException {
- return formData(name, value, true, null, null);
- }
-
- /**
- * Adds form data parameters to the request for any parameters that aren't null/empty.
- *
- * <p>
- * NE = "not empty"
- *
- * @param params The parameters. Values are converted to a string using UON notation.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall formDataIfNE(Map<String,Object> params) throws RestCallException {
- return formData(null, params, true, null, null);
- }
-
- /**
- * Replaces a variable of the form <js>"{name}"</js> in the URL path with the specified value.
- *
- * @param name The path variable name.
- * @param value The replacement value.
- * @param serializer
- * The serializer to use for serializing the value to a string value.
- * If <jk>null</jk>, then the URL-encoding serializer defined on the client is used.
- * @param schema
- * The schema object that defines the format of the output.
- * <br>If <jk>null</jk>, defaults to the schema defined on the serializer.
- * <br>If that's also <jk>null</jk>, defaults to {@link HttpPartSchema#DEFAULT}.
- * <br>Only used if serializer is schema-aware (e.g. {@link OpenApiSerializer}).
- * @return This object (for method chaining).
- * @throws RestCallException If variable could not be found in path.
- */
- public RestCall path(String name, Object value, HttpPartSerializer serializer, HttpPartSchema schema) throws RestCallException {
- String path = uriBuilder.getPath();
- if (serializer == null)
- serializer = client.getPartSerializer();
- if (schema == null)
- schema = HttpPartSchema.DEFAULT;
- boolean isMulti = isEmpty(name) || "*".equals(name) || value instanceof NameValuePairs;
- if (! isMulti) {
- String var = "{" + name + "}";
- if (path.indexOf(var) == -1 && ! name.equals("/*"))
- throw new RestCallException("Path variable {"+name+"} was not found in path.");
- try {
- String p = null;
- if (name.equals("/*"))
- p = path.replaceAll("\\/\\*$", serializer.createPartSession(null).serialize(PATH, schema, value));
- else
- p = path.replace(var, serializer.createPartSession(null).serialize(PATH, schema, value));
- uriBuilder.setPath(p);
- } catch (SchemaValidationException e) {
- throw new RestCallException(e, "Validation error on request path parameter ''{0}''=''{1}''", name, value);
- } catch (SerializeException e) {
- throw new RestCallException(e, "Serialization error on request path parameter ''{0}''", name);
- }
- } else if (value instanceof NameValuePairs) {
- for (NameValuePair p : (NameValuePairs)value) {
- String n = p.getName();
- String v = p.getValue();
- HttpPartSchema s = schema.getProperty(n);
- path(n, v, serializer, s);
- }
- } else if (value instanceof Map) {
- for (Map.Entry<String,Object> p : ((Map<String,Object>) value).entrySet()) {
- String n = p.getKey();
- Object v = p.getValue();
- HttpPartSchema s = schema.getProperty(n);
- path(n, v, serializer, s);
- }
- } else if (isBean(value)) {
- return path(name, toBeanMap(value), serializer, schema);
- } else if (value != null) {
- throw new RestCallException("Invalid name ''{0}'' passed to path(name,value) for data type ''{1}''", name, className(value));
- }
- return this;
- }
-
- /**
- * Replaces a variable of the form <js>"{name}"</js> in the URL path with the specified value.
- *
- * @param name The path variable name.
- * @param value The replacement value.
- * @return This object (for method chaining).
- * @throws RestCallException If variable could not be found in path.
- */
- public RestCall path(String name, Object value) throws RestCallException {
- return path(name, value, null, null);
- }
-
- /**
- * Sets the URI user info.
- *
- * @param userInfo The new URI user info.
- * @return This object (for method chaining).
- */
- public RestCall userInfo(String userInfo) {
- uriBuilder.setUserInfo(userInfo);
- return this;
- }
-
- /**
- * Sets the URI user info.
- *
- * @param username The new URI username.
- * @param password The new URI password.
- * @return This object (for method chaining).
- */
- public RestCall userInfo(String username, String password) {
- uriBuilder.setUserInfo(username, password);
- return this;
- }
-
- /**
- * Specifies the part schema for the request body.
- *
- * <p>
- * This is only useful for schema-aware serializers such as {@link OpenApiSerializer}.
- *
- * @param value
- * The new part schema for the request body.
- * <br>Can be <jk>null</jk>.
- * @return This object (for method chaining).
- */
- public RestCall requestBodySchema(HttpPartSchema value) {
- this.requestBodySchema = value;
- return this;
- }
-
- /**
- * Specifies the part schema for the response body.
- *
- * <p>
- * This is only useful for schema-aware parsers such as {@link OpenApiParser}.
- *
- * @param value
- * The new part schema for the response body.
- * <br>Can be <jk>null</jk>.
- * @return This object (for method chaining).
- */
- public RestCall responseBodySchema(HttpPartSchema value) {
- this.responseBodySchema = value;
- return this;
- }
-
- /**
- * Sets the input for this REST call.
- *
- * @param input
- * The input to be sent to the REST resource (only valid for PUT and POST) requests.
- * <br>Can be of the following types:
- * <ul class='spaced-list'>
- * <li>
- * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource.
- * <li>
- * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource.
- * <li>
- * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the
- * {@link RestClient}.
- * <li>
- * {@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
- * <li>
- * {@link NameValuePairs} - Converted to a URL-encoded FORM post.
- * </ul>
- * @return This object (for method chaining).
- * @throws RestCallException If a retry was attempted, but the entity was not repeatable.
- */
- public RestCall body(Object input) throws RestCallException {
- this.input = input;
- this.hasInput = true;
- this.formData = null;
- return this;
- }
-
- /**
- * Specifies the serializer to use on this call.
- *
- * <p>
- * Overrides the serializer specified on the {@link RestClient}.
- *
- * @param serializer The serializer used to serialize POJOs to the body of the HTTP request.
- * @return This object (for method chaining).
- */
- public RestCall serializer(Serializer serializer) {
- this.serializer = serializer;
- return this;
- }
-
- /**
- * Specifies the parser to use on this call.
- *
- * <p>
- * Overrides the parser specified on the {@link RestClient}.
- *
- * @param parser The parser used to parse POJOs from the body of the HTTP response.
- * @return This object (for method chaining).
- */
- public RestCall parser(Parser parser) {
- this.parser = parser;
- return this;
- }
-
- //-----------------------------------------------------------------------------------------------------------------
- // HTTP headers
- //-----------------------------------------------------------------------------------------------------------------
-
- /**
- * Sets a header on the request.
- *
- * @param name
- * The header name.
- * The name can be null/empty if the value is a {@link Map}.
- * @param value The header value.
- * @param skipIfEmpty Don't add the header if the name is null/empty.
- * @param serializer
- * The serializer to use for serializing the value to a string value.
- * If <jk>null</jk>, then the URL-encoding serializer defined on the client is used.
- * @param schema
- * The schema object that defines the format of the output.
- * <br>If <jk>null</jk>, defaults to the schema defined on the serializer.
- * <br>If that's also <jk>null</jk>, defaults to {@link HttpPartSchema#DEFAULT}.
- * <br>Only used if serializer is schema-aware (e.g. {@link OpenApiSerializer}).
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall header(String name, Object value, boolean skipIfEmpty, HttpPartSerializer serializer, HttpPartSchema schema) throws RestCallException {
- if (serializer == null)
- serializer = client.getPartSerializer();
- if (schema == null)
- schema = HttpPartSchema.DEFAULT;
- boolean isMulti = isEmpty(name) || "*".equals(name) || value instanceof NameValuePairs;
- if (! isMulti) {
- if (canAdd(value, schema, skipIfEmpty))
- try {
- request.setHeader(name, serializer.createPartSession(null).serialize(HEADER, schema, value));
- } catch (SchemaValidationException e) {
- throw new RestCallException(e, "Validation error on request header parameter ''{0}''=''{1}''", name, value);
- } catch (SerializeException e) {
- throw new RestCallException(e, "Serialization error on request header parameter ''{0}''", name);
- }
- } else if (value instanceof NameValuePairs) {
- for (NameValuePair p : (NameValuePairs)value) {
- String n = p.getName();
- String v = p.getValue();
- HttpPartSchema s = schema.getProperty(n);
- if (canAdd(v, s, skipIfEmpty))
- header(n, v, skipIfEmpty, serializer, s);
- }
- } else if (value instanceof Map) {
- for (Map.Entry<String,Object> p : ((Map<String,Object>) value).entrySet()) {
- String n = p.getKey();
- Object v = p.getValue();
- HttpPartSchema s = schema.getProperty(n);
- if (canAdd(v, s, skipIfEmpty))
- header(n, v, skipIfEmpty, serializer, s);
- }
- } else if (isBean(value)) {
- return header(name, toBeanMap(value), skipIfEmpty, serializer, schema);
- } else {
- throw new RestCallException("Invalid name ''{0}'' passed to header(name,value,skipIfEmpty) for data type ''{1}''", name, className(value));
- }
- return this;
- }
-
-
- /**
- * Sets a header on the request.
- *
- * @param name
- * The header name.
- * The name can be null/empty if the value is a {@link Map}.
- * @param value The header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall header(String name, Object value) throws RestCallException {
- return header(name, value, false, null, null);
- }
-
- /**
- * Sets headers on the request.
- *
- * @param values The header values.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall headers(Map<String,Object> values) throws RestCallException {
- return header(null, values, false, null, null);
- }
-
- /**
- * Sets a header on the request if the value is not null/empty.
- *
- * <p>
- * NE = "not empty"
- *
- * @param name
- * The header name.
- * The name can be null/empty if the value is a {@link Map}.
- * @param value The header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall headerIfNE(String name, Object value) throws RestCallException {
- return header(name, value, true, null, null);
- }
-
- /**
- * Sets headers on the request if the values are not null/empty.
- *
- * <p>
- * NE = "not empty"
- *
- * @param values The header values.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall headersIfNE(Map<String,Object> values) throws RestCallException {
- return header(null, values, true, null, null);
- }
-
- /**
- * Sets the value for the <c>Accept</c> request header.
- *
- * <p>
- * This overrides the media type specified on the parser, but is overridden by calling
- * <code>header(<js>"Accept"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall accept(Object value) throws RestCallException {
- return header("Accept", value);
- }
-
- /**
- * Sets the value for the <c>Accept-Charset</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Accept-Charset"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall acceptCharset(Object value) throws RestCallException {
- return header("Accept-Charset", value);
- }
-
- /**
- * Sets the value for the <c>Accept-Encoding</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Accept-Encoding"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall acceptEncoding(Object value) throws RestCallException {
- return header("Accept-Encoding", value);
- }
-
- /**
- * Sets the value for the <c>Accept-Language</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Accept-Language"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall acceptLanguage(Object value) throws RestCallException {
- return header("Accept-Language", value);
- }
-
- /**
- * Sets the value for the <c>Authorization</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Authorization"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall authorization(Object value) throws RestCallException {
- return header("Authorization", value);
- }
-
- /**
- * Sets the value for the <c>Cache-Control</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Cache-Control"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall cacheControl(Object value) throws RestCallException {
- return header("Cache-Control", value);
- }
-
- /**
- * Sets the value for the <c>Connection</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Connection"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall connection(Object value) throws RestCallException {
- return header("Connection", value);
- }
-
- /**
- * Sets the value for the <c>Content-Length</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Content-Length"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall contentLength(Object value) throws RestCallException {
- return header("Content-Length", value);
- }
-
- /**
- * Sets the value for the <c>Content-Type</c> request header.
- *
- * <p>
- * This overrides the media type specified on the serializer, but is overridden by calling
- * <code>header(<js>"Content-Type"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall contentType(Object value) throws RestCallException {
- return header("Content-Type", value);
- }
-
- /**
- * Sets the value for the <c>Date</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Date"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall date(Object value) throws RestCallException {
- return header("Date", value);
- }
-
- /**
- * Sets the value for the <c>Expect</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Expect"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall expect(Object value) throws RestCallException {
- return header("Expect", value);
- }
-
- /**
- * Sets the value for the <c>Forwarded</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Forwarded"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall forwarded(Object value) throws RestCallException {
- return header("Forwarded", value);
- }
-
- /**
- * Sets the value for the <c>From</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"From"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall from(Object value) throws RestCallException {
- return header("From", value);
- }
-
- /**
- * Sets the value for the <c>Host</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Host"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall host(Object value) throws RestCallException {
- return header("Host", value);
- }
-
- /**
- * Sets the value for the <c>If-Match</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-Match"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall ifMatch(Object value) throws RestCallException {
- return header("If-Match", value);
- }
-
- /**
- * Sets the value for the <c>If-Modified-Since</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-Modified-Since"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall ifModifiedSince(Object value) throws RestCallException {
- return header("If-Modified-Since", value);
- }
-
- /**
- * Sets the value for the <c>If-None-Match</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-None-Match"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall ifNoneMatch(Object value) throws RestCallException {
- return header("If-None-Match", value);
- }
-
- /**
- * Sets the value for the <c>If-Range</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-Range"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall ifRange(Object value) throws RestCallException {
- return header("If-Range", value);
- }
-
- /**
- * Sets the value for the <c>If-Unmodified-Since</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-Unmodified-Since"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall ifUnmodifiedSince(Object value) throws RestCallException {
- return header("If-Unmodified-Since", value);
- }
-
- /**
- * Sets the value for the <c>Max-Forwards</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Max-Forwards"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall maxForwards(Object value) throws RestCallException {
- return header("Max-Forwards", value);
- }
-
- /**
- * Sets the value for the <c>Origin</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Origin"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall origin(Object value) throws RestCallException {
- return header("Origin", value);
- }
-
- /**
- * Sets the value for the <c>Pragma</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Pragma"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall pragma(Object value) throws RestCallException {
- return header("Pragma", value);
- }
-
- /**
- * Sets the value for the <c>Proxy-Authorization</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Proxy-Authorization"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall proxyAuthorization(Object value) throws RestCallException {
- return header("Proxy-Authorization", value);
- }
-
- /**
- * Sets the value for the <c>Range</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Range"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall range(Object value) throws RestCallException {
- return header("Range", value);
- }
-
- /**
- * Sets the value for the <c>Referer</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Referer"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall referer(Object value) throws RestCallException {
- return header("Referer", value);
- }
-
- /**
- * Sets the value for the <c>TE</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"TE"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall te(Object value) throws RestCallException {
- return header("TE", value);
- }
-
- /**
- * Sets the value for the <c>User-Agent</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"User-Agent"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall userAgent(Object value) throws RestCallException {
- return header("User-Agent", value);
- }
-
- /**
- * Sets the value for the <c>Upgrade</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Upgrade"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall upgrade(Object value) throws RestCallException {
- return header("Upgrade", value);
- }
-
- /**
- * Sets the value for the <c>Via</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Via"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall via(Object value) throws RestCallException {
- return header("Via", value);
- }
-
- /**
- * Sets the value for the <c>Warning</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Warning"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall warning(Object value) throws RestCallException {
- return header("Warning", value);
- }
-
- /**
- * Sets the client version by setting the value for the <js>"X-Client-Version"</js> header.
- *
- * @param version The version string (e.g. <js>"1.2.3"</js>)
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall clientVersion(String version) throws RestCallException {
- return header("X-Client-Version", version);
- }
-
- /**
- * Make this call retryable if an error response (>=400) is received.
- *
- * @param retries The number of retries to attempt.
- * @param interval The time in milliseconds between attempts.
- * @param retryOn
- * Optional object used for determining whether a retry should be attempted.
- * If <jk>null</jk>, uses {@link RetryOn#DEFAULT}.
- * @return This object (for method chaining).
- * @throws RestCallException If current entity is not repeatable.
- */
- public RestCall retryable(int retries, long interval, RetryOn retryOn) throws RestCallException {
- if (request instanceof HttpEntityEnclosingRequestBase) {
- if (input != null && input instanceof HttpEntity) {
- HttpEntity e = (HttpEntity)input;
- if (e != null && ! e.isRepeatable())
- throw new RestCallException("Attempt to make call retryable, but entity is not repeatable.");
- }
- }
- this.retries = retries;
- this.retryInterval = interval;
- this.retryOn = (retryOn == null ? RetryOn.DEFAULT : retryOn);
- return this;
-
- }
-
- /**
- * For this call, allow automatic redirects when a 302 or 307 occurs when performing a POST.
- *
- * <p>
- * Note that this can be inefficient since the POST body needs to be serialized twice.
- * The preferred approach if possible is to use the {@link LaxRedirectStrategy} strategy on the underlying HTTP
- * client.
- * However, this method is provided if you don't have access to the underlying client.
- *
- * @param b Redirect flag.
- * @return This object (for method chaining).
- */
- public RestCall allowRedirectsOnPosts(boolean b) {
- this.allowRedirectsOnPosts = b;
- return this;
- }
-
- /**
- * Specify the number of redirects to follow before throwing an exception.
- *
- * @param maxAttempts Allow a redirect to occur this number of times.
- * @return This object (for method chaining).
- */
- public RestCall redirectMaxAttempts(int maxAttempts) {
- this.redirectOnPostsTries = maxAttempts;
- return this;
- }
-
- /**
- * Add an interceptor for this call only.
- *
- * @param interceptor The interceptor to add to this call.
- * @return This object (for method chaining).
- */
- public RestCall interceptor(RestCallInterceptor interceptor) {
- interceptors.add(interceptor);
- interceptor.onInit(this);
- return this;
- }
-
- /**
- * Pipes the request output to the specified writer when {@link #run()} is called.
- *
- * <p>
- * The writer is not closed.
- *
- * <p>
- * This method can be called multiple times to pipe to multiple writers.
- *
- * @param w The writer to pipe the output to.
- * @return This object (for method chaining).
- */
- public RestCall pipeTo(Writer w) {
- return pipeTo(w, false);
- }
-
- /**
- * Pipe output from response to the specified writer when {@link #run()} is called.
- *
- * <p>
- * This method can be called multiple times to pipe to multiple writers.
- *
- * @param w The writer to write the output to.
- * @param close Close the writer when {@link #close()} is called.
- * @return This object (for method chaining).
- */
- public RestCall pipeTo(Writer w, boolean close) {
- return pipeTo(null, w, close);
- }
-
- /**
- * Pipe output from response to the specified writer when {@link #run()} is called and associate that writer with an
- * ID so it can be retrieved through {@link #getWriter(String)}.
- *
- * <p>
- * This method can be called multiple times to pipe to multiple writers.
- *
- * @param id A string identifier that can be used to retrieve the writer using {@link #getWriter(String)}
- * @param w The writer to write the output to.
- * @param close Close the writer when {@link #close()} is called.
- * @return This object (for method chaining).
- */
- public RestCall pipeTo(String id, Writer w, boolean close) {
- writers.add(id, w, close);
- return this;
- }
-
- /**
- * Retrieves a writer associated with an ID via {@link #pipeTo(String, Writer, boolean)}
- *
- * @param id A string identifier that can be used to retrieve the writer using {@link #getWriter(String)}
- * @return The writer, or <jk>null</jk> if no writer is associated with that ID.
- */
- public Writer getWriter(String id) {
- return writers.getWriter(id);
- }
-
- /**
- * When output is piped to writers, flush the writers after every line of output.
- *
- * @return This object (for method chaining).
- */
- public RestCall byLines() {
- this.byLines = true;
- return this;
- }
-
- /**
- * Pipes the request output to the specified output stream when {@link #run()} is called.
- *
- * <p>
- * The output stream is not closed.
- *
- * <p>
- * This method can be called multiple times to pipe to multiple output streams.
- *
- * @param os The output stream to pipe the output to.
- * @return This object (for method chaining).
- */
- public RestCall pipeTo(OutputStream os) {
- return pipeTo(os, false);
- }
-
- /**
- * Pipe output from response to the specified output stream when {@link #run()} is called.
- *
- * <p>
- * This method can be called multiple times to pipe to multiple output stream.
- *
- * @param os The output stream to write the output to.
- * @param close Close the output stream when {@link #close()} is called.
- * @return This object (for method chaining).
- */
- public RestCall pipeTo(OutputStream os, boolean close) {
- return pipeTo(null, os, close);
- }
-
- /**
- * Pipe output from response to the specified output stream when {@link #run()} is called and associate
- * that output stream with an ID so it can be retrieved through {@link #getOutputStream(String)}.
- *
- * <p>
- * This method can be called multiple times to pipe to multiple output stream.
- *
- * @param id A string identifier that can be used to retrieve the output stream using {@link #getOutputStream(String)}
- * @param os The output stream to write the output to.
- * @param close Close the output stream when {@link #close()} is called.
- * @return This object (for method chaining).
- */
- public RestCall pipeTo(String id, OutputStream os, boolean close) {
- outputStreams.add(id, os, close);
- return this;
- }
-
- /**
- * Retrieves an output stream associated with an ID via {@link #pipeTo(String, OutputStream, boolean)}
- *
- * @param id A string identifier that can be used to retrieve the writer using {@link #getWriter(String)}
- * @return The writer, or <jk>null</jk> if no writer is associated with that ID.
- */
- public OutputStream getOutputStream(String id) {
- return outputStreams.getOutputStream(id);
- }
-
- /**
- * Prevent {@link RestCallException RestCallExceptions} from being thrown when HTTP status 400+ is encountered.
- *
- * @return This object (for method chaining).
- */
- public RestCall ignoreErrors() {
- this.ignoreErrors = true;
- return this;
- }
-
- /**
- * Stores the response text so that it can later be captured using {@link #getCapturedResponse()}.
- *
- * <p>
- * This method should only be called once. Multiple calls to this method are ignored.
- *
- * @return This object (for method chaining).
- */
- public RestCall captureResponse() {
- if (capturedResponseWriter == null) {
- capturedResponseWriter = new StringWriter();
- writers.add(capturedResponseWriter, false);
- }
- return this;
- }
-
-
- /**
- * Look for the specified regular expression pattern in the response output.
- *
- * <p>
- * Causes a {@link RestCallException} to be thrown if the specified pattern is found in the output.
- *
- * <p>
- * This method uses {@link #getCapturedResponse()} to read the response text and so does not affect the other output
- * methods such as {@link #getResponseAsString()}.
- *
- * <h5 class='section'>Example:</h5>
- * <p class='bcode w800'>
- * <jc>// Throw a RestCallException if FAILURE or ERROR is found in the output.</jc>
- * restClient.doGet(<jsf>URL</jsf>)
- * .failurePattern(<js>"FAILURE|ERROR"</js>)
- * .run();
- * </p>
- *
- * @param errorPattern A regular expression to look for in the response output.
- * @return This object (for method chaining).
- */
- public RestCall failurePattern(final String errorPattern) {
- responsePattern(
- new ResponsePattern(errorPattern) {
- @Override
- public void onMatch(RestCall rc, Matcher m) throws RestCallException {
- throw new RestCallException("Failure pattern detected.");
- }
- }
- );
- return this;
- }
-
- /**
- * Look for the specified regular expression pattern in the response output.
- *
- * <p>
- * Causes a {@link RestCallException} to be thrown if the specified pattern is not found in the output.
- *
- * <p>
- * This method uses {@link #getCapturedResponse()} to read the response text and so does not affect the other output
- * methods such as {@link #getResponseAsString()}.
- *
- * <h5 class='section'>Example:</h5>
- * <p class='bcode w800'>
- * <jc>// Throw a RestCallException if SUCCESS is not found in the output.</jc>
- * restClient.doGet(<jsf>URL</jsf>)
- * .successPattern(<js>"SUCCESS"</js>)
- * .run();
- * </p>
- *
- * @param successPattern A regular expression to look for in the response output.
- * @return This object (for method chaining).
- */
- public RestCall successPattern(String successPattern) {
- responsePattern(
- new ResponsePattern(successPattern) {
- @Override
- public void onNoMatch(RestCall rc) throws RestCallException {
- throw new RestCallException("Success pattern not detected.");
- }
- }
- );
- return this;
- }
-
- /**
- * Adds a response pattern finder to look for regular expression matches in the response output.
- *
- * <p>
- * This method can be called multiple times to add multiple response pattern finders.
- *
- * <p>
- * {@link ResponsePattern ResponsePatterns} use the {@link #getCapturedResponse()} to read the response text and so
- * does not affect the other output methods such as {@link #getResponseAsString()}.
- *
- * @param responsePattern The response pattern finder.
- * @return This object (for method chaining).
- */
- public RestCall responsePattern(final ResponsePattern responsePattern) {
- captureResponse();
- interceptor(
- new RestCallInterceptor() {
- @Override
- public void onClose(RestCall restCall) throws RestCallException {
- responsePattern.match(RestCall.this);
- }
- }
- );
- return this;
- }
-
- /**
- * Set configuration settings on this request.
- *
- * <p>
- * Use {@link RequestConfig#custom()} to create configuration parameters for the request.
- *
- * @param config The new configuration settings for this request.
- * @return This object (for method chaining).
- */
- public RestCall setConfig(RequestConfig config) {
- this.request.setConfig(config);
- return this;
- }
-
- /**
- * Method used to execute an HTTP response where you're only interested in the HTTP response code.
- *
- * <p>
- * The response entity is discarded unless one of the pipe methods have been specified to pipe the output to an
- * output stream or writer.
- *
- * <h5 class='section'>Example:</h5>
- * <p class='bcode w800'>
- * <jk>try</jk> {
- * RestClient client = <jk>new</jk> RestClient();
- * <jk>int</jk> rc = client.doGet(url).execute();
- * <jc>// Succeeded!</jc>
- * } <jk>catch</jk> (RestCallException e) {
- * <jc>// Failed!</jc>
- * }
- * </p>
- *
- * @return The HTTP status code.
- * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt.
- */
- public int run() throws RestCallException {
- connect();
- try {
- StatusLine status = response.getStatusLine();
- int sc = status.getStatusCode();
- if (sc >= 400 && ! ignoreErrors)
- throw new RestCallException(sc, status.getReasonPhrase(), request.getMethod(), request.getURI(), getResponseAsString()).setHttpResponse(response);
- if (outputStreams.size() > 0 || writers.size() > 0)
- getReader();
- return sc;
- } catch (RestCallException e) {
- isFailed = true;
- throw e;
- } catch (IOException e) {
- isFailed = true;
- throw new RestCallException(e).setHttpResponse(response);
- } finally {
- close();
- }
- }
-
- /**
- * Same as {@link #run()} but allows you to run the call asynchronously.
- *
- * @return The HTTP status code.
- * @throws RestCallException If the executor service was not defined.
- * @see RestClientBuilder#executorService(ExecutorService, boolean) for defining the executor service for creating
- * {@link Future Futures}.
- */
- public Future<Integer> runFuture() throws RestCallException {
- return client.getExecutorService(true).submit(
- new Callable<Integer>() {
- @Override /* Callable */
- public Integer call() throws Exception {
- return run();
- }
- }
- );
- }
-
- /**
- * Connects to the REST resource.
- *
- * <p>
- * If this is a <c>PUT</c> or <c>POST</c>, also sends the input to the remote resource.<br>
- *
- * <p>
- * Typically, you would only call this method if you're not interested in retrieving the body of the HTTP response.
- * Otherwise, you're better off just calling one of the {@link #getReader()}/{@link #getResponse(Class)}/{@link #pipeTo(Writer)}
- * methods directly which automatically call this method already.
- *
- * @return This object (for method chaining).
- * @throws RestCallException If an exception or <c>400+</c> HTTP status code occurred during the connection attempt.
- */
- public RestCall connect() throws RestCallException {
- return connect(null);
- }
-
- private RestCall connect(ClassMeta<?> bodyType) throws RestCallException {
-
- if (isConnected)
- return this;
- isConnected = true;
-
- try {
- HttpEntityEnclosingRequestBase request2 = request instanceof HttpEntityEnclosingRequestBase ? (HttpEntityEnclosingRequestBase)request : null;
-
- request.setURI(uriBuilder.build());
-
- if (hasInput || formData != null) {
-
- if (hasInput && formData != null)
- throw new RestCallException("Both input and form data found on same request.");
-
- if (request2 == null)
- throw new RestCallException(0, "Method does not support content entity.", request.getMethod(), request.getURI(), null);
-
- HttpEntity entity = null;
- if (formData != null)
- entity = new UrlEncodedFormEntity(formData);
- else if (input instanceof NameValuePairs)
- entity = new UrlEncodedFormEntity((NameValuePairs)input);
- else if (input instanceof HttpEntity)
- entity = (HttpEntity)input;
- else if (input instanceof Reader)
- entity = new StringEntity(IOUtils.read((Reader)input), getRequestContentType(TEXT_PLAIN));
- else if (input instanceof InputStream)
- entity = new InputStreamEntity((InputStream)input, getRequestContentType(ContentType.APPLICATION_OCTET_STREAM));
- else if (serializer != null)
- entity = new RestRequestEntity(input, serializer, requestBodySchema);
- else if (partSerializer != null)
- entity = new StringEntity(partSerializer.createPartSession(null).serialize(BODY, (HttpPartSchema)null, input), getRequestContentType(TEXT_PLAIN));
- else
- entity = new StringEntity(getBeanContext().getClassMetaForObject(input).toString(input), getRequestContentType(TEXT_PLAIN));
-
- if (retries > 1 && ! entity.isRepeatable())
- throw new RestCallException("Rest call set to retryable, but entity is not repeatable.");
-
- request2.setEntity(entity);
- }
-
- int sc = 0;
- while (retries > 0) {
- retries--;
- Exception ex = null;
- try {
- if (request2 != null)
- response = client.execute(request2);
- else
- response = client.execute(request);
- sc = (response == null || response.getStatusLine() == null) ? -1 : response.getStatusLine().getStatusCode();
- } catch (Exception e) {
- ex = e;
- sc = -1;
- if (response != null)
- EntityUtils.consumeQuietly(response.getEntity());
- }
- if (! retryOn.onResponse(response))
- retries = 0;
- if (retries > 0) {
- for (RestCallInterceptor rci : interceptors)
- rci.onRetry(this, sc, request, response, ex);
- request.reset();
- long w = retryInterval;
- synchronized(this) {
- wait(w);
- }
- } else if (ex != null) {
- throw ex;
- }
- }
- for (RestCallInterceptor rci : interceptors)
- rci.onConnect(this, sc, request, response);
- if (response == null)
- throw new RestCallException("HttpClient returned a null response");
- StatusLine sl = response.getStatusLine();
- String method = request.getMethod();
- sc = sl.getStatusCode(); // Read it again in case it was changed by one of the interceptors.
-
- int[] expected = new int[0];
- if (bodyType != null && bodyType.hasAnnotation(Response.class))
- expected = bodyType.getLastAnnotation(Response.class).code();
-
- if (sc >= 400 && ! ignoreErrors && ! ArrayUtils.contains(sc, expected)) {
- throw new RestCallException(sc, sl.getReasonPhrase(), method, request.getURI(), getResponseAsString())
- .setServerException(response.getFirstHeader("Exception-Name"), response.getFirstHeader("Exception-Message"), response.getFirstHeader("Exception-Trace"))
- .setHttpResponse(response);
- }
- if ((sc == 307 || sc == 302) && allowRedirectsOnPosts && method.equalsIgnoreCase("POST") && ! ArrayUtils.contains(sc, expected)) {
- if (redirectOnPostsTries-- < 1)
- throw new RestCallException(sc, "Maximum number of redirects occurred. Location header: " + response.getFirstHeader("Location"), method, request.getURI(), getResponseAsString());
- Header h = response.getFirstHeader("Location");
- if (h != null) {
- reset();
- request.setURI(URI.create(h.getValue()));
- retries++; // Redirects should affect retries.
- connect();
- }
- }
-
- } catch (RestCallException e) {
- isFailed = true;
- close();
- throw e;
- } catch (Exception e) {
- isFailed = true;
- close();
- throw new RestCallException(e).setHttpResponse(response);
- }
-
- return this;
- }
-
- private ContentType getRequestContentType(ContentType def) {
- Header h = request.getFirstHeader("Content-Type");
- if (h != null) {
- String s = h.getValue();
- if (! isEmpty(s))
- return ContentType.create(s);
- }
- return def;
- }
-
- private void reset() {
- if (response != null)
- EntityUtils.consumeQuietly(response.getEntity());
- request.reset();
- isConnected = false;
- isClosed = false;
- isFailed = false;
- if (capturedResponseWriter != null)
- capturedResponseWriter.getBuffer().setLength(0);
- }
-
- /**
- * Connects to the remote resource (if <c>connect()</c> hasn't already been called) and returns the HTTP
- * response message body as a reader.
- *
- * <p>
- * If an {@link Encoder} has been registered with the {@link RestClient}, then the underlying input stream will be
- * wrapped in the encoded stream (e.g. a <c>GZIPInputStream</c>).
- *
- * <p>
- * If present, automatically handles the <c>charset</c> value in the <c>Content-Type</c> response header.
- *
- * <p>
- * <b>IMPORTANT:</b> It is your responsibility to close this reader once you have finished with it.
- *
- * @return
- * The HTTP response message body reader.
- * <jk>null</jk> if response was successful but didn't contain a body (e.g. HTTP 204).
- * @throws IOException If an exception occurred while streaming was already occurring.
- */
- public Reader getReader() throws IOException {
- InputStream is = getInputStream();
- if (is == null)
- return null;
-
- // Figure out what the charset of the response is.
- String cs = null;
- Header contentType = response.getLastHeader("Content-Type");
- String ct = contentType == null ? null : contentType.getValue();
-
- // First look for "charset=" in Content-Type header of response.
- if (ct != null && ct.contains("charset="))
- cs = ct.substring(ct.indexOf("charset=")+8).trim();
-
- if (cs == null)
- cs = "UTF-8";
-
- if (writers.size() > 0) {
- try (Reader isr = new InputStreamReader(is, cs)) {
- StringWriter sw = new StringWriter();
- writers.add(sw, true);
- IOPipe.create(isr, writers).byLines(byLines).run();
- return new StringReader(sw.toString());
- }
- }
-
- return new InputStreamReader(is, cs);
- }
-
- /**
- * Returns the response text as a string if {@link #captureResponse()} was called on this object.
- *
- * <p>
- * Note that while similar to {@link #getResponseAsString()}, this method can be called multiple times to retrieve
- * the response text multiple times.
- *
- * <p>
- * Note that this method returns <jk>null</jk> if you have not called one of the methods that cause the response to
- * be processed. (e.g. {@link #run()}, {@link #getResponse()}, {@link #getResponseAsString()}.
- *
- * @return The captured response, or <jk>null</jk> if {@link #captureResponse()} has not been called.
- * @throws IllegalStateException If trying to call this method before the response is consumed.
- */
- public String getCapturedResponse() {
- if (! isClosed)
- throw new IllegalStateException("This method cannot be called until the response has been consumed.");
- if (capturedResponse == null && capturedResponseWriter != null && capturedResponseWriter.getBuffer().length() > 0)
- capturedResponse = capturedResponseWriter.toString();
- return capturedResponse;
- }
-
- /**
- * Returns the value of the <c>Content-Length</c> header.
- *
- * @return The value of the <c>Content-Length</c> header, or <c>-1</c> if header is not present.
- * @throws IOException Thrown by underlying stream.
- */
- public int getContentLength() throws IOException {
- connect();
- Header h = response.getLastHeader("Content-Length");
- if (h == null)
- return -1;
- long l = Long.parseLong(h.getValue());
- if (l > Integer.MAX_VALUE)
- return Integer.MAX_VALUE;
- return (int)l;
- }
-
- /**
- * Connects to the remote resource (if <c>connect()</c> hasn't already been called) and returns the HTTP
- * response message body as an input stream.
- *
- * <p>
- * If an {@link Encoder} has been registered with the {@link RestClient}, then the underlying input stream will be
- * wrapped in the encoded stream (e.g. a <c>GZIPInputStream</c>).
- *
- * <p>
- * <b>IMPORTANT:</b> It is your responsibility to close this reader once you have finished with it.
- *
- * @return
- * The HTTP response message body input stream. <jk>null</jk> if response was successful but didn't contain
- * a body (e.g. HTTP 204).
- * @throws IOException If an exception occurred while streaming was already occurring.
- * @throws IllegalStateException If an attempt is made to read the response more than once.
- */
- @SuppressWarnings("resource")
- public InputStream getInputStream() throws IOException {
- if (isClosed)
- throw new IllegalStateException("Method cannot be called. Response has already been consumed.");
- connect();
- if (response == null)
- throw new RestCallException("Response was null");
- if (response.getEntity() == null) // HTTP 204 results in no content.
- return null;
-
- softClose();
-
- InputStream is = new EofSensorInputStream(response.getEntity().getContent(), new EofSensorWatcher() {
- @Override
- public boolean eofDetected(InputStream wrapped) throws IOException {
- RestCall.this.forceClose();
- return true;
- }
- @Override
- public boolean streamClosed(InputStream wrapped) throws IOException {
- RestCall.this.forceClose();
- return true;
- }
- @Override
- public boolean streamAbort(InputStream wrapped) throws IOException {
- RestCall.this.forceClose();
- return true;
- }
- });
-
- if (outputStreams.size() > 0) {
- ByteArrayInOutStream baios = new ByteArrayInOutStream();
- outputStreams.add(baios, true);
- IOPipe.create(is, baios).run();
- is.close();
- return baios.getInputStream();
- }
- return is;
- }
-
- /**
- * Connects to the remote resource (if {@code connect()} hasn't already been called) and returns the HTTP response
- * message body as plain text.
- *
- * <p>
- * The response entity is discarded unless one of the pipe methods have been specified to pipe the output to an
- * output stream or writer.
- *
- * @return The response as a string.
- * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt.
- * @throws IOException If an exception occurred while streaming was already occurring.
- */
- public String getResponseAsString() throws IOException {
- try (Reader r = getReader()) {
- return read(r).toString();
- } catch (IOException e) {
- isFailed = true;
- close();
- throw e;
- }
- }
-
- /**
- * Connects to the remote resource (if {@code connect()} hasn't already been called) and returns the value of
- * an HTTP header on the response.
- *
- * <p>
- * Useful if you're only interested in a particular header value from the response and not the body of the response.
- *
- * <p>
- * The response entity is discarded unless one of the pipe methods have been specified to pipe the output to an
- * output stream or writer.
- *
- * @param name The header name.
- * @return The response header as a string, or <jk>null</jk> if the header was not found.
- * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt.
- * @throws IOException If an exception occurred while streaming was already occurring.
- */
- public String getResponseHeader(String name) throws IOException {
- try {
- HttpResponse r = getResponse();
- Header h = r.getFirstHeader(name);
- return h == null ? null : h.getValue();
- } catch (IOException e) {
- isFailed = true;
- close();
- throw e;
- }
- }
-
- /**
- * Same as {@link #getResponseHeader(String)} except parses the header value using the specified part parser and schema.
- *
- * @param name The header name.
- * @param partParser The part parser to use for parsing the header.
- * @param schema The part schema. Can be <jk>null</jk>.
- * @param c The type to convert the part into.
- * @return The parsed part.
- * @throws IOException Thrown by underlying stream.
- * @throws ParseException Header value could not be parsed into the specified type.
- */
- public <T> T getResponseHeader(HttpPartParser partParser, HttpPartSchema schema, String name, Class<T> c) throws IOException, ParseException {
- return getResponseHeader(partParser, schema, name, (Type)c);
- }
-
- /**
- * Same as {@link #getResponseHeader(String)} except parses the header value using the specified part parser and schema.
- *
- * @param name The header name.
- * @param partParser The part parser to use for parsing the header.
- * @param schema The part schema. Can be <jk>null</jk>.
- * @param type The type to convert the part into.
- * @param args The type arguments to convert the part into.
- * @return The parsed part.
- * @throws IOException Thrown by underlying stream.
- * @throws ParseException Header value could not be parsed into the specified type.
- */
- public <T> T getResponseHeader(HttpPartParser partParser, HttpPartSchema schema, String name, Type type, Type...args) throws IOException, ParseException {
- try {
- HttpResponse r = getResponse();
- Header h = r.getFirstHeader(name);
- if (h == null)
- return null;
- String hs = h.getValue();
- if (partParser == null)
- partParser = client.getPartParser();
- return partParser.createPartSession(null).parse(HEADER, schema, hs, partParser.getClassMeta(type, args));
- } catch (IOException e) {
- isFailed = true;
- close();
- throw e;
- }
- }
-
- /**
- * Connects to the remote resource (if {@code connect()} hasn't already been called) and returns the HTTP response code.
- *
- * <p>
- * Useful if you're only interested in the status code and not the body of the response.
- *
- * <p>
- * The response entity is discarded unless one of the pipe methods have been specified to pipe the output to an
- * output stream or writer.
- *
- * @return The response code.
- * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt.
- * @throws IOException If an exception occurred while streaming was already occurring.
- */
- public int getResponseCode() throws IOException {
- return run();
- }
-
- /**
- * Same as {@link #getResponse(Class)} but allows you to run the call asynchronously.
- *
- * @return The response as a string.
- * @throws RestCallException If the executor service was not defined.
- * @see
- * RestClientBuilder#executorService(ExecutorService, boolean) for defining the executor service for creating
- * {@link Future Futures}.
- */
- public Future<String> getResponseAsStringFuture() throws RestCallException {
- return client.getExecutorService(true).submit(
- new Callable<String>() {
- @Override /* Callable */
- public String call() throws Exception {
- return getResponseAsString();
- }
- }
- );
- }
-
- /**
- * Same as {@link #getResponse(Type, Type...)} except optimized for a non-parameterized class.
- *
- * <p>
- * This is the preferred parse method for simple types since you don't need to cast the results.
- *
- * <h5 class='section'>Examples:</h5>
- * <p class='bcode w800'>
- * <jc>// Parse into a string.</jc>
- * String s = restClient.doGet(url).getResponse(String.<jk>class</jk>);
- *
- * <jc>// Parse into a bean.</jc>
- * MyBean b = restClient.doGet(url).getResponse(MyBean.<jk>class</jk>);
- *
- * <jc>// Parse into a bean array.</jc>
- * MyBean[] ba = restClient.doGet(url).getResponse(MyBean[].<jk>class</jk>);
- *
- * <jc>// Parse into a linked-list of objects.</jc>
- * List l = restClient.doGet(url).getResponse(LinkedList.<jk>class</jk>);
- *
- * <jc>// Parse into a map of object keys/values.</jc>
- * Map m = restClient.doGet(url).getResponse(TreeMap.<jk>class</jk>);
- * </p>
- *
- * <ul class='notes'>
- * <li>
- * You can also specify any of the following types:
- * <ul>
- * <li>{@link HttpResponse} - Returns the raw <c>HttpResponse</c> returned by the inner <c>HttpClient</c>.
- * <li>{@link Reader} - Returns access to the raw reader of the response.
- * <li>{@link InputStream} - Returns access to the raw input stream of the response.
- * </ul>
- * </ul>
- *
- * @param <T>
- * The class type of the object being created.
- * See {@link #getResponse(Type, Type...)} for details.
- * @param type The object type to create.
- * @return The parsed object.
- * @throws ParseException
- * If the input contains a syntax error or is malformed, or is not valid for the specified type.
- * @throws IOException If a connection error occurred.
- */
- public <T> T getResponse(Class<T> type) throws IOException, ParseException {
- BeanContext bc = parser;
- if (bc == null)
- bc = BeanContext.DEFAULT;
- return getResponseInner(bc.getClassMeta(type));
- }
-
- /**
- * Same as {@link #getResponse(Class)} but allows you to run the call asynchronously.
- *
- * @param <T>
- * The class type of the object being created.
- * See {@link #getResponse(Type, Type...)} for details.
- * @param type The object type to create.
- * @return The parsed object.
- * @throws RestCallException If the executor service was not defined.
- * @see
- * RestClientBuilder#executorService(ExecutorService, boolean) for defining the executor service for creating
- * {@link Future Futures}.
- */
- public <T> Future<T> getResponseFuture(final Class<T> type) throws RestCallException {
- return client.getExecutorService(true).submit(
- new Callable<T>() {
- @Override /* Callable */
- public T call() throws Exception {
- return getResponse(type);
- }
- }
- );
- }
-
- /**
- * Parses HTTP body into the specified object type.
- *
- * <p>
- * The type can be a simple type (e.g. beans, strings, numbers) or parameterized type (collections/maps).
- *
- * <h5 class='section'>Examples:</h5>
- * <p class='bcode w800'>
- * <jc>// Parse into a linked-list of strings.</jc>
- * List l = restClient.doGet(url).getResponse(LinkedList.<jk>class</jk>, String.<jk>class</jk>);
- *
- * <jc>// Parse into a linked-list of beans.</jc>
- * List l = restClient.doGet(url).getResponse(LinkedList.<jk>class</jk>, MyBean.<jk>class</jk>);
- *
- * <jc>// Parse into a linked-list of linked-lists of strings.</jc>
- * List l = restClient.doGet(url).getResponse(LinkedList.<jk>class</jk>, LinkedList.<jk>class</jk>, String.<jk>class</jk>);
- *
- * <jc>// Parse into a map of string keys/values.</jc>
- * Map m = restClient.doGet(url).getResponse(TreeMap.<jk>class</jk>, String.<jk>class</jk>, String.<jk>class</jk>);
- *
- * <jc>// Parse into a map containing string keys and values of lists containing beans.</jc>
- * Map m = restClient.doGet(url).getResponse(TreeMap.<jk>class</jk>, String.<jk>class</jk>, List.<jk>class</jk>, MyBean.<jk>class</jk>);
- * </p>
- *
- * <p>
- * <c>Collection</c> classes are assumed to be followed by zero or one objects indicating the element type.
- *
- * <p>
- * <c>Map</c> classes are assumed to be followed by zero or two meta objects indicating the key and value types.
- *
- * <p>
- * The array can be arbitrarily long to indicate arbitrarily complex data structures.
- *
- * <ul class='notes'>
- * <li>
- * Use the {@link #getResponse(Class)} method instead if you don't need a parameterized map/collection.
- * <li>
- * You can also specify any of the following types:
- * <ul>
- * <li>{@link HttpResponse} - Returns the raw <c>HttpResponse</c> returned by the inner <c>HttpClient</c>.
- * <li>{@link Reader} - Returns access to the raw reader of the response.
- * <li>{@link InputStream} - Returns access to the raw input stream of the response.
- * </ul>
- * </ul>
- *
- * @param <T> The class type of the object to create.
- * @param type
- * The object type to create.
- * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
- * @param args
- * The type arguments of the class if it's a collection or map.
- * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
- * <br>Ignored if the main type is not a map or collection.
- * @return The parsed object.
- * @throws ParseException
- * If the input contains a syntax error or is malformed, or is not valid for the specified type.
- * @throws IOException If a connection error occurred.
- * @see BeanSession#getClassMeta(Class) for argument syntax for maps and collections.
- */
- public <T> T getResponse(Type type, Type...args) throws IOException, ParseException {
- BeanContext bc = parser;
- if (bc == null)
- bc = BeanContext.DEFAULT;
- return (T)getResponseInner(bc.getClassMeta(type, args));
- }
-
- /**
- * Same as {@link #getResponse(Type, Type...)} but allows you to specify a part parser to use for parsing the response.
- *
- * @param <T> The class type of the object to create.
- * @param type
- * The object type to create.
- * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
- * @param args
- * The type arguments of the class if it's a collection or map.
- * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
- * <br>Ignored if the main type is not a map or collection.
- * @return The parsed object.
- * @throws ParseException
- * If the input contains a syntax error or is malformed, or is not valid for the specified type.
- * @throws IOException If a connection error occurred.
- * @see BeanSession#getClassMeta(Class) for argument syntax for maps and collections.
- */
- public <T> T getResponseBody(Type type, Type...args) throws IOException, ParseException {
- BeanContext bc = parser;
- if (bc == null)
- bc = BeanContext.DEFAULT;
- return (T)getResponseInner(bc.getClassMeta(type, args));
- }
-
- /**
- * Same as {@link #getResponse(Class)} but allows you to run the call asynchronously.
- *
- * @param <T>
- * The class type of the object being created.
- * See {@link #getResponse(Type, Type...)} for details.
- * @param type
- * The object type to create.
- * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
- * @param args
- * The type arguments of the class if it's a collection or map.
- * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
- * <br>Ignored if the main type is not a map or collection.
- * @return The parsed object.
- * @throws RestCallException If the executor service was not defined.
- * @see
- * RestClientBuilder#executorService(ExecutorService, boolean) for defining the executor service for creating
- * {@link Future Futures}.
- */
- public <T> Future<T> getResponseFuture(final Type type, final Type...args) throws RestCallException {
- return client.getExecutorService(true).submit(
- new Callable<T>() {
- @Override /* Callable */
- public T call() throws Exception {
- return getResponse(type, args);
- }
- }
- );
- }
-
- /**
- * Parses the output from the connection into the specified type and then wraps that in a {@link PojoRest}.
- *
- * <p>
- * Useful if you want to quickly retrieve a single value from inside of a larger JSON document.
- *
- * @param innerType The class type of the POJO being wrapped.
- * @return The parsed output wrapped in a {@link PojoRest}.
- * @throws IOException If a connection error occurred.
- * @throws ParseException
- * If the input contains a syntax error or is malformed for the <c>Content-Type</c> header.
- */
- public PojoRest getResponsePojoRest(Class<?> innerType) throws IOException, ParseException {
- return new PojoRest(getResponse(innerType));
- }
-
- /**
- * Converts the output from the connection into an {@link OMap} and then wraps that in a {@link PojoRest}.
- *
- * <p>
- * Useful if you want to quickly retrieve a single value from inside of a larger JSON document.
- *
- * @return The parsed output wrapped in a {@link PojoRest}.
- * @throws IOException If a connection error occurred.
- * @throws ParseException
- * If the input contains a syntax error or is malformed for the <c>Content-Type</c> header.
- */
- public PojoRest getResponsePojoRest() throws IOException, ParseException {
- return getResponsePojoRest(OMap.class);
- }
-
- <T> T getResponseInner(ClassMeta<T> type) throws IOException, ParseException {
- try {
- if (response == null)
- connect(type);
-
- Class<?> ic = type.getInnerClass();
-
- if (ic.equals(HttpResponse.class)) {
- softClose();
- return (T)response;
- }
- if (ic.equals(Reader.class))
- return (T)getReader();
- if (ic.equals(InputStream.class))
- return (T)getInputStream();
-
- connect(type);
- Header h = response.getFirstHeader("Content-Type");
- int sc = response.getStatusLine().getStatusCode();
- String ct = firstNonEmpty(h == null ? null : h.getValue(), "text/plain");
-
- MediaType mt = MediaType.of(ct);
-
- if (parser == null || (mt.toString().equals("text/plain") && ! parser.canHandle(ct))) {
- if (type.hasStringMutater())
- return type.getStringMutater().mutate(getResponseAsString());
- }
-
- if (parser != null) {
- try (Closeable in = parser.isReaderParser() ? getReader() : getInputStream()) {
-
- // HttpClient automatically ignores the content body for certain HTTP status codes.
- // So instantiate the object anyway if it has a no-arg constructor.
- // This allows a remote resource method to return a NoContent object for example.
- if (in == null && (sc < SC_OK || sc == SC_NO_CONTENT || sc == SC_NOT_MODIFIED || sc == SC_RESET_CONTENT)) {
- ConstructorInfo c = type.getInfo().getPublicConstructor();
- if (c != null) {
- try {
- return c.<T>invoke();
- } catch (ExecutableException e) {
- throw new ParseException(e);
- }
- }
- }
-
- ParserSessionArgs pArgs =
- ParserSessionArgs
- .create()
- .properties(new OMap().inner(getProperties()))
- .locale(response.getLocale())
- .mediaType(mt)
- .schema(responseBodySchema);
- return parser.createSession(pArgs).parse(in, type);
- }
- }
-
- if (type.hasReaderMutater())
- return type.getReaderMutater().mutate(getReader());
-
- if (type.hasInputStreamMutater())
- return type.getInputStreamMutater().mutate(getInputStream());
-
- throw new ParseException(
- "Unsupported media-type in request header ''Content-Type'': ''{0}''\n\tSupported media-types: {1}",
- getResponseHeader("Content-Type"), parser == null ? null : parser.getMediaTypes()
- );
-
- } catch (ParseException | IOException e) {
- isFailed = true;
- close();
- throw e;
- }
- }
-
- BeanContext getBeanContext() {
- BeanContext bc = parser;
- if (bc == null)
- bc = BeanContext.DEFAULT;
- return bc;
- }
-
- /**
- * Converts the response from this call into a response bean.
- *
- * @param rbm The metadata used to construct the response bean.
- * @return A new response bean.
- */
- public <T> T getResponse(final ResponseBeanMeta rbm) {
- try {
- softClose();
- Class<T> c = (Class<T>)rbm.getClassMeta().getInnerClass();
- final RestClient rc = this.client;
- final HttpPartParser p = ObjectUtils.firstNonNull(partParser, rc.getPartParser());
- return (T)Proxy.newProxyInstance(
- c.getClassLoader(),
- new Class[] { c },
- new InvocationHandler() {
- @Override /* InvocationHandler */
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- ResponseBeanPropertyMeta pm = rbm.getProperty(method.getName());
- if (pm != null) {
- HttpPartParser pp = pm.getParser(p);
- HttpPartSchema schema = pm.getSchema();
- String name = pm.getPartName();
- ClassMeta<?> type = rc.getClassMeta(method.getGenericReturnType());
- HttpPartType pt = pm.getPartType();
- if (pt == RESPONSE_BODY) {
- responseBodySchema(schema);
- return getResponseBody(type);
- }
- if (pt == RESPONSE_HEADER)
- return getResponseHeader(pp, schema, name, type);
- if (pt == RESPONSE_STATUS)
- return getResponseCode();
- }
- return null;
- }
-
- });
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Returns access to the {@link HttpUriRequest} passed to {@link HttpClient#execute(HttpUriRequest)}.
- *
- * @return The {@link HttpUriRequest} object.
- */
- public HttpUriRequest getRequest() {
- return request;
- }
-
- /**
- * Returns access to the {@link HttpResponse} returned by {@link HttpClient#execute(HttpUriRequest)}.
- *
- * <p>
- * Returns <jk>null</jk> if {@link #connect()} has not yet been called.
- *
- * @return The HTTP response object.
- * @throws IOException Thrown by underlying stream.
- */
- public HttpResponse getResponse() throws IOException {
- connect();
- return response;
- }
-
- /**
- * Shortcut for calling <c>getRequest().setHeader(header)</c>
- *
- * @param header The header to set on the request.
- * @return This object (for method chaining).
- */
- public RestCall header(Header header) {
- request.setHeader(header);
- return this;
- }
-
- /**
- * Cleans up this HTTP call.
- *
- * @throws RestCallException Can be thrown by one of the {@link RestCallInterceptor#onClose(RestCall)} calls.
- */
- @Override /* Closeable */
- public void close() throws RestCallException {
- if (response != null && ! softClose)
- EntityUtils.consumeQuietly(response.getEntity());
- if (! softClose)
- isClosed = true;
- if (! isFailed)
- for (RestCallInterceptor r : interceptors)
- r.onClose(this);
- }
-
- void forceClose() throws RestCallException {
- softClose = false;
- close();
- }
-
- /**
- * Adds a {@link RestCallLogger} to the list of interceptors on this class.
- *
- * @param level The log level to log events at.
- * @param log The logger.
- * @return This object (for method chaining).
- */
- public RestCall logTo(Level level, Logger log) {
- interceptor(new RestCallLogger(level, log));
- return this;
- }
-
- /**
- * Sets <c>Debug: value</c> header on this request.
- *
- * @return This object (for method chaining).
- * @throws RestCallException Invalid input.
- */
- public RestCall debug() throws RestCallException {
- header("Debug", true);
- return this;
- }
-
- /**
- * If called, the underlying response stream will not be closed when you call {@link #close()}.
- *
- * <p>
- * This is useful in cases where you want access to that stream after you've already cleaned up this object.
- * However, it is your responsibility to close that stream yourself.
- *
- * @return This object (for method chaining).
- */
- public RestCall softClose() {
- this.softClose = true;
- return this;
- }
-
- //-----------------------------------------------------------------------------------------------------------------
- // Utility methods
- //-----------------------------------------------------------------------------------------------------------------
-
- /**
- * Specifies that the following value can be added as an HTTP part.
- */
- private boolean canAdd(Object value, HttpPartSchema schema, boolean skipIfEmpty) {
- if (value != null) {
- if (ObjectUtils.isEmpty(value) && skipIfEmpty)
- return false;
- return true;
- }
- if (schema == null)
- return false;
- if (schema.isRequired())
- return true;
- String def = schema.getDefault();
- if (def == null)
- return false;
- if (StringUtils.isEmpty(def) && skipIfEmpty)
- return false;
- return true;
- }
-
- private static String className(Object o) {
- return ClassInfo.of(o).getFullName();
- }
-
- //-----------------------------------------------------------------------------------------------------------------
- // Other methods
- //-----------------------------------------------------------------------------------------------------------------
-
- @Override /* Session */
- public OMap toMap() {
- return super.toMap()
- .a("RestCall", new DefaultFilteringOMap()
- .a("allowRedirectsOnPosts", allowRedirectsOnPosts)
- .a("byLines", byLines)
- .a("capturedResponse", capturedResponse)
- .a("client", client)
- .a("hasInput", hasInput)
- .a("ignoreErrors", ignoreErrors)
- .a("interceptors", interceptors)
- .a("isClosed", isClosed)
- .a("isConnected", isConnected)
- .a("isFailed", isFailed)
- .a("parser", parser)
- .a("partParser", partParser)
- .a("partSerializer", partSerializer)
- .a("redirectOnPostsTries", redirectOnPostsTries)
- .a("requestBodySchema", requestBodySchema)
- .a("response", response)
- .a("responseBodySchema", responseBodySchema)
- .a("retries", retries)
- .a("retryInterval", retryInterval)
- .a("retryOn", retryOn)
- .a("serializer", serializer)
- .a("softClose", softClose)
- .a("uriBuilder", uriBuilder)
- );
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallException.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallException.java
deleted file mode 100644
index 12f4ac8..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallException.java
+++ /dev/null
@@ -1,249 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import static java.lang.String.*;
-import static org.apache.juneau.internal.StringUtils.*;
-import static org.apache.juneau.internal.IOUtils.*;
-import static org.apache.juneau.internal.StringUtils.format;
-
-import java.io.*;
-import java.net.*;
-import java.text.*;
-import java.util.regex.*;
-
-import org.apache.http.*;
-import org.apache.http.client.*;
-import org.apache.http.util.*;
-import org.apache.juneau.reflect.*;
-
-/**
- * Exception representing a <c>400+</c> HTTP response code against a remote resource.
- *
- * @deprecated Use {@link org.apache.juneau.rest.client2.RestCallException} class.
- */
-@Deprecated
-public final class RestCallException extends IOException {
-
- private static final long serialVersionUID = 1L;
-
- private int responseCode;
- private String response, responseStatusMessage;
- HttpResponseException e;
- private HttpResponse httpResponse;
-
- @SuppressWarnings("unused")
- private String serverExceptionName, serverExceptionMessage, serverExceptionTrace;
-
- /**
- * Constructor.
- *
- * @param message The {@link MessageFormat}-style message.
- * @param args Optional {@link MessageFormat}-style arguments.
- */
- public RestCallException(String message, Object...args) {
- super(format(message, args));
- }
-
- /**
- * Constructor.
- *
- * @param cause The cause of this exception.
- * @param message The {@link MessageFormat}-style message.
- * @param args Optional {@link MessageFormat}-style arguments.
- */
- public RestCallException(Throwable cause, String message, Object...args) {
- this(getMessage(cause, message, null), args);
- initCause(cause);
- }
-
- /**
- * Constructor.
- *
- * @param e The inner cause of the exception.
- */
- public RestCallException(Exception e) {
- super(e.getLocalizedMessage(), e);
- if (e instanceof FileNotFoundException) {
- responseCode = 404;
- } else if (e.getMessage() != null) {
- Pattern p = Pattern.compile("[^\\d](\\d{3})[^\\d]");
- Matcher m = p.matcher(e.getMessage());
- if (m.find())
- responseCode = Integer.parseInt(m.group(1));
- }
- setStackTrace(e.getStackTrace());
- }
-
- /**
- * Create an exception with a simple message and the status code and body of the specified response.
- *
- * @param msg The exception message.
- * @param response The HTTP response object.
- * @throws IOException Thrown by underlying stream.
- */
- public RestCallException(String msg, HttpResponse response) throws IOException {
- super(format("{0}\n{1}\nstatus=''{2}''\nResponse: \n{3}", msg, response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), UTF8)));
- }
-
- /**
- * Constructor.
- *
- * @param responseCode The response code.
- * @param responseMsg The response message.
- * @param method The HTTP method (for message purposes).
- * @param url The HTTP URL (for message purposes).
- * @param response The response from the server.
- */
- public RestCallException(int responseCode, String responseMsg, String method, URI url, String response) {
- super(format("HTTP method ''{0}'' call to ''{1}'' caused response code ''{2}, {3}''.\nResponse: \n{4}", method, url, responseCode, responseMsg, response));
- this.responseCode = responseCode;
- this.responseStatusMessage = responseMsg;
- this.response = response;
- }
-
- /**
- * Sets the server-side exception details.
- *
- * @param exceptionName The <c>Exception-Name:</c> header specifying the full name of the exception.
- * @param exceptionMessage
- * The <c>Exception-Message:</c> header specifying the message returned by {@link Throwable#getMessage()}.
- * @param exceptionTrace The stack trace of the exception returned by {@link Throwable#printStackTrace()}.
- * @return This object (for method chaining).
- */
- protected RestCallException setServerException(Header exceptionName, Header exceptionMessage, Header exceptionTrace) {
- if (exceptionName != null)
- serverExceptionName = exceptionName.getValue();
- if (exceptionMessage != null)
- serverExceptionMessage = exceptionMessage.getValue();
- if (exceptionTrace != null)
- serverExceptionTrace = exceptionTrace.getValue();
- return this;
- }
-
- /**
- * Tries to reconstruct and re-throw the server-side exception.
- *
- * <p>
- * The exception is based on the following HTTP response headers:
- * <ul>
- * <li><c>Exception-Name:</c> - The full class name of the exception.
- * <li><c>Exception-Message:</c> - The message returned by {@link Throwable#getMessage()}.
- * <li><c>Exception-Trace:</c> - The stack trace of the exception returned by {@link Throwable#printStackTrace()}.
- * </ul>
- *
- * <p>
- * Does nothing if the server-side exception could not be reconstructed.
- *
- * <p>
- * Currently only supports <c>Throwables</c> with either a public no-arg constructor
- * or a public constructor that takes in a simple string message.
- *
- * @param cl The classloader to use to resolve the throwable class name.
- * @param throwables The possible throwables.
- * @throws Throwable If the throwable could be reconstructed.
- */
- protected void throwServerException(ClassLoader cl, Class<?>...throwables) throws Throwable {
- if (serverExceptionName != null) {
- for (Class<?> t : throwables)
- if (t.getName().endsWith(serverExceptionName))
- doThrow(t, serverExceptionMessage);
- try {
- ClassInfo t = ClassInfo.of(cl.loadClass(serverExceptionName));
- if (t.isChildOf(RuntimeException.class) || t.isChildOf(Error.class))
- doThrow(t.inner(), serverExceptionMessage);
- } catch (ClassNotFoundException e2) { /* Ignore */ }
- }
- }
-
- private void doThrow(Class<?> t, String msg) throws Throwable {
- ConstructorInfo c = null;
- ClassInfo ci = ClassInfo.of(t);
- if (msg != null) {
- c = ci.getPublicConstructor(String.class);
- if (c != null)
- throw c.<Throwable>invoke(msg);
- c = ci.getPublicConstructor(Object.class);
- if (c != null)
- throw c.<Throwable>invoke(msg);
- }
- c = ci.getPublicConstructor();
- if (c != null)
- throw c.<Throwable>invoke();
- }
-
- /**
- * Sets the HTTP response object that caused this exception.
- *
- * @param httpResponse The HTTP response object.
- * @return This object (for method chaining).
- */
- protected RestCallException setHttpResponse(HttpResponse httpResponse) {
- this.httpResponse = httpResponse;
- return this;
- }
-
- /**
- * Returns the HTTP response object that caused this exception.
- *
- * @return
- * The HTTP response object that caused this exception, or <jk>null</jk> if no response was created yet when the
- * exception was thrown.
- */
- public HttpResponse getHttpResponse() {
- return this.httpResponse;
- }
-
- /**
- * Returns the HTTP response status code.
- *
- * @return The response status code. If a connection could not be made at all, returns <c>0</c>.
- */
- public int getResponseCode() {
- return responseCode;
- }
-
- /**
- * Returns the HTTP response message body text.
- *
- * @return The response message body text.
- */
- public String getResponseMessage() {
- return response;
- }
-
- /**
- * Returns the response status message as a plain string.
- *
- * @return The response status message.
- */
- public String getResponseStatusMessage() {
- return responseStatusMessage;
- }
-
- /**
- * Finds the message.
- *
- * @param cause The cause.
- * @param msg The message.
- * @param def The default value if both above are <jk>null</jk>.
- * @return The resolved message.
- */
- protected static final String getMessage(Throwable cause, String msg, String def) {
- if (msg != null)
- return msg;
- if (cause != null)
- return cause.getMessage();
- return def;
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallHandler.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallHandler.java
deleted file mode 100644
index 83241ab..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallHandler.java
+++ /dev/null
@@ -1,68 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import java.io.*;
-
-import org.apache.http.*;
-import org.apache.http.client.*;
-import org.apache.http.client.methods.*;
-
-/**
- * Interface that allows you to override the handling of HTTP requests.
- *
- * <p>
- * Providing this implementation is the equivalent to overriding the {@link RestClient#execute(HttpEntityEnclosingRequestBase)}
- * and {@link RestClient#execute(HttpRequestBase)} methods.
- *
- * <p>
- * This can also be accomplished by providing your own {@link RestClientBuilder#connectionManager(org.apache.http.conn.HttpClientConnectionManager)},
- * but this provides a simpler way of handling the requests yourself.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_callHandler}
- * <li class='jf'>{@link RestClientBuilder#callHandler(Class)}
- * <li class='jf'>{@link RestClientBuilder#callHandler(RestCallHandler)}
- * </ul>
- *
- * @deprecated Use {@link org.apache.juneau.rest.client2.RestCallHandler} class.
- */
-@Deprecated
-public interface RestCallHandler {
-
- /**
- * Execute the specified body request (e.g. POST/PUT).
- *
- * <p>
- * Subclasses can override this method to provide specialized handling.
- *
- * @param req The HTTP request.
- * @return The HTTP response.
- * @throws IOException Stream exception occurred.
- * @throws ClientProtocolException Signals an error in the HTTP protocol.
- */
- HttpResponse execute(HttpEntityEnclosingRequestBase req) throws ClientProtocolException, IOException;
-
- /**
- * Execute the specified no-body request (e.g. GET/DELETE).
- *
- * <p>
- * Subclasses can override this method to provide specialized handling.
- *
- * @param req The HTTP request.
- * @return The HTTP response.
- * @throws IOException Stream exception occurred.
- * @throws ClientProtocolException Signals an error in the HTTP protocol.
- */
- HttpResponse execute(HttpRequestBase req) throws ClientProtocolException, IOException;
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallInterceptor.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallInterceptor.java
deleted file mode 100644
index 3737ea1..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallInterceptor.java
+++ /dev/null
@@ -1,64 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import org.apache.http.*;
-
-/**
- * Used to intercept http connection responses to allow modification of that response before processing and for
- * listening for call lifecycle events.
- *
- * <p>
- * Useful if you want to prevent {@link RestCallException RestCallExceptions} from being thrown on error conditions.
- *
- * @deprecated Use {@link org.apache.juneau.rest.client2.RestCallInterceptor} class.
- */
-@Deprecated
-public abstract class RestCallInterceptor {
-
- /**
- * Called when {@link RestCall} object is created.
- *
- * @param restCall The restCall object invoking this method.
- */
- public void onInit(RestCall restCall) {}
-
- /**
- * Called immediately after an HTTP response has been received.
- *
- * @param statusCode The HTTP status code received.
- * @param restCall The restCall object invoking this method.
- * @param req The HTTP request object.
- * @param res The HTTP response object.
- */
- public void onConnect(RestCall restCall, int statusCode, HttpRequest req, HttpResponse res) {}
-
- /**
- * Called if retry is going to be attempted.
- *
- * @param statusCode The HTTP status code received.
- * @param restCall The restCall object invoking this method.
- * @param req The HTTP request object.
- * @param res The HTTP response object.
- * @param ex The exception thrown from the client.
- */
- public void onRetry(RestCall restCall, int statusCode, HttpRequest req, HttpResponse res, Exception ex) {}
-
- /**
- * Called when {@link RestCall#close()} is called.
- *
- * @param restCall The restCall object invoking this method.
- * @throws RestCallException Error occurred during call.
- */
- public void onClose(RestCall restCall) throws RestCallException {}
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallLogger.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallLogger.java
deleted file mode 100644
index d5cf396..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestCallLogger.java
+++ /dev/null
@@ -1,130 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import static org.apache.juneau.internal.StringUtils.*;
-
-import java.io.*;
-import java.util.logging.*;
-
-import org.apache.http.*;
-import org.apache.http.client.methods.*;
-import org.apache.http.util.*;
-
-/**
- * Specialized interceptor for logging calls to a log file.
- *
- * <p>
- * Causes a log entry to be created that shows all the request and response headers and content at the end of the
- * request.
- *
- * <p>
- * Use the {@link RestClientBuilder#logTo(Level, Logger)} and {@link RestCall#logTo(Level, Logger)} methods to create
- * instances of this class.
- */
-@Deprecated
-public class RestCallLogger extends RestCallInterceptor {
-
- /**
- * Default HTTP request logger.
- * <p>
- * Logs outgoing HTTP requests to the <c>org.apache.juneau.rest.client</c> logger at <jsf>WARNING</jsf> level.
- */
- public static final RestCallLogger DEFAULT = new RestCallLogger(Level.WARNING, Logger.getLogger("org.apache.juneau.rest.client"));
-
- private Level level;
- private Logger log;
-
- /**
- * Constructor.
- *
- * @param level The log level to log messages at.
- * @param log The logger to log to.
- */
- protected RestCallLogger(Level level, Logger log) {
- this.level = level;
- this.log = log;
- }
-
- @Override /* RestCallInterceptor */
- public void onInit(RestCall restCall) {
- if (log.isLoggable(level))
- restCall.captureResponse();
- }
-
- @Override /* RestCallInterceptor */
- public void onConnect(RestCall restCall, int statusCode, HttpRequest req, HttpResponse res) {
- // Do nothing.
- }
-
- @Override /* RestCallInterceptor */
- public void onRetry(RestCall restCall, int statusCode, HttpRequest req, HttpResponse res, Exception ex) {
- if (log.isLoggable(level)) {
- if (ex == null)
- log.log(level, format("Call to {0} returned {1}. Will retry.", req.getRequestLine().getUri(), statusCode));
- else
- log.log(level, format("Call to {0} caused exception {1}. Will retry.", req.getRequestLine().getUri(), ex.getLocalizedMessage()), ex);
- }
- }
-
- @Override /* RestCallInterceptor */
- public void onClose(RestCall restCall) throws RestCallException {
- try {
- if (log.isLoggable(level)) {
- String output = restCall.getCapturedResponse();
- StringBuilder sb = new StringBuilder();
- HttpUriRequest req = restCall.getRequest();
- HttpResponse res = restCall.getResponse();
- if (req != null) {
- sb.append("\n=== HTTP Call (outgoing) =======================================================");
-
- sb.append("\n=== REQUEST ===\n").append(req);
- sb.append("\n---request headers---");
- for (Header h : req.getAllHeaders())
- sb.append("\n\t").append(h);
- if (req instanceof HttpEntityEnclosingRequestBase) {
- sb.append("\n---request entity---");
- HttpEntityEnclosingRequestBase req2 = (HttpEntityEnclosingRequestBase)req;
- HttpEntity e = req2.getEntity();
- if (e == null)
- sb.append("\nEntity is null");
- else {
- if (e.getContentType() != null)
- sb.append("\n").append(e.getContentType());
- if (e.getContentEncoding() != null)
- sb.append("\n").append(e.getContentEncoding());
- if (e.isRepeatable()) {
- try {
- sb.append("\n---request content---\n").append(EntityUtils.toString(e));
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
- }
- }
- }
- if (res != null) {
- sb.append("\n=== RESPONSE ===\n").append(res.getStatusLine());
- sb.append("\n---response headers---");
- for (Header h : res.getAllHeaders())
- sb.append("\n\t").append(h);
- sb.append("\n---response content---\n").append(output);
- sb.append("\n=== END ========================================================================");
- }
- log.log(level, sb.toString());
- }
- } catch (IOException e) {
- log.log(Level.SEVERE, e.getLocalizedMessage(), e);
- }
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClient.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClient.java
deleted file mode 100644
index 5baf6fd..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClient.java
+++ /dev/null
@@ -1,1544 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import static org.apache.juneau.internal.StringUtils.*;
-import static org.apache.juneau.internal.ClassUtils.*;
-import static org.apache.juneau.httppart.HttpPartType.*;
-
-import java.io.*;
-import java.lang.reflect.*;
-import java.lang.reflect.Proxy;
-import java.net.*;
-import java.net.URI;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.regex.*;
-
-import org.apache.http.*;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.methods.*;
-import org.apache.http.client.utils.*;
-import org.apache.http.entity.*;
-import org.apache.http.impl.client.*;
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.collections.*;
-import org.apache.juneau.http.remote.RemoteReturn;
-import org.apache.juneau.http.remote.*;
-import org.apache.juneau.httppart.*;
-import org.apache.juneau.httppart.bean.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.oapi.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.reflect.*;
-import org.apache.juneau.remote.*;
-import org.apache.juneau.rest.client.remote.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.urlencoding.*;
-
-/**
- * Utility class for interfacing with remote REST interfaces.
- *
- * <h5 class='topic'>Features</h5>
- * <ul class='spaced-list'>
- * <li>
- * Convert POJOs directly to HTTP request message bodies using {@link Serializer} class.
- * <li>
- * Convert HTTP response message bodies directly to POJOs using {@link Parser} class.
- * <li>
- * Fluent interface.
- * <li>
- * Thread safe.
- * <li>
- * API for interacting with remote services.
- * </ul>
- *
- *
- * <ul class='seealso'>
- * <li class='link'>{@doc juneau-rest-client}
- * </ul>
- *
- * @deprecated Use {@link org.apache.juneau.rest.client2.RestClient}
- */
-@SuppressWarnings("rawtypes")
-@ConfigurableContext(nocache=true)
-@Deprecated
-public class RestClient extends BeanContext implements Closeable {
-
- //-------------------------------------------------------------------------------------------------------------------
- // Configurable properties
- //-------------------------------------------------------------------------------------------------------------------
-
- private static final String PREFIX = "RestClient.";
-
- /**
- * Configuration property: REST call handler.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_callHandler RESTCLIENT_callHandler}
- * <li><b>Name:</b> <js>"RestClient.callHandler.o"</js>
- * <li><b>Data type:</b> {@link org.apache.juneau.rest.client.RestCallHandler}
- * <li><b>Default:</b> <c><jk>null</jk></c>
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#callHandler(Class)}
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#callHandler(RestCallHandler)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Allows you to provide a custom handler for making HTTP calls.
- */
- public static final String RESTCLIENT_callHandler = PREFIX + "callHandler.o";
-
- /**
- * Configuration property: Debug.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_debug RESTCLIENT_debug}
- * <li><b>Name:</b> <js>"RestClient.debug.b"</js>
- * <li><b>Data type:</b> <jk>boolean</jk>
- * <li><b>System property:</b> <c>RestClient.debug</c>
- * <li><b>Environment variable:</b> <c>RESTCLIENT_DEBUG</c>
- * <li><b>Default:</b> <jk>false</jk>
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#debug()}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Enable debug mode.
- */
- public static final String RESTCLIENT_debug = PREFIX + "debug.b";
-
- /**
- * Configuration property: Executor service.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_executorService RESTCLIENT_executorService}
- * <li><b>Name:</b> <js>"RestClient.executorService.o"</js>
- * <li><b>Data type:</b>
- * <ul>
- * <li><c>Class<{@link java.util.concurrent.ExecutorService}></c>
- * <li>{@link java.util.concurrent.ExecutorService}
- * </ul>
- * <li><b>Default:</b> <jk>null</jk>.
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#executorService(ExecutorService, boolean)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Defines the executor service to use when calling future methods on the {@link RestCall} class.
- *
- * <p>
- * This executor service is used to create {@link Future} objects on the following methods:
- * <ul>
- * <li>{@link RestCall#runFuture()}
- * <li>{@link RestCall#getResponseFuture(Class)}
- * <li>{@link RestCall#getResponseFuture(Type,Type...)}
- * <li>{@link RestCall#getResponseAsString()}
- * </ul>
- *
- * <p>
- * The default executor service is a single-threaded {@link ThreadPoolExecutor} with a 30 second timeout
- * and a queue size of 10.
- */
- public static final String RESTCLIENT_executorService = PREFIX + "executorService.o";
-
- /**
- * Configuration property: Shut down executor service on close.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_executorServiceShutdownOnClose RESTCLIENT_executorServiceShutdownOnClose}
- * <li><b>Name:</b> <js>"RestClient.executorServiceShutdownOnClose.b"</js>
- * <li><b>Data type:</b> <jk>boolean</jk>
- * <li><b>System property:</b> <c>RestClient.executorServiceShutdownOnClose</c>
- * <li><b>Environment variable:</b> <c>RESTCLIENT_EXECUTORSERVICESHUTDOWNONCLOSE</c>
- * <li><b>Default:</b> <jk>false</jk>
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#executorService(ExecutorService, boolean)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Call {@link ExecutorService#shutdown()} when {@link RestClient#close()} is called.
- */
- public static final String RESTCLIENT_executorServiceShutdownOnClose = PREFIX + "executorServiceShutdownOnClose.b";
-
- /**
- * Configuration property: Request headers.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_headers RESTCLIENT_headers}
- * <li><b>Name:</b> <js>"RestClient.requestHeaders.sms"</js>
- * <li><b>Data type:</b> <c>Map<String,String></c>
- * <li><b>System property:</b> <c>RestClient.requestHeaders</c>
- * <li><b>Environment variable:</b> <c>RESTCLIENT_REQUESTHEADERS</c>
- * <li><b>Default:</b> empty map
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#header(String, Object)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Headers to add to every request.
- */
- public static final String RESTCLIENT_headers = PREFIX + "headers.sms";
-
- /**
- * Configuration property: Call interceptors.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_interceptors RESTCLIENT_interceptors}
- * <li><b>Name:</b> <js>"RestClient.interceptors.lo"</js>
- * <li><b>Data type:</b><c>List<Class<{@link org.apache.juneau.rest.client.RestCallInterceptor}>|{@link org.apache.juneau.rest.client.RestCallInterceptor}></c>
- * <li><b>Default:</b> empty list.
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#interceptors(RestCallInterceptor...)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Interceptors that get called immediately after a connection is made.
- */
- public static final String RESTCLIENT_interceptors = PREFIX + "interceptors.lo";
-
- /**
- * Add to the Call interceptors property.
- */
- public static final String RESTCLIENT_interceptors_add = PREFIX + "interceptors.lo/add";
-
- /**
- * Configuration property: Keep HttpClient open.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_keepHttpClientOpen RESTCLIENT_keepHttpClientOpen}
- * <li><b>Name:</b> <js>"RestClient.keepHttpClientOpen.b"</js>
- * <li><b>Data type:</b> <jk>boolean</jk>
- * <li><b>System property:</b> <c>RestClient.keepHttpClientOpen</c>
- * <li><b>Environment variable:</b> <c>RESTCLIENT_KEEPHTTPCLIENTOPEN</c>
- * <li><b>Default:</b> <jk>false</jk>
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#keepHttpClientOpen(boolean)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Don't close this client when the {@link RestClient#close()} method is called.
- */
- public static final String RESTCLIENT_keepHttpClientOpen = PREFIX + "keepHttpClientOpen.b";
-
- /**
- * Configuration property: Parser.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_parser RESTCLIENT_parser}
- * <li><b>Name:</b> <js>"RestClient.parser.o"</js>
- * <li><b>Data type:</b>
- * <ul>
- * <li><c>Class<{@link org.apache.juneau.parser.Parser}></c>
- * <li>{@link org.apache.juneau.parser.Parser}
- * </ul>
- * <li><b>Default:</b> {@link org.apache.juneau.json.JsonParser};
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#parser(Class)}
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#parser(Parser)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * The parser to use for parsing POJOs in response bodies.
- */
- public static final String RESTCLIENT_parser = PREFIX + "parser.o";
-
- /**
- * Configuration property: Part parser.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_partParser RESTCLIENT_partParser}
- * <li><b>Name:</b> <js>"RestClient.partParser.o"</js>
- * <li><b>Data type:</b>
- * <ul>
- * <li><c>Class<{@link org.apache.juneau.httppart.HttpPartParser}></c>
- * <li>{@link org.apache.juneau.httppart.HttpPartParser}
- * </ul>
- * <li><b>Default:</b> {@link org.apache.juneau.oapi.OpenApiParser};
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#partParser(Class)}
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#partParser(HttpPartParser)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * The parser to use for parsing POJOs from form data, query parameters, headers, and path variables.
- */
- public static final String RESTCLIENT_partParser = PREFIX + "partParser.o";
-
- /**
- * Configuration property: Part serializer.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_partSerializer RESTCLIENT_partSerializer}
- * <li><b>Name:</b> <js>"RestClient.partSerializer.o"</js>
- * <li><b>Data type:</b>
- * <ul>
- * <li><c>Class<{@link org.apache.juneau.httppart.HttpPartSerializer}></c>
- * <li>{@link org.apache.juneau.httppart.HttpPartSerializer}
- * </ul>
- * <li><b>Default:</b> {@link org.apache.juneau.oapi.OpenApiSerializer};
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#partSerializer(Class)}
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#partSerializer(HttpPartSerializer)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * The serializer to use for serializing POJOs in form data, query parameters, headers, and path variables.
- */
- public static final String RESTCLIENT_partSerializer = PREFIX + "partSerializer.o";
-
- /**
- * Configuration property: Request query parameters.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_query RESTCLIENT_query}
- * <li><b>Name:</b> <js>"RestClient.query.sms"</js>
- * <li><b>Data type:</b> <c>Map<String,String></c>
- * <li><b>System property:</b> <c>RestClient.query</c>
- * <li><b>Environment variable:</b> <c>RESTCLIENT_QUERY</c>
- * <li><b>Default:</b> empty map
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#query(String, Object)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Query parameters to add to every request.
- */
- public static final String RESTCLIENT_query = PREFIX + "query.sms";
-
- /**
- * Configuration property: Number of retries to attempt.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_retries RESTCLIENT_retries}
- * <li><b>Name:</b> <js>"RestClient.retries.i"</js>
- * <li><b>Data type:</b> <jk>int</jk>
- * <li><b>System property:</b> <c>RestClient.retries</c>
- * <li><b>Environment variable:</b> <c>RESTCLIENT_RETRIES</c>
- * <li><b>Default:</b> <c>1</c>
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#retryable(int, int, RetryOn)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * The number of retries to attempt when the connection cannot be made or a <c>>400</c> response is received.
- */
- public static final String RESTCLIENT_retries = PREFIX + "retries.i";
-
- /**
- * Configuration property: The time in milliseconds between retry attempts.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_retryInterval RESTCLIENT_retryInterval}
- * <li><b>Name:</b> <js>"RestClient.retryInterval.i"</js>
- * <li><b>Data type:</b> <jk>int</jk>
- * <li><b>System property:</b> <c>RestClient.retryInterval</c>
- * <li><b>Environment variable:</b> <c>RESTCLIENT_RETRYINTERVAL</c>
- * <li><b>Default:</b> <c>-1</c>
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#retryable(int, int, RetryOn)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * The time in milliseconds between retry attempts.
- * <c>-1</c> means retry immediately.
- */
- public static final String RESTCLIENT_retryInterval = PREFIX + "retryInterval.i";
-
- /**
- * Configuration property: Retry-on determination object.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_retryOn RESTCLIENT_retryOn}
- * <li><b>Name:</b> <js>"RestClient.retryOn.o"</js>
- * <li><b>Data type:</b>
- * <ul>
- * <li><c>Class<{@link org.apache.juneau.rest.client.RetryOn}></c>
- * <li>{@link org.apache.juneau.rest.client.RetryOn}
- * </ul>
- * <li><b>Default:</b> {@link org.apache.juneau.rest.client.RetryOn#DEFAULT}
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#retryable(int, int, RetryOn)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * Object used for determining whether a retry should be attempted.
- */
- public static final String RESTCLIENT_retryOn = PREFIX + "retryOn.o";
-
- /**
- * Configuration property: Root URI.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_rootUri RESTCLIENT_rootUri}
- * <li><b>Name:</b> <js>"RestClient.rootUri.s"</js>
- * <li><b>Data type:</b> <c>String</c>
- * <li><b>System property:</b> <c>RestClient.rootUri</c>
- * <li><b>Environment variable:</b> <c>RESTCLIENT_ROOTURI</c>
- * <li><b>Default:</b> <jk>false</jk>
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#rootUrl(Object)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * When set, relative URL strings passed in through the various rest call methods (e.g. {@link RestClient#doGet(Object)}
- * will be prefixed with the specified root.
- * <br>This root URL is ignored on those methods if you pass in a {@link URL}, {@link URI}, or an absolute URL string.
- * <br>Trailing slashes are trimmed.
- */
- public static final String RESTCLIENT_rootUri = PREFIX + "rootUri.s";
-
- /**
- * Configuration property: Serializer.
- *
- * <h5 class='section'>Property:</h5>
- * <ul class='spaced-list'>
- * <li><b>ID:</b> {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_serializer RESTCLIENT_serializer}
- * <li><b>Name:</b> <js>"RestClient.serializer.o"</js>
- * <li><b>Data type:</b>
- * <ul>
- * <li><c>Class<{@link org.apache.juneau.serializer.Serializer}></c>
- * <li>{@link org.apache.juneau.serializer.Serializer}
- * </ul>
- * <li><b>Default:</b> {@link org.apache.juneau.json.JsonSerializer};
- * <li><b>Methods:</b>
- * <ul>
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#serializer(Class)}
- * <li class='jm'>{@link org.apache.juneau.rest.client.RestClientBuilder#serializer(Serializer)}
- * </ul>
- * </ul>
- *
- * <h5 class='section'>Description:</h5>
- * <p>
- * The serializer to use for serializing POJOs in request bodies.
- */
- public static final String RESTCLIENT_serializer = PREFIX + "serializer.o";
-
- private static final Set<String> NO_BODY_METHODS = ASet.unmodifiable("GET","HEAD","DELETE","CONNECT","OPTIONS","TRACE");
-
- private static final ConcurrentHashMap<Class,HttpPartSerializer> partSerializerCache = new ConcurrentHashMap<>();
-
- private final Map<String,String> headers, query;
- private final HttpClientBuilder httpClientBuilder;
- final CloseableHttpClient httpClient;
- private final boolean keepHttpClientOpen, debug;
- private final UrlEncodingSerializer urlEncodingSerializer; // Used for form posts only.
- private final HttpPartSerializer partSerializer;
- private final HttpPartParser partParser;
- private final RestCallHandler callHandler;
- private final String rootUrl;
- private volatile boolean isClosed = false;
- private final StackTraceElement[] creationStack;
- private StackTraceElement[] closedStack;
-
- // These are read directly by RestCall.
- final Serializer serializer;
- final Parser parser;
- final RetryOn retryOn;
- final int retries;
- final long retryInterval;
- final RestCallInterceptor[] interceptors;
-
- // This is lazy-created.
- private volatile ExecutorService executorService;
- private final boolean executorServiceShutdownOnClose;
-
- /**
- * Instantiates a new clean-slate {@link RestClientBuilder} object.
- *
- * @return A new {@link RestClientBuilder} object.
- */
- public static RestClientBuilder create() {
- return new RestClientBuilder(PropertyStore.DEFAULT, null);
- }
-
- /**
- * Instantiates a new {@link RestClientBuilder} object using the specified serializer and parser.
- *
- * <p>
- * Shortcut for calling <code>RestClient.<jsm>create</jsm>().serializer(s).parser(p);</code>
- *
- * @param s The serializer to use for output.
- * @param p The parser to use for input.
- * @return A new {@link RestClientBuilder} object.
- */
- public static RestClientBuilder create(Serializer s, Parser p) {
- return create().serializer(s).parser(p);
- }
-
- /**
- * Instantiates a new {@link RestClientBuilder} object using the specified serializer and parser.
- *
- * <p>
- * Shortcut for calling <code>RestClient.<jsm>create</jsm>().serializer(s).parser(p);</code>
- *
- * @param s The serializer class to use for output.
- * @param p The parser class to use for input.
- * @return A new {@link RestClientBuilder} object.
- */
- public static RestClientBuilder create(Class<? extends Serializer> s, Class<? extends Parser> p) {
- return create().serializer(s).parser(p);
- }
-
- @Override /* Context */
- public RestClientBuilder builder() {
- return new RestClientBuilder(getPropertyStore(), httpClientBuilder);
- }
-
- /**
- * Constructor.
- *
- * @param builder The REST client builder.
- */
- @SuppressWarnings("unchecked")
- protected RestClient(RestClientBuilder builder) {
- super(builder.getPropertyStore());
- PropertyStore ps = getPropertyStore();
- this.httpClientBuilder = builder.getHttpClientBuilder();
- this.httpClient = builder.getHttpClient();
- this.keepHttpClientOpen = getBooleanProperty(RESTCLIENT_keepHttpClientOpen, false);
- this.headers = getMapProperty(RESTCLIENT_headers, String.class);
- this.query = getMapProperty(RESTCLIENT_query, String.class);
- this.retries = getIntegerProperty(RESTCLIENT_retries, 1);
- this.retryInterval = getIntegerProperty(RESTCLIENT_retryInterval, -1);
- this.retryOn = getInstanceProperty(RESTCLIENT_retryOn, RetryOn.class, RetryOn.DEFAULT);
- this.debug = getBooleanProperty(RESTCLIENT_debug, false);
- this.executorServiceShutdownOnClose = getBooleanProperty(RESTCLIENT_executorServiceShutdownOnClose, false);
- this.rootUrl = StringUtils.nullIfEmpty(getStringProperty(RESTCLIENT_rootUri, "").replaceAll("\\/$", ""));
-
- Object o = getProperty(RESTCLIENT_serializer, Object.class, null);
- if (o instanceof Serializer) {
- this.serializer = ((Serializer)o).builder().apply(ps).build();
- } else if (o instanceof Class) {
- this.serializer = ContextCache.INSTANCE.create((Class<? extends Serializer>)o, ps);
- } else {
- this.serializer = null;
- }
-
- o = getProperty(RESTCLIENT_parser, Object.class, null);
- if (o instanceof Parser) {
- this.parser = ((Parser)o).builder().apply(ps).build();
- } else if (o instanceof Class) {
- this.parser = ContextCache.INSTANCE.create((Class<? extends Parser>)o, ps);
- } else {
- this.parser = null;
- }
-
- this.urlEncodingSerializer = new SerializerBuilder(ps).build(UrlEncodingSerializer.class);
- this.partSerializer = getInstanceProperty(RESTCLIENT_partSerializer, HttpPartSerializer.class, OpenApiSerializer.class, ResourceResolver.FUZZY, ps);
- this.partParser = getInstanceProperty(RESTCLIENT_partParser, HttpPartParser.class, OpenApiParser.class, ResourceResolver.FUZZY, ps);
- this.executorService = getInstanceProperty(RESTCLIENT_executorService, ExecutorService.class, null);
-
- RestCallHandler callHandler = getInstanceProperty(RESTCLIENT_callHandler, RestCallHandler.class, null);
- if (callHandler == null) {
- callHandler = new RestCallHandler() {
- @Override
- public HttpResponse execute(HttpEntityEnclosingRequestBase req) throws ClientProtocolException, IOException {
- return RestClient.this.httpClient.execute(req);
- }
-
- @Override
- public HttpResponse execute(HttpRequestBase req) throws ClientProtocolException, IOException {
- return RestClient.this.httpClient.execute(req);
- }
- };
- }
- this.callHandler = callHandler;
-
- RestCallInterceptor[] rci = getInstanceArrayProperty(RESTCLIENT_interceptors, RestCallInterceptor.class, new RestCallInterceptor[0]);
- if (debug)
- rci = ArrayUtils.append(rci, RestCallLogger.DEFAULT);
- this.interceptors = rci;
-
- if (Boolean.getBoolean("org.apache.juneau.rest.client.RestClient.trackLifecycle"))
- creationStack = Thread.currentThread().getStackTrace();
- else
- creationStack = null;
- }
-
- /**
- * Returns <jk>true</jk> if specified http method has content.
- * <p>
- * By default, anything not in this list can have content: <c>GET, HEAD, DELETE, CONNECT, OPTIONS, TRACE</c>.
- *
- * @param httpMethod The HTTP method. Must be upper-case.
- * @return <jk>true</jk> if specified http method has content.
- */
- protected boolean hasContent(String httpMethod) {
- return ! NO_BODY_METHODS.contains(httpMethod);
- }
-
- /**
- * Calls {@link CloseableHttpClient#close()} on the underlying {@link CloseableHttpClient}.
- *
- * <p>
- * It's good practice to call this method after the client is no longer used.
- *
- * @throws IOException Thrown by underlying stream.
- */
- @Override
- public void close() throws IOException {
- isClosed = true;
- if (httpClient != null && ! keepHttpClientOpen)
- httpClient.close();
- if (executorService != null && executorServiceShutdownOnClose)
- executorService.shutdown();
- if (creationStack != null)
- closedStack = Thread.currentThread().getStackTrace();
- }
-
- /**
- * Same as {@link #close()}, but ignores any exceptions.
- */
- public void closeQuietly() {
- isClosed = true;
- try {
- if (httpClient != null && ! keepHttpClientOpen)
- httpClient.close();
- if (executorService != null && executorServiceShutdownOnClose)
- executorService.shutdown();
- } catch (Throwable t) {}
- if (creationStack != null)
- closedStack = Thread.currentThread().getStackTrace();
- }
-
- /**
- * Execute the specified no-body request (e.g. GET/DELETE).
- *
- * <p>
- * Subclasses can override this method to provide specialized handling.
- *
- * @param req The HTTP request.
- * @return The HTTP response.
- * @throws IOException Stream exception occurred.
- * @throws ClientProtocolException Signals an error in the HTTP protocol.
- */
- protected HttpResponse execute(HttpRequestBase req) throws ClientProtocolException, IOException {
- return callHandler.execute(req);
- }
-
- /**
- * Execute the specified body request (e.g. POST/PUT).
- *
- * <p>
- * Subclasses can override this method to provide specialized handling.
- *
- * @param req The HTTP request.
- * @return The HTTP response.
- * @throws IOException Stream exception occurred.
- * @throws ClientProtocolException Signals an error in the HTTP protocol.
- */
- protected HttpResponse execute(HttpEntityEnclosingRequestBase req) throws ClientProtocolException, IOException {
- return callHandler.execute(req);
- }
-
- /**
- * Perform a <c>GET</c> request against the specified URL.
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doGet(Object url) throws RestCallException {
- return doCall("GET", url, false);
- }
-
- /**
- * Perform a <c>PUT</c> request against the specified URL.
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @param o
- * The object to serialize and transmit to the URL as the body of the request.
- * Can be of the following types:
- * <ul class='spaced-list'>
- * <li>
- * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource.
- * <li>
- * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource.
- * <li>
- * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the
- * {@link RestClient}.
- * <li>
- * {@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
- * </ul>
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request
- * and getting the response as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doPut(Object url, Object o) throws RestCallException {
- return doCall("PUT", url, true).body(o);
- }
-
- /**
- * Same as {@link #doPut(Object, Object)} but don't specify the input yet.
- *
- * <p>
- * You must call either {@link RestCall#body(Object)} or {@link RestCall#formData(String, Object)}
- * to set the contents on the result object.
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException REST call failed.
- */
- public RestCall doPut(Object url) throws RestCallException {
- return doCall("PUT", url, true);
- }
-
- /**
- * Perform a <c>POST</c> request against the specified URL.
- *
- * <ul class='notes'>
- * <li>Use {@link #doFormPost(Object, Object)} for <c>application/x-www-form-urlencoded</c> form posts.
- * </ul>
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @param o
- * The object to serialize and transmit to the URL as the body of the request.
- * Can be of the following types:
- * <ul class='spaced-list'>
- * <li>
- * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource.
- * <li>
- * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource.
- * <li>
- * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the {@link RestClient}.
- * <li>
- * {@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
- * </ul>
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doPost(Object url, Object o) throws RestCallException {
- return doCall("POST", url, true).body(o);
- }
-
- /**
- * Same as {@link #doPost(Object, Object)} but don't specify the input yet.
- *
- * <p>
- * You must call either {@link RestCall#body(Object)} or {@link RestCall#formData(String, Object)} to set the
- * contents on the result object.
- *
- * <ul class='notes'>
- * <li>Use {@link #doFormPost(Object, Object)} for <c>application/x-www-form-urlencoded</c> form posts.
- * </ul>
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException REST call failed.
- */
- public RestCall doPost(Object url) throws RestCallException {
- return doCall("POST", url, true);
- }
-
- /**
- * Perform a <c>DELETE</c> request against the specified URL.
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doDelete(Object url) throws RestCallException {
- return doCall("DELETE", url, false);
- }
-
- /**
- * Perform an <c>OPTIONS</c> request against the specified URL.
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doOptions(Object url) throws RestCallException {
- return doCall("OPTIONS", url, true);
- }
-
- /**
- * Perform a <c>POST</c> request with a content type of <c>application/x-www-form-urlencoded</c>
- * against the specified URL.
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @param o
- * The object to serialize and transmit to the URL as the body of the request, serialized as a form post
- * using the {@link UrlEncodingSerializer#DEFAULT} serializer.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doFormPost(Object url, Object o) throws RestCallException {
- return doCall("POST", url, true)
- .body(o instanceof HttpEntity ? o : new RestRequestEntity(o, urlEncodingSerializer, null));
- }
-
- /**
- * Perform a <c>PATCH</c> request against the specified URL.
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @param o
- * The object to serialize and transmit to the URL as the body of the request.
- * Can be of the following types:
- * <ul class='spaced-list'>
- * <li>
- * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource.
- * <li>
- * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource.
- * <li>
- * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the {@link RestClient}.
- * <li>
- * {@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
- * </ul>
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doPatch(Object url, Object o) throws RestCallException {
- return doCall("PATCH", url, true).body(o);
- }
-
- /**
- * Same as {@link #doPatch(Object, Object)} but don't specify the input yet.
- *
- * <p>
- * You must call either {@link RestCall#body(Object)} or {@link RestCall#formData(String, Object)} to set the
- * contents on the result object.
- *
- * <ul class='notes'>
- * <li>Use {@link #doFormPost(Object, Object)} for <c>application/x-www-form-urlencoded</c> form posts.
- * </ul>
- *
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException REST call failed.
- */
- public RestCall doPatch(Object url) throws RestCallException {
- return doCall("PATCH", url, true);
- }
-
-
- /**
- * Performs a REST call where the entire call is specified in a simple string.
- *
- * <p>
- * This method is useful for performing callbacks when the target of a callback is passed in
- * on an initial request, for example to signal when a long-running process has completed.
- *
- * <p>
- * The call string can be any of the following formats:
- * <ul class='spaced-list'>
- * <li>
- * <js>"[method] [url]"</js> - e.g. <js>"GET http://localhost/callback"</js>
- * <li>
- * <js>"[method] [url] [payload]"</js> - e.g. <js>"POST http://localhost/callback some text payload"</js>
- * <li>
- * <js>"[method] [headers] [url] [payload]"</js> - e.g. <js>"POST {'Content-Type':'text/json'} http://localhost/callback {'some':'json'}"</js>
- * </ul>
- * <p>
- * The payload will always be sent using a simple {@link StringEntity}.
- *
- * @param callString The call string.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException REST call failed.
- */
- public RestCall doCallback(String callString) throws RestCallException {
- String s = callString;
- try {
- RestCall rc = null;
- String method = null, uri = null, content = null;
- OMap h = null;
- int i = s.indexOf(' ');
- if (i != -1) {
- method = s.substring(0, i).trim();
- s = s.substring(i).trim();
- if (s.length() > 0) {
- if (s.charAt(0) == '{') {
- i = s.indexOf('}');
- if (i != -1) {
- String json = s.substring(0, i+1);
- h = JsonParser.DEFAULT.parse(json, OMap.class);
- s = s.substring(i+1).trim();
- }
- }
- if (s.length() > 0) {
- i = s.indexOf(' ');
- if (i == -1)
- uri = s;
- else {
- uri = s.substring(0, i).trim();
- s = s.substring(i).trim();
- if (s.length() > 0)
- content = s;
- }
- }
- }
- }
- if (method != null && uri != null) {
- rc = doCall(method, uri, content != null);
- if (content != null)
- rc.body(new StringEntity(content));
- if (h != null)
- for (Map.Entry<String,Object> e : h.entrySet())
- rc.header(e.getKey(), e.getValue());
- return rc;
- }
- } catch (Exception e) {
- throw new RestCallException(e);
- }
- throw new RestCallException("Invalid format for call string.");
- }
-
- /**
- * Perform a generic REST call.
- *
- * @param method The HTTP method.
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @param content
- * The HTTP body content.
- * Can be of the following types:
- * <ul class='spaced-list'>
- * <li>
- * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource.
- * <li>
- * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource.
- * <li>
- * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the
- * {@link RestClient}.
- * <li>
- * {@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
- * <li>
- * {@link NameValuePairs} - Converted to a URL-encoded FORM post.
- * </ul>
- * This parameter is IGNORED if {@link HttpMethod#hasContent()} is <jk>false</jk>.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doCall(HttpMethod method, Object url, Object content) throws RestCallException {
- RestCall rc = doCall(method.name(), url, method.hasContent());
- if (method.hasContent())
- rc.body(content);
- return rc;
- }
-
- /**
- * Perform a generic REST call.
- *
- * @param method The method name (e.g. <js>"GET"</js>, <js>"OPTIONS"</js>).
- * @param url
- * The URL of the remote REST resource.
- * Can be any of the following: {@link String}, {@link URI}, {@link URL}.
- * @param hasContent Boolean flag indicating if the specified request has content associated with it.
- * @return
- * A {@link RestCall} object that can be further tailored before executing the request and getting the response
- * as a parsed object.
- * @throws RestCallException If any authentication errors occurred.
- */
- public RestCall doCall(String method, Object url, boolean hasContent) throws RestCallException {
- if (isClosed) {
- Exception e2 = null;
- if (closedStack != null) {
- e2 = new Exception("Creation stack:");
- e2.setStackTrace(closedStack);
- throw new RestCallException(e2, "RestClient.close() has already been called. This client cannot be reused.");
- }
- throw new RestCallException("RestClient.close() has already been called. This client cannot be reused. Closed location stack trace can be displayed by setting the system property 'org.apache.juneau.rest.client.RestClient.trackCreation' to true.");
- }
-
- HttpRequestBase req = null;
- RestCall restCall = null;
- final String methodUC = method.toUpperCase(Locale.ENGLISH);
- try {
- if (hasContent) {
- req = new HttpEntityEnclosingRequestBase() {
- @Override /* HttpRequest */
- public String getMethod() {
- return methodUC;
- }
- };
- restCall = new RestCall(this, req, toURI(url));
- } else {
- req = new HttpRequestBase() {
- @Override /* HttpRequest */
- public String getMethod() {
- return methodUC;
- }
- };
- restCall = new RestCall(this, req, toURI(url));
- }
- } catch (URISyntaxException e1) {
- throw new RestCallException(e1);
- }
-
- for (Map.Entry<String,String> e : query.entrySet())
- restCall.query(e.getKey(), e.getValue());
-
- for (Map.Entry<String,String> e : headers.entrySet())
- restCall.header(e.getKey(), e.getValue());
-
- if (parser != null && ! req.containsHeader("Accept"))
- req.setHeader("Accept", parser.getPrimaryMediaType().toString());
-
- return restCall;
- }
-
- /**
- * Create a new proxy interface against a 3rd-party REST interface.
- *
- * <p>
- * The URL to the REST interface is based on the following values:
- * <ul>
- * <li>The {@link Remote#path() @Remote(path)} annotation on the interface (<c>remote-path</c>).
- * <li>The {@link RestClientBuilder#rootUrl(Object) rootUrl} on the client (<c>root-url</c>).
- * <li>The fully-qualified class name of the interface (<c>class-name</c>).
- * </ul>
- *
- * <p>
- * The URL calculation is as follows:
- * <ul>
- * <li><c>remote-path</c> - If remote path is absolute.
- * <li><c>root-url/remote-path</c> - If remote path is relative and root-url has been specified.
- * <li><c>root-url/class-name</c> - If remote path is not specified.
- * </ul>
- *
- * <p>
- * If the information is not available to resolve to an absolute URL, a {@link RemoteMetadataException} is thrown.
- *
- * <p>
- * Examples:
- * <p class='bcode w800'>
- * <jk>package</jk> org.apache.foo;
- *
- * <ja>@RemoteResource</ja>(path=<js>"http://hostname/resturl/myinterface1"</js>)
- * <jk>public interface</jk> MyInterface1 { ... }
- *
- * <ja>@RemoteResource</ja>(path=<js>"/myinterface2"</js>)
- * <jk>public interface</jk> MyInterface2 { ... }
- *
- * <jk>public interface</jk> MyInterface3 { ... }
- *
- * <jc>// Resolves to "http://localhost/resturl/myinterface1"</jc>
- * MyInterface1 i1 = RestClient
- * .<jsm>create</jsm>()
- * .build()
- * .getRemoteResource(MyInterface1.<jk>class</jk>);
- *
- * <jc>// Resolves to "http://hostname/resturl/myinterface2"</jc>
- * MyInterface2 i2 = RestClient
- * .<jsm>create</jsm>()
- * .rootUrl(<js>"http://hostname/resturl"</js>)
- * .build()
- * .getRemoteResource(MyInterface2.<jk>class</jk>);
- *
- * <jc>// Resolves to "http://hostname/resturl/org.apache.foo.MyInterface3"</jc>
- * MyInterface3 i3 = RestClient
- * .<jsm>create</jsm>()
- * .rootUrl(<js>"http://hostname/resturl"</js>)
- * .build()
- * .getRemoteResource(MyInterface3.<jk>class</jk>);
- * </p>
- *
- * <ul class='notes'>
- * <li>
- * If you plan on using your proxy in a multi-threaded environment, you'll want to use an underlying
- * pooling client connection manager.
- * </ul>
- *
- * @param interfaceClass The interface to create a proxy for.
- * @return The new proxy interface.
- * @throws RemoteMetadataException If the REST URI cannot be determined based on the information given.
- */
- public <T> T getRemote(final Class<T> interfaceClass) {
- return getRemote(interfaceClass, null);
- }
-
- /**
- * Same as {@link #getRemote(Class)} except explicitly specifies the URL of the REST interface.
- *
- * @param interfaceClass The interface to create a proxy for.
- * @param restUrl The URL of the REST interface.
- * @return The new proxy interface.
- */
- public <T> T getRemote(final Class<T> interfaceClass, final Object restUrl) {
- return getRemote(interfaceClass, restUrl, serializer, parser);
- }
-
- /**
- * Same as {@link #getRemote(Class, Object)} but allows you to override the serializer and parser used.
- *
- * @param interfaceClass The interface to create a proxy for.
- * @param restUrl The URL of the REST interface.
- * @param serializer The serializer used to serialize POJOs to the body of the HTTP request.
- * @param parser The parser used to parse POJOs from the body of the HTTP response.
- * @return The new proxy interface.
- */
- @SuppressWarnings({ "unchecked" })
- public <T> T getRemote(final Class<T> interfaceClass, Object restUrl, final Serializer serializer, final Parser parser) {
-
- if (restUrl == null)
- restUrl = rootUrl;
-
- final String restUrl2 = trimSlashes(emptyIfNull(restUrl));
-
- try {
- return (T)Proxy.newProxyInstance(
- interfaceClass.getClassLoader(),
- new Class[] { interfaceClass },
- new InvocationHandler() {
-
- final RemoteMeta rm = new RemoteMeta(interfaceClass);
-
- @Override /* InvocationHandler */
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- RemoteMethodMeta rmm = rm.getMethodMeta(method);
-
- if (rmm == null)
- throw new RuntimeException("Method is not exposed as a remote method.");
-
- String url = rmm.getFullPath();
- if (url.indexOf("://") == -1)
- url = restUrl2 + '/' + url;
- if (url.indexOf("://") == -1)
- throw new RemoteMetadataException(interfaceClass, "Root URI has not been specified. Cannot construct absolute path to remote resource.");
-
- String httpMethod = rmm.getHttpMethod();
- HttpPartSerializer s = getPartSerializer();
-
- try (RestCall rc = doCall(httpMethod, url, hasContent(httpMethod))) {
-
- rc.serializer(serializer).parser(parser);
-
- for (RemoteMethodArg a : rmm.getPathArgs())
- rc.path(a.getName(), args[a.getIndex()], s, a.getSchema());
-
- for (RemoteMethodArg a : rmm.getQueryArgs())
- rc.query(a.getName(), args[a.getIndex()], a.isSkipIfEmpty(), s, a.getSchema());
-
- for (RemoteMethodArg a : rmm.getFormDataArgs())
- rc.formData(a.getName(), args[a.getIndex()], a.isSkipIfEmpty(), s, a.getSchema());
-
- for (RemoteMethodArg a : rmm.getHeaderArgs())
- rc.header(a.getName(), args[a.getIndex()], a.isSkipIfEmpty(), s, a.getSchema());
-
- RemoteMethodArg ba = rmm.getBodyArg();
- if (ba != null)
- rc.requestBodySchema(ba.getSchema()).body(args[ba.getIndex()]);
-
- if (rmm.getRequestArgs().length > 0) {
- for (RemoteMethodBeanArg rmba : rmm.getRequestArgs()) {
- RequestBeanMeta rbm = rmba.getMeta();
- Object bean = args[rmba.getIndex()];
- if (bean != null) {
- for (RequestBeanPropertyMeta p : rbm.getProperties()) {
- Object val = p.getGetter().invoke(bean);
- HttpPartType pt = p.getPartType();
- HttpPartSerializer ps = p.getSerializer(s);
- String pn = p.getPartName();
- HttpPartSchema schema = p.getSchema();
- boolean sie = schema.isSkipIfEmpty();
- if (pt == PATH)
- rc.path(pn, val, p.getSerializer(s), schema);
- else if (val != null) {
- if (pt == QUERY)
- rc.query(pn, val, sie, ps, schema);
- else if (pt == FORMDATA)
- rc.formData(pn, val, sie, ps, schema);
- else if (pt == HEADER)
- rc.header(pn, val, sie, ps, schema);
- else
- rc.requestBodySchema(schema).body(val);
- }
- }
- }
- }
- }
-
- RemoteMethodReturn rmr = rmm.getReturns();
- if (rmr.getReturnValue() == RemoteReturn.NONE) {
- rc.run();
- return null;
- } else if (rmr.getReturnValue() == RemoteReturn.STATUS) {
- rc.ignoreErrors();
- int returnCode = rc.run();
- Class<?> rt = method.getReturnType();
- if (rt == Integer.class || rt == int.class)
- return returnCode;
- if (rt == Boolean.class || rt == boolean.class)
- return returnCode < 400;
- throw new RestCallException("Invalid return type on method annotated with @RemoteMethod(returns=HTTP_STATUS). Only integer and booleans types are valid.");
- } else if (rmr.getReturnValue() == RemoteReturn.BEAN) {
- return rc.getResponse(rmr.getResponseBeanMeta());
- } else {
- Object v = rc.getResponseBody(rmr.getReturnType());
- if (v == null && method.getReturnType().isPrimitive())
- v = ClassInfo.of(method.getReturnType()).getPrimitiveDefault();
- return v;
- }
-
- } catch (RestCallException e) {
- // Try to throw original exception if possible.
- e.throwServerException(interfaceClass.getClassLoader(), rmm.getExceptions());
- throw new RuntimeException(e);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- });
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @SuppressWarnings("javadoc")
- @Deprecated
- public <T> T getRemoteResource(final Class<T> interfaceClass) {
- return getRemote(interfaceClass, null);
- }
-
- @SuppressWarnings("javadoc")
- @Deprecated
- public <T> T getRemoteResource(final Class<T> interfaceClass, final Object restUrl) {
- return getRemote(interfaceClass, null);
- }
-
- @SuppressWarnings("javadoc")
- @Deprecated
- public <T> T getRemoteResource(final Class<T> interfaceClass, Object restUrl, final Serializer serializer, final Parser parser) {
- return getRemote(interfaceClass, null);
- }
-
- /**
- * Create a new Remote Interface against a {@link RemoteInterface @RemoteInterface}-annotated class.
- *
- * <p>
- * Remote interfaces are interfaces exposed on the server side using either the <c>RrpcServlet</c>
- * or <c>RRPC</c> REST methods.
- *
- * <p>
- * The URL to the REST interface is based on the following values:
- * <ul>
- * <li>The {@link Remote#path() @Remote(path)} annotation on the interface (<c>remote-path</c>).
- * <li>The {@link RestClientBuilder#rootUrl(Object) rootUrl} on the client (<c>root-url</c>).
- * <li>The fully-qualified class name of the interface (<c>class-name</c>).
- * </ul>
- *
- * <p>
- * The URL calculation is as follows:
- * <ul>
- * <li><c>remote-path</c> - If remote path is absolute.
- * <li><c>root-url/remote-path</c> - If remote path is relative and root-url has been specified.
- * <li><c>root-url/class-name</c> - If remote path is not specified.
- * </ul>
- *
- * <p>
- * If the information is not available to resolve to an absolute URL, a {@link RemoteMetadataException} is thrown.
- *
- * <ul class='notes'>
- * <li>
- * If you plan on using your proxy in a multi-threaded environment, you'll want to use an underlying
- * pooling client connection manager.
- * </ul>
- *
- * @param interfaceClass The interface to create a proxy for.
- * @return The new proxy interface.
- * @throws RemoteMetadataException If the REST URI cannot be determined based on the information given.
- */
- public <T> T getRrpcInterface(final Class<T> interfaceClass) {
- return getRrpcInterface(interfaceClass, null);
- }
-
- /**
- * Same as {@link #getRrpcInterface(Class)} except explicitly specifies the URL of the REST interface.
- *
- * @param interfaceClass The interface to create a proxy for.
- * @param restUrl The URL of the REST interface.
- * @return The new proxy interface.
- */
- public <T> T getRrpcInterface(final Class<T> interfaceClass, final Object restUrl) {
- return getRrpcInterface(interfaceClass, restUrl, serializer, parser);
- }
-
- /**
- * Same as {@link #getRrpcInterface(Class, Object)} but allows you to override the serializer and parser used.
- *
- * @param interfaceClass The interface to create a proxy for.
- * @param restUrl The URL of the REST interface.
- * @param serializer The serializer used to serialize POJOs to the body of the HTTP request.
- * @param parser The parser used to parse POJOs from the body of the HTTP response.
- * @return The new proxy interface.
- */
- @SuppressWarnings({ "unchecked" })
- public <T> T getRrpcInterface(final Class<T> interfaceClass, Object restUrl, final Serializer serializer, final Parser parser) {
-
- if (restUrl == null) {
- RrpcInterfaceMeta rm = new RrpcInterfaceMeta(interfaceClass, stringify(restUrl));
- String path = rm.getPath();
- if (path.indexOf("://") == -1) {
- if (rootUrl == null)
- throw new RemoteMetadataException(interfaceClass, "Root URI has not been specified. Cannot construct absolute path to remote interface.");
- path = trimSlashes(rootUrl) + '/' + path;
- }
- restUrl = path;
- }
-
- final String restUrl2 = stringify(restUrl);
-
- try {
- return (T)Proxy.newProxyInstance(
- interfaceClass.getClassLoader(),
- new Class[] { interfaceClass },
- new InvocationHandler() {
-
- final RrpcInterfaceMeta rm = new RrpcInterfaceMeta(interfaceClass, restUrl2);
-
- @Override /* InvocationHandler */
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- RrpcInterfaceMethodMeta rim = rm.getMethodMeta(method);
-
- if (rim == null)
- throw new RuntimeException("Method is not exposed as a remote method.");
-
- String url = rim.getUri();
-
- try (RestCall rc = doCall("POST", url, true)) {
-
- rc.serializer(serializer).parser(parser).body(args);
-
- Object v = rc.getResponse(method.getGenericReturnType());
- if (v == null && method.getReturnType().isPrimitive())
- v = ClassInfo.of(method.getReturnType()).getPrimitiveDefault();
- return v;
-
- } catch (RestCallException e) {
- // Try to throw original exception if possible.
- e.throwServerException(interfaceClass.getClassLoader(), method.getExceptionTypes());
- throw new RuntimeException(e);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- });
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- static final String getName(String name1, String name2, BeanPropertyMeta pMeta) {
- String n = name1.isEmpty() ? name2 : name1;
- ClassMeta<?> cm = pMeta.getClassMeta();
- if (n.isEmpty() && (cm.isMapOrBean() || cm.isReader() || cm.isInstanceOf(NameValuePairs.class)))
- n = "*";
- if (n.isEmpty())
- n = pMeta.getName();
- return n;
- }
-
- final HttpPartSerializer getPartSerializer(Class c, HttpPartSerializer c2) {
- if (c2 != null)
- return c2;
- if (c == HttpPartSerializer.Null.class)
- return null;
- HttpPartSerializer pf = partSerializerCache.get(c);
- if (pf == null) {
- partSerializerCache.putIfAbsent(c, castOrCreate(HttpPartSerializer.class, c, true, getPropertyStore()));
- pf = partSerializerCache.get(c);
- }
- return pf;
- }
-
- private Pattern absUrlPattern = Pattern.compile("^\\w+\\:\\/\\/.*");
-
- HttpPartSerializer getPartSerializer() {
- return partSerializer;
- }
-
- HttpPartParser getPartParser() {
- return partParser;
- }
-
- URI toURI(Object url) throws URISyntaxException {
- if (url instanceof URI)
- return (URI)url;
- if (url instanceof URL)
- ((URL)url).toURI();
- if (url instanceof URIBuilder)
- return ((URIBuilder)url).build();
- String s = url == null ? "" : url.toString();
- if (rootUrl != null && ! absUrlPattern.matcher(s).matches()) {
- if (s.isEmpty())
- s = rootUrl;
- else {
- StringBuilder sb = new StringBuilder(rootUrl);
- if (! s.startsWith("/"))
- sb.append('/');
- sb.append(s);
- s = sb.toString();
- }
- }
- if (s.indexOf('{') != -1)
- s = s.replace("{", "%7B").replace("}", "%7D");
- return new URI(s);
- }
-
- ExecutorService getExecutorService(boolean create) {
- if (executorService != null || ! create)
- return executorService;
- synchronized(this) {
- if (executorService == null)
- executorService = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
- return executorService;
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- if (! isClosed && ! keepHttpClientOpen) {
- System.err.println("WARNING: RestClient garbage collected before it was finalized."); // NOT DEBUG
- if (creationStack != null) {
- System.err.println("Creation Stack:"); // NOT DEBUG
- for (StackTraceElement e : creationStack)
- System.err.println(e); // NOT DEBUG
- } else {
- System.err.println("Creation stack traces can be displayed by setting the system property 'org.apache.juneau.rest.client.RestClient.trackLifecycle' to true."); // NOT DEBUG
- }
- }
- }
-
- //-----------------------------------------------------------------------------------------------------------------
- // Other methods.
- //-----------------------------------------------------------------------------------------------------------------
-
- @Override /* Context */
- public OMap toMap() {
- return super.toMap()
- .a("RestClient", new DefaultFilteringOMap()
- .a("debug", debug)
- .a("executorService", executorService)
- .a("executorServiceShutdownOnClose", executorServiceShutdownOnClose)
- .a("headers", headers)
- .a("interceptors", interceptors)
- .a("keepHttpClientOpen", keepHttpClientOpen)
- .a("parser", parser)
- .a("partParser", partParser)
- .a("partSerializer", partSerializer)
- .a("query", query)
- .a("retries", retries)
- .a("retryInterval", retryInterval)
- .a("retryOn", retryOn)
- .a("rootUri", rootUrl)
- .a("serializer", serializer)
- );
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClientBuilder.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClientBuilder.java
deleted file mode 100644
index 2b8659c..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestClientBuilder.java
+++ /dev/null
@@ -1,3274 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import static org.apache.juneau.internal.StringUtils.*;
-import static org.apache.juneau.parser.InputStreamParser.*;
-import static org.apache.juneau.parser.ReaderParser.*;
-import static org.apache.juneau.rest.client.RestClient.*;
-import static org.apache.juneau.BeanTraverseContext.*;
-import static org.apache.juneau.serializer.OutputStreamSerializer.*;
-import static org.apache.juneau.serializer.WriterSerializer.*;
-import static org.apache.juneau.uon.UonSerializer.*;
-
-import java.lang.annotation.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.net.URI;
-import java.security.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.logging.*;
-
-import javax.net.ssl.*;
-
-import org.apache.http.*;
-import org.apache.http.auth.*;
-import org.apache.http.client.*;
-import org.apache.http.client.CookieStore;
-import org.apache.http.client.config.*;
-import org.apache.http.client.entity.*;
-import org.apache.http.config.*;
-import org.apache.http.conn.*;
-import org.apache.http.conn.routing.*;
-import org.apache.http.conn.socket.*;
-import org.apache.http.conn.ssl.*;
-import org.apache.http.conn.util.*;
-import org.apache.http.cookie.*;
-import org.apache.http.impl.client.*;
-import org.apache.http.impl.conn.*;
-import org.apache.http.protocol.*;
-import org.apache.juneau.*;
-import org.apache.juneau.html.*;
-import org.apache.juneau.http.*;
-import org.apache.juneau.httppart.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.marshall.*;
-import org.apache.juneau.msgpack.*;
-import org.apache.juneau.oapi.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.plaintext.*;
-import org.apache.juneau.reflect.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.svl.*;
-import org.apache.juneau.uon.*;
-import org.apache.juneau.urlencoding.*;
-import org.apache.juneau.xml.*;
-
-/**
- * Builder class for the {@link RestClient} class.
- *
- * <p>
- * Instances of this class are created by the following methods:
- * <ul>
- * <li>{@link RestClient#create()} - Create from scratch.
- * <li>{@link RestClient#create(Serializer,Parser)} - Create from scratch using specified serializer/parser.
- * <li>{@link RestClient#create(Class,Class)} - Create from scratch using specified serializer/parser classes.
- * <li>{@link RestClient#builder()} - Copy settings from an existing client.
- * </ul>
- *
- * <ul class='seealso'>
- * <li class='link'>{@doc juneau-rest-client}
- * </ul>
- *
- * @deprecated Use {@link org.apache.juneau.rest.client2.RestClientBuilder}
- */
-@Deprecated
-public class RestClientBuilder extends BeanContextBuilder {
-
- private HttpClientBuilder httpClientBuilder;
- private CloseableHttpClient httpClient;
-
- // Deprecated
- @Deprecated private HttpClientConnectionManager httpClientConnectionManager;
- @Deprecated private boolean enableSsl = false;
- @Deprecated private HostnameVerifier hostnameVerifier;
- @Deprecated private KeyManager[] keyManagers;
- @Deprecated private TrustManager[] trustManagers;
- @Deprecated private SecureRandom secureRandom;
- @Deprecated private String[] sslProtocols, cipherSuites;
- @Deprecated private boolean pooled;
-
- /**
- * Constructor.
- * @param ps
- * Initial configuration properties for this builder.
- * <br>Can be <jk>null</jk>.
- * @param httpClientBuilder
- * The HTTP client builder to use for this REST client builder.
- * <br>Can be <jk>null</jk> to just call {@link #createHttpClientBuilder()} to instantiate it again.
- */
- protected RestClientBuilder(PropertyStore ps, HttpClientBuilder httpClientBuilder) {
- super(ps);
- this.httpClientBuilder = httpClientBuilder != null ? httpClientBuilder : createHttpClientBuilder();
- }
-
- @Override /* ContextBuilder */
- public RestClient build() {
- return new RestClient(this);
- }
-
- //------------------------------------------------------------------------------------------------------------------
- // Convenience marshalling support methods.
- //------------------------------------------------------------------------------------------------------------------
-
- /**
- * Convenience method for specifying JSON as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(JsonSerializer.<jk>class</jk>).parser(JsonParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder json() {
- return serializer(JsonSerializer.class).parser(JsonParser.class);
- }
-
- /**
- * Convenience method for specifying Simple JSON as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(SimpleJsonSerializer.<jk>class</jk>).parser(JsonParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder simpleJson() {
- return serializer(SimpleJsonSerializer.class).parser(JsonParser.class);
- }
-
- /**
- * Convenience method for specifying XML as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(XmlSerializer.<jk>class</jk>).parser(XmlParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder xml() {
- return serializer(XmlSerializer.class).parser(XmlParser.class);
- }
-
- /**
- * Convenience method for specifying HTML as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(HtmlSerializer.<jk>class</jk>).parser(HtmlParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder html() {
- return serializer(HtmlSerializer.class).parser(HtmlParser.class);
- }
-
- /**
- * Convenience method for specifying plain-text as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(PlainTextSerializer.<jk>class</jk>).parser(PlainTextParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder plainText() {
- return serializer(PlainTextSerializer.class).parser(PlainTextParser.class);
- }
-
- /**
- * Convenience method for specifying MessagePack as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(MsgPackSerializer.<jk>class</jk>).parser(MsgPackParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder msgpack() {
- return serializer(MsgPackSerializer.class).parser(MsgPackParser.class);
- }
-
- /**
- * Convenience method for specifying UON as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(UonSerializer.<jk>class</jk>).parser(UonParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder uon() {
- return serializer(UonSerializer.class).parser(UonParser.class);
- }
-
- /**
- * Convenience method for specifying URL-Encoding as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(UrlEncodingSerializer.<jk>class</jk>).parser(UrlEncodingParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder urlEnc() {
- return serializer(UrlEncodingSerializer.class).parser(UrlEncodingParser.class);
- }
-
- /**
- * Convenience method for specifying URL-Encoding as the transmission media type.
- *
- * <p>
- * Identical to calling <code>serializer(OpenApiSerializer.<jk>class</jk>).parser(OpenApiParser.<jk>class</jk>)</code>.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder openapi() {
- return serializer(OpenApiSerializer.class).parser(OpenApiParser.class);
- }
-
- //------------------------------------------------------------------------------------------------------------------
- // HttpClientBuilder
- //------------------------------------------------------------------------------------------------------------------
-
- /**
- * Creates an instance of an {@link HttpClientBuilder} to be used to create the {@link HttpClient}.
- *
- * <p>
- * Subclasses can override this method to provide their own client builder.
- * The builder can also be specified using the {@link #httpClientBuilder(HttpClientBuilder)} method.
- *
- * <p>
- * The predefined method returns an {@link HttpClientBuilder} with the following settings:
- * <ul>
- * <li>Lax redirect strategy.
- * </ul>
- *
- * @return The HTTP client builder to use to create the HTTP client.
- */
- protected HttpClientBuilder createHttpClientBuilder() {
- return HttpClientBuilder.create().setRedirectStrategy(new AllowAllRedirects());
- }
-
- /**
- * Returns the {@link HttpClientBuilder} that will be used to create the {@link HttpClient} used by {@link RestClient}.
- *
- * <p>
- * This method can be used to make customizations to the {@link HttpClient}.
- *
- * <p>
- * If not set via {@link #httpClientBuilder(HttpClientBuilder)}, then this object is the one created by {@link #createHttpClientBuilder()}.
- *
- * @return The {@link HttpClientBuilder} that will be used to create the {@link HttpClient} used by {@link RestClient}.
- */
- public HttpClientBuilder getHttpClientBuilder() {
- if (httpClientBuilder == null)
- httpClientBuilder = createHttpClientBuilder();
- return httpClientBuilder;
- }
-
- /**
- * Sets the {@link HttpClientBuilder} that will be used to create the {@link HttpClient} used by {@link RestClient}.
- *
- * <p>
- * This can be used to bypass the builder created by {@link #createHttpClientBuilder()} method.
- *
- * @param value The {@link HttpClientBuilder} that will be used to create the {@link HttpClient} used by {@link RestClient}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder httpClientBuilder(HttpClientBuilder value) {
- this.httpClientBuilder = value;
- return this;
- }
-
- //------------------------------------------------------------------------------------------------------------------
- // HttpClient
- //------------------------------------------------------------------------------------------------------------------
-
- /**
- * Creates an instance of an {@link HttpClient} to be used to handle all HTTP communications with the target server.
- *
- * <p>
- * This HTTP client is used when the HTTP client is not specified through one of the constructors or the
- * {@link #httpClient(CloseableHttpClient, boolean)} method.
- *
- * <p>
- * Subclasses can override this method to provide specially-configured HTTP clients to handle stuff such as
- * SSL/TLS certificate handling, authentication, etc.
- *
- * <p>
- * The default implementation returns an instance of {@link HttpClient} using the client builder returned by
- * {@link #createHttpClientBuilder()}.
- *
- * @return The HTTP client to use.
- * @throws Exception Error occurred.
- */
- protected CloseableHttpClient createHttpClient() throws Exception {
- // Don't call createConnectionManager() if RestClient.setConnectionManager() was called.
- if (httpClientConnectionManager == null)
- httpClientBuilder.setConnectionManager(createConnectionManager());
- else
- httpClientBuilder.setConnectionManager(httpClientConnectionManager);
- return httpClientBuilder.build();
- }
-
- /**
- * Returns the {@link HttpClient} to be used to handle all HTTP communications with the target server.
- *
- * @return The {@link HttpClient} to be used to handle all HTTP communications with the target server.
- */
- public CloseableHttpClient getHttpClient() {
- try {
- return httpClient != null ? httpClient : createHttpClient();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Sets the {@link HttpClient} to be used to handle all HTTP communications with the target server.
- *
- * <p>
- * This can be used to bypass the client created by {@link #createHttpClient()} method.
- *
- * @param value The {@link HttpClient} to be used to handle all HTTP communications with the target server.
- * @return This object (for method chaining).
- */
- public RestClientBuilder httpClient(CloseableHttpClient value) {
- this.httpClient = value;
- return this;
- }
-
- /**
- * Sets the internal {@link HttpClient} to use for handling HTTP communications.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #httpClient(CloseableHttpClient)} and {@link #keepHttpClientOpen(boolean)}
- * </div>
- *
- * @param httpClient The HTTP client.
- * @param keepHttpClientOpen Don't close this client when the {@link RestClient#close()} method is called.
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder httpClient(CloseableHttpClient httpClient, boolean keepHttpClientOpen) {
- this.httpClient = httpClient;
- set(RESTCLIENT_keepHttpClientOpen, keepHttpClientOpen);
- return this;
- }
-
- //------------------------------------------------------------------------------------------------------------------
- // Logging.
- //------------------------------------------------------------------------------------------------------------------
-
- /**
- * Adds a {@link RestCallLogger} to the list of interceptors on this class.
- *
- * @param level The log level to log messages at.
- * @param log The logger to log messages to.
- * @return This object (for method chaining).
- */
- public RestClientBuilder logTo(Level level, Logger log) {
- return interceptors(new RestCallLogger(level, log));
- }
-
- /**
- * Sets the internal {@link HttpClientConnectionManager}.
- *
- * @param httpClientConnectionManager The HTTP client connection manager.
- * @return This object (for method chaining).
- */
- public RestClientBuilder httpClientConnectionManager(HttpClientConnectionManager httpClientConnectionManager) {
- this.httpClientConnectionManager = httpClientConnectionManager;
- return this;
- }
-
- //------------------------------------------------------------------------------------------------------------------
- // Deprecated HttpClientBuilder methods.
- //------------------------------------------------------------------------------------------------------------------
-
- /**
- * Creates the {@link HttpClientConnectionManager} returned by {@link #createConnectionManager()}.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * Subclasses can override this method to provide their own connection manager.
- *
- * <p>
- * The default implementation returns an instance of a {@link PoolingHttpClientConnectionManager}.
- *
- * @return The HTTP client builder to use to create the HTTP client.
- * @throws NoSuchAlgorithmException Unknown cryptographic algorithm.
- * @throws KeyManagementException General key management exception.
- */
- @SuppressWarnings("resource")
- @Deprecated
- protected HttpClientConnectionManager createConnectionManager() throws KeyManagementException, NoSuchAlgorithmException {
- if (enableSsl) {
-
- HostnameVerifier hv = hostnameVerifier != null ? hostnameVerifier : new DefaultHostnameVerifier();
- TrustManager[] tm = trustManagers;
- String[] sslp = sslProtocols == null ? getDefaultProtocols() : sslProtocols;
- SecureRandom sr = secureRandom;
- KeyManager[] km = keyManagers;
- String[] cs = cipherSuites;
-
- RegistryBuilder<ConnectionSocketFactory> rb = RegistryBuilder.<ConnectionSocketFactory>create();
- rb.register("http", PlainConnectionSocketFactory.getSocketFactory());
-
- SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().build();
- sslContext.init(km, tm, sr);
-
- SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslContext, sslp, cs, hv);
- rb.register("https", sslcsf).build();
-
- return (pooled ? new PoolingHttpClientConnectionManager(rb.build()) : new BasicHttpClientConnectionManager(rb.build()));
- }
-
- // Using pooling connection so that this client is threadsafe.
- return (pooled ? new PoolingHttpClientConnectionManager() : new BasicHttpClientConnectionManager());
- }
-
- private static String[] getDefaultProtocols() {
- String sp = System.getProperty("transport.client.protocol");
- if (isEmpty(sp))
- return new String[] {"SSL_TLS","TLS","SSL"};
- return StringUtils.split(sp, ',');
- }
-
- /**
- * Enable SSL support on this client.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * Used in conjunction with the following methods for setting up SSL parameters:
- * <ul class='javatree'>
- * <li class='jf'>{@link #sslProtocols(String...)}
- * <li class='jf'>{@link #cipherSuites(String...)}
- * <li class='jf'>{@link #hostnameVerifier(HostnameVerifier)}
- * <li class='jf'>{@link #keyManagers(KeyManager...)}
- * <li class='jf'>{@link #trustManagers(TrustManager...)}
- * <li class='jf'>{@link #secureRandom(SecureRandom)}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder enableSSL() {
- this.enableSsl = true;
- return this;
- }
-
- /**
- * Enable LARestClientBuilder SSL support.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * Same as calling the following:
- * <p class='bcode w800'>
- * builder
- * .enableSSL()
- * .hostnameVerifier(<jk>new</jk> NoopHostnameVerifier())
- * .trustManagers(<jk>new</jk> SimpleX509TrustManager(<jk>true</jk>));
- * </p>
- *
- * @return This object (for method chaining).
- * @throws KeyStoreException Generic keystore exception.
- * @throws NoSuchAlgorithmException Unknown cryptographic algorithm.
- */
- @Deprecated
- public RestClientBuilder enableLaxSSL() throws KeyStoreException, NoSuchAlgorithmException {
- this.enableSsl = true;
- hostnameVerifier(new NoopHostnameVerifier());
- trustManagers(new SimpleX509TrustManager(true));
- return this;
- }
-
- /**
- * Supported SSL protocols.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * This is the value passed to the <c>supportedProtocols</c> parameter of the
- * {@link SSLConnectionSocketFactory#SSLConnectionSocketFactory(SSLContext,String[],String[],HostnameVerifier)}
- * constructor.
- *
- * <p>
- * The default value is taken from the system property <js>"transport.client.protocol"</js>.
- * <br>If system property is not defined, defaults to <code>{<js>"SSL_TLS"</js>,<js>"TLS"</js>,<js>"SSL"</js>}</code>.
- *
- * <p>
- * This method is effectively ignored if {@link #enableSSL()} has not been called or the client connection manager
- * has been defined via {@link #httpClientConnectionManager(HttpClientConnectionManager)}.
- *
- * @param sslProtocols The supported SSL protocols.
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder sslProtocols(String...sslProtocols) {
- this.sslProtocols = sslProtocols;
- return this;
- }
-
- /**
- * Supported cipher suites.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * This is the value passed to the <c>supportedCipherSuites</c> parameter of the
- * {@link SSLConnectionSocketFactory#SSLConnectionSocketFactory(SSLContext,String[],String[],HostnameVerifier)}
- * constructor.
- *
- * <p>
- * The default value is <jk>null</jk>.
- *
- * <p>
- * This method is effectively ignored if {@link #enableSSL()} has not been called or the client connection manager
- * has been defined via {@link #httpClientConnectionManager(HttpClientConnectionManager)}.
- *
- * @param cipherSuites The supported cipher suites.
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder cipherSuites(String...cipherSuites) {
- this.cipherSuites = cipherSuites;
- return this;
- }
-
- /**
- * Hostname verifier.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * This is the value passed to the <c>hostnameVerifier</c> parameter of the
- * {@link SSLConnectionSocketFactory#SSLConnectionSocketFactory(SSLContext,String[],String[],HostnameVerifier)}
- * constructor.
- *
- * <p>
- * The default value is <jk>null</jk>.
- *
- * <p>
- * This method is effectively ignored if {@link #enableSSL()} has not been called or the client connection manager
- * has been defined via {@link #httpClientConnectionManager(HttpClientConnectionManager)}.
- *
- * @param hostnameVerifier The hostname verifier.
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder hostnameVerifier(HostnameVerifier hostnameVerifier) {
- this.hostnameVerifier = hostnameVerifier;
- return this;
- }
-
- /**
- * Key managers.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * This is the value passed to the <c>keyManagers</c> parameter of the
- * {@link SSLContext#init(KeyManager[],TrustManager[],SecureRandom)} method.
- *
- * <p>
- * The default value is <jk>null</jk>.
- *
- * <p>
- * This method is effectively ignored if {@link #enableSSL()} has not been called or the client connection manager
- * has been defined via {@link #httpClientConnectionManager(HttpClientConnectionManager)}.
- *
- * @param keyManagers The key managers.
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder keyManagers(KeyManager...keyManagers) {
- this.keyManagers = keyManagers;
- return this;
- }
-
- /**
- * Trust managers.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * This is the value passed to the <c>trustManagers</c> parameter of the
- * {@link SSLContext#init(KeyManager[],TrustManager[],SecureRandom)} method.
- *
- * <p>
- * The default value is <jk>null</jk>.
- *
- * <p>
- * This method is effectively ignored if {@link #enableSSL()} has not been called or the client connection manager
- * has been defined via {@link #httpClientConnectionManager(HttpClientConnectionManager)}.
- *
- * @param trustManagers The trust managers.
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder trustManagers(TrustManager...trustManagers) {
- this.trustManagers = trustManagers;
- return this;
- }
-
- /**
- * Trust managers.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * <p>
- * This is the value passed to the <c>random</c> parameter of the
- * {@link SSLContext#init(KeyManager[],TrustManager[],SecureRandom)} method.
- *
- * <p>
- * The default value is <jk>null</jk>.
- *
- * <p>
- * This method is effectively ignored if {@link #enableSSL()} has not been called or the client connection manager
- * has been defined via {@link #httpClientConnectionManager(HttpClientConnectionManager)}.
- *
- * @param secureRandom The random number generator.
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder secureRandom(SecureRandom secureRandom) {
- this.secureRandom = secureRandom;
- return this;
- }
-
- /**
- * When called, the {@link #createConnectionManager()} method will return a {@link PoolingHttpClientConnectionManager}
- * instead of a {@link BasicHttpClientConnectionManager}.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder pooled() {
- this.pooled = true;
- return this;
- }
-
- /**
- * Set up this client to use BASIC auth.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use {@link #getHttpClientBuilder()} and modify the client builder directly using {@link HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)}
- * </div>
- *
- * @param host The auth scope hostname.
- * @param port The auth scope port.
- * @param user The username.
- * @param pw The password.
- * @return This object (for method chaining).
- */
- @Deprecated
- public RestClientBuilder basicAuth(String host, int port, String user, String pw) {
- AuthScope scope = new AuthScope(host, port);
- Credentials up = new UsernamePasswordCredentials(user, pw);
- CredentialsProvider p = new BasicCredentialsProvider();
- p.setCredentials(scope, up);
- defaultCredentialsProvider(p);
- return this;
- }
-
- //-----------------------------------------------------------------------------------------------------------------
- // HTTP headers
- //-----------------------------------------------------------------------------------------------------------------
-
- /**
- * Sets arbitrary request headers.
- *
- * @param headers The headers to set on requests.
- * @return This object (for method chaining).
- */
- public RestClientBuilder headers(Map<String,Object> headers) {
- if (headers != null)
- for (Map.Entry<String,Object> e : headers.entrySet())
- header(e.getKey(), e.getValue());
- return this;
- }
-
- /**
- * Sets the value for the <c>Accept</c> request header.
- *
- * <p>
- * This overrides the media type specified on the parser, but is overridden by calling
- * <code>header(<js>"Accept"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder accept(Object value) {
- return header("Accept", value);
- }
-
- /**
- * Sets the value for the <c>Accept-Charset</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Accept-Charset"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder acceptCharset(Object value) {
- return header("Accept-Charset", value);
- }
-
- /**
- * Sets the value for the <c>Accept-Encoding</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Accept-Encoding"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder acceptEncoding(Object value) {
- return header("Accept-Encoding", value);
- }
-
- /**
- * Sets the value for the <c>Accept-Language</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Accept-Language"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder acceptLanguage(Object value) {
- return header("Accept-Language", value);
- }
-
- /**
- * Sets the value for the <c>Authorization</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Authorization"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder authorization(Object value) {
- return header("Authorization", value);
- }
-
- /**
- * Sets the value for the <c>Cache-Control</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Cache-Control"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder cacheControl(Object value) {
- return header("Cache-Control", value);
- }
-
- /**
- * Sets the client version by setting the value for the <js>"X-Client-Version"</js> header.
- *
- * @param version The version string (e.g. <js>"1.2.3"</js>)
- * @return This object (for method chaining).
- */
- public RestClientBuilder clientVersion(String version) {
- return header("X-Client-Version", version);
- }
-
- /**
- * Sets the value for the <c>Connection</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Connection"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder connection(Object value) {
- return header("Connection", value);
- }
-
- /**
- * Sets the value for the <c>Content-Length</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Content-Length"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder contentLength(Object value) {
- return header("Content-Length", value);
- }
-
- /**
- * Sets the value for the <c>Content-Type</c> request header.
- *
- * <p>
- * This overrides the media type specified on the serializer, but is overridden by calling
- * <code>header(<js>"Content-Type"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder contentType(Object value) {
- return header("Content-Type", value);
- }
-
- /**
- * Sets the value for the <c>Date</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Date"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder date(Object value) {
- return header("Date", value);
- }
-
- /**
- * Sets the value for the <c>Expect</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Expect"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder expect(Object value) {
- return header("Expect", value);
- }
-
- /**
- * Sets the value for the <c>Forwarded</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Forwarded"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder forwarded(Object value) {
- return header("Forwarded", value);
- }
-
- /**
- * Sets the value for the <c>From</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"From"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder from(Object value) {
- return header("From", value);
- }
-
- /**
- * Sets the value for the <c>Host</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Host"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder host(Object value) {
- return header("Host", value);
- }
-
- /**
- * Sets the value for the <c>If-Match</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-Match"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder ifMatch(Object value) {
- return header("If-Match", value);
- }
-
- /**
- * Sets the value for the <c>If-Modified-Since</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-Modified-Since"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder ifModifiedSince(Object value) {
- return header("If-Modified-Since", value);
- }
-
- /**
- * Sets the value for the <c>If-None-Match</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-None-Match"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder ifNoneMatch(Object value) {
- return header("If-None-Match", value);
- }
-
- /**
- * Sets the value for the <c>If-Range</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-Range"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder ifRange(Object value) {
- return header("If-Range", value);
- }
-
- /**
- * Sets the value for the <c>If-Unmodified-Since</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"If-Unmodified-Since"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder ifUnmodifiedSince(Object value) {
- return header("If-Unmodified-Since", value);
- }
-
- /**
- * Sets the value for the <c>Max-Forwards</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Max-Forwards"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder maxForwards(Object value) {
- return header("If-Unmodified-Since", value);
- }
-
- /**
- * When called, <c>No-Trace: true</c> is added to requests.
- *
- * <p>
- * This gives the opportunity for the servlet to not log errors on invalid requests.
- * This is useful for testing purposes when you don't want your log file to show lots of errors that are simply the
- * results of testing.
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder noTrace() {
- return header("No-Trace", true);
- }
-
- /**
- * Sets the value for the <c>Origin</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Origin"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder origin(Object value) {
- return header("If-Unmodified-Since", value);
- }
-
- /**
- * Sets the value for the <c>Pragma</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Pragma"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder pragma(Object value) {
- return header("Pragma", value);
- }
-
- /**
- * Sets the value for the <c>Proxy-Authorization</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Proxy-Authorization"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder proxyAuthorization(Object value) {
- return header("Proxy-Authorization", value);
- }
-
- /**
- * Sets the value for the <c>Range</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Range"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder range(Object value) {
- return header("Range", value);
- }
-
- /**
- * Sets the value for the <c>Referer</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Referer"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder referer(Object value) {
- return header("Referer", value);
- }
-
- /**
- * Sets the value for the <c>TE</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"TE"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder te(Object value) {
- return header("TE", value);
- }
-
- /**
- * Sets the value for the <c>User-Agent</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"User-Agent"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder userAgent(Object value) {
- return header("User-Agent", value);
- }
-
- /**
- * Sets the value for the <c>Upgrade</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Upgrade"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder upgrade(Object value) {
- return header("Upgrade", value);
- }
-
- /**
- * Sets the value for the <c>Via</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Via"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder via(Object value) {
- return header("Via", value);
- }
-
- /**
- * Sets the value for the <c>Warning</c> request header.
- *
- * <p>
- * This is a shortcut for calling <code>header(<js>"Warning"</js>, value);</code>
- *
- * @param value The new header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder warning(Object value) {
- return header("Warning", value);
- }
-
- //-----------------------------------------------------------------------------------------------------------------
- // Properties
- //-----------------------------------------------------------------------------------------------------------------
-
- /**
- * Configuration property: REST call handler.
- *
- * <p>
- * Allows you to provide a custom handler for making HTTP calls.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_callHandler}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default value is <jk>null</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder callHandler(Class<? extends RestCallHandler> value) {
- return set(RESTCLIENT_callHandler, value);
- }
-
- /**
- * Configuration property: REST call handler.
- *
- * <p>
- * Allows you to provide a custom handler for making HTTP calls.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_callHandler}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default value is <jk>null</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder callHandler(RestCallHandler value) {
- return set(RESTCLIENT_callHandler, value);
- }
-
- /**
- * Configuration property: Executor service.
- *
- * <p>
- * Defines the executor service to use when calling future methods on the {@link RestCall} class.
- *
- * <p>
- * This executor service is used to create {@link Future} objects on the following methods:
- * <ul>
- * <li>{@link RestCall#runFuture()}
- * <li>{@link RestCall#getResponseFuture(Class)}
- * <li>{@link RestCall#getResponseFuture(Type,Type...)}
- * <li>{@link RestCall#getResponseAsString()}
- * </ul>
- *
- * <p>
- * The default executor service is a single-threaded {@link ThreadPoolExecutor} with a 30 second timeout
- * and a queue size of 10.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_executorService}
- * <li class='jf'>{@link RestClient#RESTCLIENT_executorServiceShutdownOnClose}
- * </ul>
- *
- * @param executorService The executor service.
- * @param shutdownOnClose Call {@link ExecutorService#shutdown()} when {@link RestClient#close()} is called.
- * @return This object (for method chaining).
- */
- public RestClientBuilder executorService(ExecutorService executorService, boolean shutdownOnClose) {
- set(RESTCLIENT_executorService, executorService);
- set(RESTCLIENT_executorServiceShutdownOnClose, shutdownOnClose);
- return this;
- }
-
- /**
- * Configuration property: Request headers.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_headers}
- * </ul>
- *
- * @param key The header name.
- * @param value The header value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder header(String key, Object value) {
- return putTo(RESTCLIENT_headers, key, value);
- }
-
- /**
- * Configuration property: Keep HttpClient open.
- *
- * <p>
- * Don't close this client when the {@link RestClient#close()} method is called.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_keepHttpClientOpen}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder keepHttpClientOpen(boolean value) {
- return set(RESTCLIENT_keepHttpClientOpen, value);
- }
-
- /**
- * Configuration property: Keep HttpClient open.
- *
- * <p>
- * Don't close this client when the {@link RestClient#close()} method is called.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_keepHttpClientOpen}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder keepHttpClientOpen() {
- return keepHttpClientOpen(true);
- }
-
- /**
- * Configuration property: Call interceptors.
- *
- * <p>
- * Adds an interceptor that gets called immediately after a connection is made.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_interceptors}
- * </ul>
- *
- * @param value The values to add to this setting.
- * @return This object (for method chaining).
- */
- public RestClientBuilder interceptors(RestCallInterceptor...value) {
- return prependTo(RESTCLIENT_interceptors, value);
- }
-
- /**
- * Configuration property: Marshall
- *
- * <p>
- * Shortcut for specifying the {@link RestClient#RESTCLIENT_serializer} and {@link RestClient#RESTCLIENT_parser}
- * using the serializer and parser defined in a marshall.
- *
- * @param value The values to add to this setting.
- * @return This object (for method chaining).
- */
- public RestClientBuilder marshall(Marshall value) {
- if (value == null)
- serializer((Serializer)null).parser((Parser)null);
- else
- serializer(value.getSerializer()).parser(value.getParser());
- return this;
- }
-
- /**
- * Configuration property: Parser.
- *
- * <p>
- * The parser to use for parsing POJOs in response bodies.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_parser}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default value is {@link JsonParser#DEFAULT}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder parser(Class<? extends Parser> value) {
- return set(RESTCLIENT_parser, value);
- }
-
- /**
- * Configuration property: Parser.
- *
- * <p>
- * Same as {@link #parser(Parser)} except takes in a parser instance.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_parser}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default value is {@link JsonParser#DEFAULT}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder parser(Parser value) {
- return set(RESTCLIENT_parser, value);
- }
-
- /**
- * Configuration property: Part parser.
- *
- * <p>
- * The parser to use for parsing POJOs from form data, query parameters, headers, and path variables.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_partParser}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default value is {@link OpenApiParser}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder partParser(Class<? extends HttpPartParser> value) {
- return set(RESTCLIENT_partParser, value);
- }
-
- /**
- * Configuration property: Part parser.
- *
- * <p>
- * Same as {@link #partParser(Class)} but takes in a parser instance.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_partParser}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default value is {@link OpenApiParser}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder partParser(HttpPartParser value) {
- return set(RESTCLIENT_partParser, value);
- }
-
- /**
- * Configuration property: Part serializer.
- *
- * <p>
- * The serializer to use for serializing POJOs in form data, query parameters, headers, and path variables.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_partSerializer}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default value is {@link OpenApiSerializer}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder partSerializer(Class<? extends HttpPartSerializer> value) {
- return set(RESTCLIENT_partSerializer, value);
- }
-
- /**
- * Configuration property: Part serializer.
- *
- * <p>
- * Same as {@link #partSerializer(Class)} but takes in a parser instance.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_partSerializer}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default value is {@link OpenApiSerializer}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder partSerializer(HttpPartSerializer value) {
- return set(RESTCLIENT_partSerializer, value);
- }
-
- /**
- * Make HTTP calls retryable if an error response (>=400) is received.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_retries}
- * <li class='jf'>{@link RestClient#RESTCLIENT_retryInterval}
- * <li class='jf'>{@link RestClient#RESTCLIENT_retryOn}
- * </ul>
- *
- * @param retries The number of retries to attempt.
- * @param interval The time in milliseconds between attempts.
- * @param retryOn
- * Optional object used for determining whether a retry should be attempted.
- * If <jk>null</jk>, uses {@link RetryOn#DEFAULT}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder retryable(int retries, int interval, RetryOn retryOn) {
- set(RESTCLIENT_retries, retries);
- set(RESTCLIENT_retryInterval, interval);
- set(RESTCLIENT_retryOn, retryOn);
- return this;
- }
-
- /**
- * Configuration property: Root URI.
- *
- * <p>
- * When set, relative URL strings passed in through the various rest call methods (e.g. {@link RestClient#doGet(Object)}
- * will be prefixed with the specified root.
- * <br>This root URL is ignored on those methods if you pass in a {@link URL}, {@link URI}, or an absolute URL string.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_rootUri}
- * </ul>
- *
- * @param value
- * The root URL to prefix to relative URL strings.
- * <br>Trailing slashes are trimmed.
- * <br>Usually a <c>String</c> but you can also pass in <c>URI</c> and <c>URL</c> objects as well.
- * @return This object (for method chaining).
- */
- public RestClientBuilder rootUrl(Object value) {
- return set(RESTCLIENT_rootUri, value);
- }
-
- /**
- * Configuration property: Request query parameters.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_query}
- * </ul>
- *
- * @param key The query parameter name.
- * @param value The query parameter value value.
- * @return This object (for method chaining).
- */
- public RestClientBuilder query(String key, Object value) {
- return putTo(RESTCLIENT_query, key, value);
- }
-
- /**
- * Configuration property: Serializer.
- *
- * <p>
- * The serializer to use for serializing POJOs in request bodies.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_serializer}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default is {@link JsonSerializer}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder serializer(Class<? extends Serializer> value) {
- return set(RESTCLIENT_serializer, value);
- }
-
- /**
- * Configuration property: Serializer.
- *
- * <p>
- * Same as {@link #serializer(Class)} but takes in a serializer instance.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link RestClient#RESTCLIENT_serializer}
- * </ul>
- *
- * @param value
- * The new value for this setting.
- * <br>The default is {@link JsonSerializer}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder serializer(Serializer value) {
- return set(RESTCLIENT_serializer, value);
- }
-
- /**
- * Configuration property: Add <js>"_type"</js> properties when needed.
- *
- * <p>
- * If <jk>true</jk>, then <js>"_type"</js> properties will be added to beans if their type cannot be inferred
- * through reflection.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_addBeanTypes}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder addBeanTypes(boolean value) {
- return set(SERIALIZER_addBeanTypes, value);
- }
-
- /**
- * Configuration property: Add <js>"_type"</js> properties when needed.
- *
- * <p>
- * Shortcut for calling <code>addBeanTypes(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_addBeanTypes}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder addBeanTypes() {
- return set(SERIALIZER_addBeanTypes, true);
- }
-
- /**
- * Configuration property: Add type attribute to root nodes.
- *
- * <p>
- * When disabled, it is assumed that the parser knows the exact Java POJO type being parsed, and therefore top-level
- * type information that might normally be included to determine the data type will not be serialized.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_addRootType}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder addRootType(boolean value) {
- return set(SERIALIZER_addRootType, value);
- }
-
- /**
- * Configuration property: Add type attribute to root nodes.
- *
- * <p>
- * Shortcut for calling <code>addRootType(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_addRootType}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder addRootType() {
- return set(SERIALIZER_addRootType, true);
- }
-
- /**
- * Configuration property: Automatically detect POJO recursions.
- *
- * <p>
- * Specifies that recursions should be checked for during serialization.
- *
- * <ul class='notes'>
- * <li>
- * Checking for recursion can cause a small performance penalty.
- * </ul>
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link BeanTraverseContext#BEANTRAVERSE_detectRecursions}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder detectRecursions(boolean value) {
- return set(BEANTRAVERSE_detectRecursions, value);
- }
-
- /**
- * Configuration property: Automatically detect POJO recursions.
- *
- * <p>
- * Shortcut for calling <code>detectRecursions(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link BeanTraverseContext#BEANTRAVERSE_detectRecursions}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder detectRecursions() {
- return set(BEANTRAVERSE_detectRecursions, true);
- }
-
- /**
- * Configuration property: Ignore recursion errors.
- *
- * <p>
- * If <jk>true</jk>, when we encounter the same object when serializing a tree, we set the value to <jk>null</jk>.
- * Otherwise, an exception is thrown.
- *
- * <ul class='notes'>
- * <li>
- * Checking for recursion can cause a small performance penalty.
- * </ul>
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link BeanTraverseContext#BEANTRAVERSE_ignoreRecursions}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder ignoreRecursions(boolean value) {
- return set(BEANTRAVERSE_ignoreRecursions, value);
- }
-
- /**
- * Configuration property: Ignore recursion errors.
- *
- * <p>
- * Shortcut for calling <code>ignoreRecursions(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link BeanTraverseContext#BEANTRAVERSE_ignoreRecursions}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder ignoreRecursions() {
- return set(BEANTRAVERSE_ignoreRecursions, true);
- }
-
- /**
- * Configuration property: Initial depth.
- *
- * <p>
- * The initial indentation level at the root.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link BeanTraverseContext#BEANTRAVERSE_initialDepth}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <c>0</c>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder initialDepth(int value) {
- return set(BEANTRAVERSE_initialDepth, value);
- }
-
- /**
- * Configuration property: Serializer listener.
- *
- * <p>
- * Class used to listen for errors and warnings that occur during serialization.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_listener}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * @return This object (for method chaining).
- */
- public RestClientBuilder listenerS(Class<? extends SerializerListener> value) {
- return set(SERIALIZER_listener, value);
- }
-
- /**
- * Configuration property: Max serialization depth.
- *
- * <p>
- * Abort serialization if specified depth is reached in the POJO tree.
- * <br>If this depth is exceeded, an exception is thrown.
- * <br>This prevents stack overflows from occurring when trying to serialize models with recursive references.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link BeanTraverseContext#BEANTRAVERSE_maxDepth}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <c>100</c>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder maxDepth(int value) {
- return set(BEANTRAVERSE_maxDepth, value);
- }
-
- /**
- * Configuration property: Sort arrays and collections alphabetically.
- *
- * <p>
- * Copies and sorts the contents of arrays and collections before serializing them.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_sortCollections}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder sortCollections(boolean value) {
- return set(SERIALIZER_sortCollections, value);
- }
-
- /**
- * Configuration property: Sort arrays and collections alphabetically.
- *
- * <p>
- * Shortcut for calling <code>sortCollections(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_sortCollections}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder sortCollections() {
- return set(SERIALIZER_sortCollections, true);
- }
-
- /**
- * Sets the {@link Serializer#SERIALIZER_sortMaps} property on all serializers in this group.
- *
- * <p>
- * Copies and sorts the contents of maps before serializing them.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_sortMaps}
- * </ul>
- *
- * @param value The new value for this property.
- * @return This object (for method chaining).
- */
- public RestClientBuilder sortMaps(boolean value) {
- return set(SERIALIZER_sortMaps, value);
- }
-
- /**
- * Configuration property: Sort maps alphabetically.
- *
- * <p>
- * Shortcut for calling <code>sortMaps(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_sortMaps}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder sortMaps() {
- return set(SERIALIZER_sortMaps, true);
- }
-
- /**
- * Configuration property: Trim empty lists and arrays.
- *
- * <p>
- * If <jk>true</jk>, empty list values will not be serialized to the output.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_trimEmptyCollections}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimEmptyCollections(boolean value) {
- return set(SERIALIZER_trimEmptyCollections, value);
- }
-
- /**
- * Configuration property: Trim empty lists and arrays.
- *
- * <p>
- * Shortcut for calling <code>trimEmptyCollections(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_trimEmptyCollections}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimEmptyCollections() {
- return set(SERIALIZER_trimEmptyCollections, true);
- }
-
- /**
- * Configuration property: Trim empty maps.
- *
- * <p>
- * If <jk>true</jk>, empty map values will not be serialized to the output.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_trimEmptyMaps}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimEmptyMaps(boolean value) {
- return set(SERIALIZER_trimEmptyMaps, value);
- }
-
- /**
- * Configuration property: Trim empty maps.
- *
- * <p>
- * Shortcut for calling <code>trimEmptyMaps(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_trimEmptyMaps}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimEmptyMaps() {
- return set(SERIALIZER_trimEmptyMaps, true);
- }
-
- /**
- * Configuration property: Trim null bean property values.
- *
- * <p>
- * If <jk>true</jk>, null bean values will not be serialized to the output.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_trimNullProperties}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>true</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimNullProperties(boolean value) {
- return set(SERIALIZER_trimNullProperties, value);
- }
-
- /**
- * Configuration property: Trim strings.
- *
- * <p>
- * If <jk>true</jk>, string values will be trimmed of whitespace using {@link String#trim()} before being serialized.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_trimStrings}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimStringsS(boolean value) {
- return set(SERIALIZER_trimStrings, value);
- }
-
- /**
- * Configuration property: Trim strings.
- *
- * <p>
- * Shortcut for calling <code>trimStrings(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_trimStrings}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimStringsS() {
- return set(SERIALIZER_trimStrings, true);
- }
-
- /**
- * Configuration property: URI context bean.
- *
- * <p>
- * Bean used for resolution of URIs to absolute or root-relative form.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_uriContext}
- * </ul>
- *
- * @param value The new value for this property.
- * @return This object (for method chaining).
- */
- public RestClientBuilder uriContext(UriContext value) {
- return set(SERIALIZER_uriContext, value);
- }
-
- /**
- * Configuration property: URI relativity.
- *
- * <p>
- * Defines what relative URIs are relative to when serializing URI/URL objects.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_uriRelativity}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is {@link UriRelativity#RESOURCE}
- * @return This object (for method chaining).
- */
- public RestClientBuilder uriRelativity(UriRelativity value) {
- return set(SERIALIZER_uriRelativity, value);
- }
-
- /**
- * Configuration property: URI resolution.
- *
- * <p>
- * Defines the resolution level for URIs when serializing URI/URL objects.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Serializer#SERIALIZER_uriResolution}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is {@link UriResolution#NONE}
- * @return This object (for method chaining).
- */
- public RestClientBuilder uriResolution(UriResolution value) {
- return set(SERIALIZER_uriResolution, value);
- }
-
- /**
- * Configuration property: Maximum indentation.
- *
- * <p>
- * Specifies the maximum indentation level in the serialized document.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link WriterSerializer#WSERIALIZER_maxIndent}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <c>100</c>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder maxIndent(int value) {
- return set(WSERIALIZER_maxIndent, value);
- }
-
- /**
- * Configuration property: Quote character.
- *
- * <p>
- * This is the character used for quoting attributes and values.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link WriterSerializer#WSERIALIZER_quoteChar}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <js>'"'</js>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder quoteChar(char value) {
- return set(WSERIALIZER_quoteChar, value);
- }
-
- /**
- * Configuration property: Quote character.
- *
- * <p>
- * Shortcut for calling <code>quoteChar(<js>'\''</js>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link WriterSerializer#WSERIALIZER_quoteChar}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder sq() {
- return set(WSERIALIZER_quoteChar, '\'');
- }
-
- /**
- * Configuration property: Use whitespace.
- *
- * <p>
- * If <jk>true</jk>, newlines and indentation and spaces are added to the output to improve readability.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link WriterSerializer#WSERIALIZER_useWhitespace}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder useWhitespace(boolean value) {
- return set(WSERIALIZER_useWhitespace, value);
- }
-
- /**
- * Configuration property: Use whitespace.
- *
- * <p>
- * Shortcut for calling <code>useWhitespace(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link WriterSerializer#WSERIALIZER_useWhitespace}
- * </ul>
- * @return This object (for method chaining).
- */
- public RestClientBuilder useWhitespace() {
- return set(WSERIALIZER_useWhitespace, true);
- }
-
- /**
- * Configuration property: Use whitespace.
- *
- * <p>
- * Shortcut for calling <code>useWhitespace(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link WriterSerializer#WSERIALIZER_useWhitespace}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder ws() {
- return set(WSERIALIZER_useWhitespace, true);
- }
-
- /**
- * Configuration property: Binary string format.
- *
- * <p>
- * When using the {@link Serializer#serializeToString(Object)} method on stream-based serializers, this defines the format to use
- * when converting the resulting byte array to a string.
- *
- * <ul class='javatree'>
- * <li class='jf'>{@link OutputStreamSerializer#OSSERIALIZER_binaryFormat}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default is {@link BinaryFormat#HEX}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder binaryOutputFormat(BinaryFormat value) {
- return set(OSSERIALIZER_binaryFormat, value);
- }
-
- /**
- * Configuration property: Auto-close streams.
- *
- * If <jk>true</jk>, <l>InputStreams</l> and <l>Readers</l> passed into parsers will be closed
- * after parsing is complete.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_autoCloseStreams}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder autoCloseStreams(boolean value) {
- return set(PARSER_autoCloseStreams, value);
- }
-
- /**
- * Configuration property: Auto-close streams.
- *
- * <p>
- * Shortcut for calling <code>autoCloseStreams(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_autoCloseStreams}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder autoCloseStreams() {
- return set(PARSER_autoCloseStreams, true);
- }
-
- /**
- * Configuration property: Debug output lines.
- *
- * When parse errors occur, this specifies the number of lines of input before and after the
- * error location to be printed as part of the exception message.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_debugOutputLines}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is <c>5</c>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder debugOutputLines(int value) {
- set(PARSER_debugOutputLines, value);
- return this;
- }
-
- /**
- * Configuration property: Parser listener.
- *
- * <p>
- * Class used to listen for errors and warnings that occur during parsing.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_listener}
- * </ul>
- *
- * @param value The new value for this property.
- * @return This object (for method chaining).
- */
- public RestClientBuilder listenerP(Class<? extends ParserListener> value) {
- return set(PARSER_listener, value);
- }
-
- /**
- * Configuration property: Strict mode.
- *
- * <p>
- * If <jk>true</jk>, strict mode for the parser is enabled.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_strict}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder strict(boolean value) {
- return set(PARSER_strict, value);
- }
-
- /**
- * Configuration property: Strict mode.
- *
- * <p>
- * Shortcut for calling <code>strict(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_strict}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder strict() {
- return set(PARSER_strict, true);
- }
-
- /**
- * Configuration property: Trim parsed strings.
- *
- * <p>
- * If <jk>true</jk>, string values will be trimmed of whitespace using {@link String#trim()} before being added to
- * the POJO.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_trimStrings}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimStringsP(boolean value) {
- return set(PARSER_trimStrings, value);
- }
-
- /**
- * Configuration property: Trim parsed strings.
- *
- * <p>
- * Shortcut for calling <code>trimStrings(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_trimStrings}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder trimStringsP() {
- return set(PARSER_trimStrings, true);
- }
-
- /**
- * Configuration property: Unbuffered.
- *
- * If <jk>true</jk>, don't use internal buffering during parsing.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_unbuffered}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is <jk>false</jk>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder unbuffered(boolean value) {
- return set(PARSER_unbuffered, value);
- }
-
- /**
- * Configuration property: Unbuffered.
- *
- * <p>
- * Shortcut for calling <code>unbuffered(<jk>true</jk>)</code>.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link Parser#PARSER_unbuffered}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder unbuffered() {
- return set(PARSER_unbuffered, true);
- }
-
- /**
- * Configuration property: File charset.
- *
- * <p>
- * The character set to use for reading <c>Files</c> from the file system.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link ReaderParser#RPARSER_fileCharset}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is <js>"DEFAULT"</js> which causes the system default to be used.
- * @return This object (for method chaining).
- */
- public RestClientBuilder fileCharset(String value) {
- return set(RPARSER_fileCharset, value);
- }
-
- /**
- * Configuration property: Input stream charset.
- *
- * <p>
- * The character set to use for converting <c>InputStreams</c> and byte arrays to readers.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link ReaderParser#RPARSER_streamCharset}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is <js>"UTF-8"</js>.
- * @return This object (for method chaining).
- */
- public RestClientBuilder inputStreamCharset(String value) {
- return set(RPARSER_streamCharset, value);
- }
-
- /**
- * Configuration property: Binary input format.
- *
- * <p>
- * When using the {@link Parser#parse(Object,Class)} method on stream-based parsers and the input is a string, this defines the format to use
- * when converting the string into a byte array.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link InputStreamParser#ISPARSER_binaryFormat}
- * </ul>
- *
- * @param value
- * The new value for this property.
- * <br>The default value is {@link BinaryFormat#HEX}.
- * @return This object (for method chaining).
- */
- public RestClientBuilder binaryInputFormat(BinaryFormat value) {
- return set(ISPARSER_binaryFormat, value);
- }
-
- /**
- * Configuration property: Parameter format.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link UonSerializer#UON_paramFormat}
- * </ul>
- *
- * @param value The new value for this property.
- * @return This object (for method chaining).
- */
- public RestClientBuilder paramFormat(String value) {
- return set(UON_paramFormat, value);
- }
-
- /**
- * Configuration property: Parameter format.
- *
- * <ul class='seealso'>
- * <li class='jf'>{@link UonSerializer#UON_paramFormat}
- * </ul>
- *
- * @return This object (for method chaining).
- */
- public RestClientBuilder paramFormatPlain() {
- return set(UON_paramFormat, "PLAINTEXT");
- }
-
- // <FluentSetters>
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanClassVisibility(Visibility value) {
- super.beanClassVisibility(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanConstructorVisibility(Visibility value) {
- super.beanConstructorVisibility(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- @Deprecated
- public RestClientBuilder beanDictionary(Class<?>...values) {
- super.beanDictionary(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- @Deprecated
- public RestClientBuilder beanDictionary(Object...values) {
- super.beanDictionary(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- @Deprecated
- public RestClientBuilder beanDictionaryReplace(Class<?>...values) {
- super.beanDictionaryReplace(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- @Deprecated
- public RestClientBuilder beanDictionaryReplace(Object...values) {
- super.beanDictionaryReplace(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- @Deprecated
- public RestClientBuilder beanDictionaryRemove(Class<?>...values) {
- super.beanDictionaryRemove(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- @Deprecated
- public RestClientBuilder beanDictionaryRemove(Object...values) {
- super.beanDictionaryRemove(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanFieldVisibility(Visibility value) {
- super.beanFieldVisibility(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanFilters(Object...values) {
- super.beanFilters(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanFiltersReplace(Object...values) {
- super.beanFiltersReplace(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanFiltersRemove(Object...values) {
- super.beanFiltersRemove(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanMapPutReturnsOldValue(boolean value) {
- super.beanMapPutReturnsOldValue(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanMapPutReturnsOldValue() {
- super.beanMapPutReturnsOldValue();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beanMethodVisibility(Visibility value) {
- super.beanMethodVisibility(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beansRequireDefaultConstructor(boolean value) {
- super.beansRequireDefaultConstructor(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beansRequireDefaultConstructor() {
- super.beansRequireDefaultConstructor();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beansRequireSerializable(boolean value) {
- super.beansRequireSerializable(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beansRequireSerializable() {
- super.beansRequireSerializable();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beansRequireSettersForGetters(boolean value) {
- super.beansRequireSettersForGetters(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beansRequireSettersForGetters() {
- super.beansRequireSettersForGetters();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder beansRequireSomeProperties(boolean value) {
- super.beansRequireSomeProperties(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpi(Class<?> beanClass, String value) {
- super.bpi(beanClass, value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpi(Map<String,Object> values) {
- super.bpi(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpi(String beanClassName, String value) {
- super.bpi(beanClassName, value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpx(Class<?> beanClass, String properties) {
- super.bpx(beanClass, properties);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpx(Map<String,Object> values) {
- super.bpx(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpx(String beanClassName, String value) {
- super.bpx(beanClassName, value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpro(Class<?> beanClass, String value) {
- super.bpro(beanClass, value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpro(Map<String,Object> values) {
- super.bpro(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpro(String beanClassName, String value) {
- super.bpro(beanClassName, value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpwo(Class<?> beanClass, String properties) {
- super.bpwo(beanClass, properties);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpwo(Map<String,Object> values) {
- super.bpwo(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder bpwo(String beanClassName, String value) {
- super.bpwo(beanClassName, value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder debug() {
- super.debug();
- interceptors(RestCallLogger.DEFAULT);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder debug(boolean value) {
- super.debug(value);
- if (value)
- interceptors(RestCallLogger.DEFAULT);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder dictionary(Object...values) {
- super.dictionary(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public <T> RestClientBuilder example(Class<T> c, T o) {
- super.example(c, o);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public <T> RestClientBuilder exampleJson(Class<T> c, String value) {
- super.exampleJson(c, value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder ignoreInvocationExceptionsOnGetters(boolean value) {
- super.ignoreInvocationExceptionsOnGetters(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder ignoreInvocationExceptionsOnGetters() {
- super.ignoreInvocationExceptionsOnGetters();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder ignoreInvocationExceptionsOnSetters(boolean value) {
- super.ignoreInvocationExceptionsOnSetters(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder ignoreInvocationExceptionsOnSetters() {
- super.ignoreInvocationExceptionsOnSetters();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder ignorePropertiesWithoutSetters(boolean value) {
- super.ignorePropertiesWithoutSetters(value);
- return this;
- }
-
- @Override
- public RestClientBuilder ignoreUnknownBeanProperties(boolean value) {
- super.ignoreUnknownBeanProperties(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder ignoreUnknownBeanProperties() {
- super.ignoreUnknownBeanProperties();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder ignoreUnknownNullBeanProperties(boolean value) {
- super.ignoreUnknownNullBeanProperties(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder implClass(Class<?> interfaceClass, Class<?> implClass) {
- super.implClass(interfaceClass, implClass);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder implClasses(Map<Class<?>,Class<?>> values) {
- super.implClasses(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder locale(Locale value) {
- super.locale(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder mediaType(MediaType value) {
- super.mediaType(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder notBeanClasses(Object...values) {
- super.notBeanClasses(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder notBeanPackages(Object...values) {
- super.notBeanPackages(values);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder sortProperties(boolean value) {
- super.sortProperties(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder sortProperties() {
- super.sortProperties();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder timeZone(TimeZone value) {
- super.timeZone(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder useEnumNames(boolean value) {
- super.useEnumNames(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder useEnumNames() {
- super.useEnumNames();
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder useInterfaceProxies(boolean value) {
- super.useInterfaceProxies(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder useJavaBeanIntrospector(boolean value) {
- super.useJavaBeanIntrospector(value);
- return this;
- }
-
- @Override /* BeanContextBuilder */
- public RestClientBuilder useJavaBeanIntrospector() {
- super.useJavaBeanIntrospector();
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder annotations(Annotation...values) {
- super.annotations(values);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder set(String name, Object value) {
- super.set(name, value);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder set(Map<String,Object> properties) {
- super.set(properties);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder add(Map<String,Object> properties) {
- super.add(properties);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder addTo(String name, Object value) {
- super.addTo(name, value);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder prependTo(String name, Object value) {
- super.prependTo(name, value);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder putTo(String name, String key, Object value) {
- super.putTo(name, key, value);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder removeFrom(String name, Object value) {
- super.removeFrom(name, value);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder apply(PropertyStore copyFrom) {
- super.apply(copyFrom);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder applyAnnotations(AnnotationList al, VarResolverSession vrs) {
- super.applyAnnotations(al, vrs);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder applyAnnotations(Class<?>...fromClasses) {
- super.applyAnnotations(fromClasses);
- return this;
- }
-
- @Override /* ContextBuilder */
- public RestClientBuilder applyAnnotations(Method...fromMethods) {
- super.applyAnnotations(fromMethods);
- return this;
- }
-
- // </FluentSetters>
-
- //------------------------------------------------------------------------------------------------
- // Passthrough methods for HttpClientBuilder.
- //------------------------------------------------------------------------------------------------
-
- /**
- * @return This object (for method chaining).
- * @see HttpClientBuilder#disableRedirectHandling()
- */
- public RestClientBuilder disableRedirectHandling() {
- httpClientBuilder.disableRedirectHandling();
- return this;
- }
-
- /**
- * @param redirectStrategy New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setRedirectStrategy(RedirectStrategy)
- */
- public RestClientBuilder redirectStrategy(RedirectStrategy redirectStrategy) {
- httpClientBuilder.setRedirectStrategy(redirectStrategy);
- return this;
- }
-
- /**
- * @param cookieSpecRegistry New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setDefaultCookieSpecRegistry(Lookup)
- */
- public RestClientBuilder defaultCookieSpecRegistry(Lookup<CookieSpecProvider> cookieSpecRegistry) {
- httpClientBuilder.setDefaultCookieSpecRegistry(cookieSpecRegistry);
- return this;
- }
-
- /**
- * @param requestExec New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setRequestExecutor(HttpRequestExecutor)
- */
- public RestClientBuilder requestExecutor(HttpRequestExecutor requestExec) {
- httpClientBuilder.setRequestExecutor(requestExec);
- return this;
- }
-
- /**
- * @param hostnameVerifier New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setSSLHostnameVerifier(HostnameVerifier)
- */
- public RestClientBuilder sslHostnameVerifier(HostnameVerifier hostnameVerifier) {
- httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
- return this;
- }
-
- /**
- * @param publicSuffixMatcher New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setPublicSuffixMatcher(PublicSuffixMatcher)
- */
- public RestClientBuilder publicSuffixMatcher(PublicSuffixMatcher publicSuffixMatcher) {
- httpClientBuilder.setPublicSuffixMatcher(publicSuffixMatcher);
- return this;
- }
-
- /**
- * @param sslContext New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setSSLContext(SSLContext)
- */
- public RestClientBuilder sslContext(SSLContext sslContext) {
- httpClientBuilder.setSSLContext(sslContext);
- return this;
- }
-
- /**
- * @param sslSocketFactory New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setSSLSocketFactory(LayeredConnectionSocketFactory)
- */
- public RestClientBuilder sslSocketFactory(LayeredConnectionSocketFactory sslSocketFactory) {
- httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
- return this;
- }
-
- /**
- * @param maxConnTotal New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setMaxConnTotal(int)
- */
- public RestClientBuilder maxConnTotal(int maxConnTotal) {
- httpClientBuilder.setMaxConnTotal(maxConnTotal);
- return this;
- }
-
- /**
- * @param maxConnPerRoute New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setMaxConnPerRoute(int)
- */
- public RestClientBuilder maxConnPerRoute(int maxConnPerRoute) {
- httpClientBuilder.setMaxConnPerRoute(maxConnPerRoute);
- return this;
- }
-
- /**
- * @param config New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setDefaultSocketConfig(SocketConfig)
- */
- public RestClientBuilder defaultSocketConfig(SocketConfig config) {
- httpClientBuilder.setDefaultSocketConfig(config);
- return this;
- }
-
- /**
- * @param config New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setDefaultConnectionConfig(ConnectionConfig)
- */
- public RestClientBuilder defaultConnectionConfig(ConnectionConfig config) {
- httpClientBuilder.setDefaultConnectionConfig(config);
- return this;
- }
-
- /**
- * @param connTimeToLive New property value.
- * @param connTimeToLiveTimeUnit New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setConnectionTimeToLive(long,TimeUnit)
- */
- public RestClientBuilder connectionTimeToLive(long connTimeToLive, TimeUnit connTimeToLiveTimeUnit) {
- httpClientBuilder.setConnectionTimeToLive(connTimeToLive, connTimeToLiveTimeUnit);
- return this;
- }
-
- /**
- * @param connManager New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setConnectionManager(HttpClientConnectionManager)
- */
- public RestClientBuilder connectionManager(HttpClientConnectionManager connManager) {
- this.httpClientConnectionManager = connManager;
- httpClientBuilder.setConnectionManager(connManager);
- return this;
- }
-
- /**
- * @param shared New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setConnectionManagerShared(boolean)
- */
- public RestClientBuilder connectionManagerShared(boolean shared) {
- httpClientBuilder.setConnectionManagerShared(shared);
- return this;
- }
-
- /**
- * @param reuseStrategy New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setConnectionReuseStrategy(ConnectionReuseStrategy)
- */
- public RestClientBuilder connectionReuseStrategy(ConnectionReuseStrategy reuseStrategy) {
- httpClientBuilder.setConnectionReuseStrategy(reuseStrategy);
- return this;
- }
-
- /**
- * @param keepAliveStrategy New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setKeepAliveStrategy(ConnectionKeepAliveStrategy)
- */
- public RestClientBuilder keepAliveStrategy(ConnectionKeepAliveStrategy keepAliveStrategy) {
- httpClientBuilder.setKeepAliveStrategy(keepAliveStrategy);
- return this;
- }
-
- /**
- * @param targetAuthStrategy New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setTargetAuthenticationStrategy(AuthenticationStrategy)
- */
- public RestClientBuilder targetAuthenticationStrategy(AuthenticationStrategy targetAuthStrategy) {
- httpClientBuilder.setTargetAuthenticationStrategy(targetAuthStrategy);
- return this;
- }
-
- /**
- * @param proxyAuthStrategy New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setProxyAuthenticationStrategy(AuthenticationStrategy)
- */
- public RestClientBuilder proxyAuthenticationStrategy(AuthenticationStrategy proxyAuthStrategy) {
- httpClientBuilder.setProxyAuthenticationStrategy(proxyAuthStrategy);
- return this;
- }
-
- /**
- * @param userTokenHandler New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setUserTokenHandler(UserTokenHandler)
- */
- public RestClientBuilder userTokenHandler(UserTokenHandler userTokenHandler) {
- httpClientBuilder.setUserTokenHandler(userTokenHandler);
- return this;
- }
-
- /**
- * @return This object (for method chaining).
- * @see HttpClientBuilder#disableConnectionState()
- */
- public RestClientBuilder disableConnectionState() {
- httpClientBuilder.disableConnectionState();
- return this;
- }
-
- /**
- * @param schemePortResolver New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setSchemePortResolver(SchemePortResolver)
- */
- public RestClientBuilder schemePortResolver(SchemePortResolver schemePortResolver) {
- httpClientBuilder.setSchemePortResolver(schemePortResolver);
- return this;
- }
-
- /**
- * @param userAgent New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setUserAgent(String)
- */
- public RestClientBuilder userAgent(String userAgent) {
- httpClientBuilder.setUserAgent(userAgent);
- return this;
- }
-
- /**
- * @param defaultHeaders New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setDefaultHeaders(Collection)
- */
- public RestClientBuilder defaultHeaders(Collection<? extends Header> defaultHeaders) {
- httpClientBuilder.setDefaultHeaders(defaultHeaders);
- return this;
- }
-
- /**
- * @param itcp New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#addInterceptorFirst(HttpResponseInterceptor)
- */
- public RestClientBuilder addInterceptorFirst(HttpResponseInterceptor itcp) {
- httpClientBuilder.addInterceptorFirst(itcp);
- return this;
- }
-
- /**
- * @param itcp New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#addInterceptorLast(HttpResponseInterceptor)
- */
- public RestClientBuilder addInterceptorLast(HttpResponseInterceptor itcp) {
- httpClientBuilder.addInterceptorLast(itcp);
- return this;
- }
-
- /**
- * @param itcp New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#addInterceptorFirst(HttpRequestInterceptor)
- */
- public RestClientBuilder addInterceptorFirst(HttpRequestInterceptor itcp) {
- httpClientBuilder.addInterceptorFirst(itcp);
- return this;
- }
-
- /**
- * @param itcp New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#addInterceptorLast(HttpRequestInterceptor)
- */
- public RestClientBuilder addInterceptorLast(HttpRequestInterceptor itcp) {
- httpClientBuilder.addInterceptorLast(itcp);
- return this;
- }
-
- /**
- * @return This object (for method chaining).
- * @see HttpClientBuilder#disableCookieManagement()
- */
- public RestClientBuilder disableCookieManagement() {
- httpClientBuilder.disableCookieManagement();
- return this;
- }
-
- /**
- * @return This object (for method chaining).
- * @see HttpClientBuilder#disableContentCompression()
- */
- public RestClientBuilder disableContentCompression() {
- httpClientBuilder.disableContentCompression();
- return this;
- }
-
- /**
- * @return This object (for method chaining).
- * @see HttpClientBuilder#disableAuthCaching()
- */
- public RestClientBuilder disableAuthCaching() {
- httpClientBuilder.disableAuthCaching();
- return this;
- }
-
- /**
- * @param httpprocessor New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setHttpProcessor(HttpProcessor)
- */
- public RestClientBuilder httpProcessor(HttpProcessor httpprocessor) {
- httpClientBuilder.setHttpProcessor(httpprocessor);
- return this;
- }
-
- /**
- * @param retryHandler New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setRetryHandler(HttpRequestRetryHandler)
- */
- public RestClientBuilder retryHandler(HttpRequestRetryHandler retryHandler) {
- httpClientBuilder.setRetryHandler(retryHandler);
- return this;
- }
-
- /**
- * @return This object (for method chaining).
- * @see HttpClientBuilder#disableAutomaticRetries()
- */
- public RestClientBuilder disableAutomaticRetries() {
- httpClientBuilder.disableAutomaticRetries();
- return this;
- }
-
- /**
- * @param proxy New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setProxy(HttpHost)
- */
- public RestClientBuilder proxy(HttpHost proxy) {
- httpClientBuilder.setProxy(proxy);
- return this;
- }
-
- /**
- * @param routePlanner New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setRoutePlanner(HttpRoutePlanner)
- */
- public RestClientBuilder routePlanner(HttpRoutePlanner routePlanner) {
- httpClientBuilder.setRoutePlanner(routePlanner);
- return this;
- }
-
- /**
- * @param connectionBackoffStrategy New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setConnectionBackoffStrategy(ConnectionBackoffStrategy)
- */
- public RestClientBuilder connectionBackoffStrategy(ConnectionBackoffStrategy connectionBackoffStrategy) {
- httpClientBuilder.setConnectionBackoffStrategy(connectionBackoffStrategy);
- return this;
- }
-
- /**
- * @param backoffManager New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setBackoffManager(BackoffManager)
- */
- public RestClientBuilder backoffManager(BackoffManager backoffManager) {
- httpClientBuilder.setBackoffManager(backoffManager);
- return this;
- }
-
- /**
- * @param serviceUnavailStrategy New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setServiceUnavailableRetryStrategy(ServiceUnavailableRetryStrategy)
- */
- public RestClientBuilder serviceUnavailableRetryStrategy(ServiceUnavailableRetryStrategy serviceUnavailStrategy) {
- httpClientBuilder.setServiceUnavailableRetryStrategy(serviceUnavailStrategy);
- return this;
- }
-
- /**
- * @param cookieStore New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setDefaultCookieStore(CookieStore)
- */
- public RestClientBuilder defaultCookieStore(CookieStore cookieStore) {
- httpClientBuilder.setDefaultCookieStore(cookieStore);
- return this;
- }
-
- /**
- * @param credentialsProvider New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setDefaultCredentialsProvider(CredentialsProvider)
- */
- public RestClientBuilder defaultCredentialsProvider(CredentialsProvider credentialsProvider) {
- httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
- return this;
- }
-
- /**
- * @param authSchemeRegistry New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setDefaultAuthSchemeRegistry(Lookup)
- */
- public RestClientBuilder defaultAuthSchemeRegistry(Lookup<AuthSchemeProvider> authSchemeRegistry) {
- httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
- return this;
- }
-
- /**
- * @param contentDecoderMap New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setContentDecoderRegistry(Map)
- */
- public RestClientBuilder contentDecoderRegistry(Map<String,InputStreamFactory> contentDecoderMap) {
- httpClientBuilder.setContentDecoderRegistry(contentDecoderMap);
- return this;
- }
-
- /**
- * @param config New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#setDefaultRequestConfig(RequestConfig)
- */
- public RestClientBuilder defaultRequestConfig(RequestConfig config) {
- httpClientBuilder.setDefaultRequestConfig(config);
- return this;
- }
-
- /**
- * @return This object (for method chaining).
- * @see HttpClientBuilder#useSystemProperties()
- */
- public RestClientBuilder useSystemProperties() {
- httpClientBuilder.useSystemProperties();
- return this;
- }
-
- /**
- * @return This object (for method chaining).
- * @see HttpClientBuilder#evictExpiredConnections()
- */
- public RestClientBuilder evictExpiredConnections() {
- httpClientBuilder.evictExpiredConnections();
- return this;
- }
-
- /**
- * @param maxIdleTime New property value.
- * @param maxIdleTimeUnit New property value.
- * @return This object (for method chaining).
- * @see HttpClientBuilder#evictIdleConnections(long,TimeUnit)
- */
- public RestClientBuilder evictIdleConnections(long maxIdleTime, TimeUnit maxIdleTimeUnit) {
- httpClientBuilder.evictIdleConnections(maxIdleTime, maxIdleTimeUnit);
- return this;
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestRequestEntity.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestRequestEntity.java
deleted file mode 100644
index 6b5158a..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RestRequestEntity.java
+++ /dev/null
@@ -1,97 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import static org.apache.juneau.internal.IOUtils.*;
-
-import java.io.*;
-
-import org.apache.http.entity.*;
-import org.apache.http.message.*;
-import org.apache.juneau.httppart.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.utils.*;
-
-/**
- * HttpEntity for serializing POJOs as the body of HTTP requests.
- *
- * @deprecated Use {@link org.apache.juneau.http.SerializedHttpEntity}.
- */
-@Deprecated
-public final class RestRequestEntity extends BasicHttpEntity {
- final Object output;
- final Serializer serializer;
- final HttpPartSchema schema;
- byte[] outputBytes;
-
- /**
- * Constructor.
- *
- * @param input The POJO to serialize. Can also be a {@link Reader} or {@link InputStream}.
- * @param serializer The serializer to use to serialize this response.
- * @param schema The optional schema information about the serialized part.
- */
- public RestRequestEntity(Object input, Serializer serializer, HttpPartSchema schema) {
- this.output = input;
- this.serializer = serializer;
- this.schema = schema;
- if (serializer != null && serializer.getResponseContentType() != null)
- setContentType(new BasicHeader("Content-Type", serializer.getResponseContentType().toString()));
- }
-
- @Override /* BasicHttpEntity */
- public void writeTo(OutputStream os) throws IOException {
- os = new NoCloseOutputStream(os);
- if (output instanceof InputStream) {
- IOPipe.create(output, os).run();
- } else if (output instanceof Reader) {
- try (OutputStreamWriter osw = new OutputStreamWriter(os, UTF8)) {
- IOPipe.create(output, osw).run();
- }
- } else {
- try {
- if (serializer == null) {
- // If no serializer specified, just close the stream.
- os.close();
- } else {
- SerializerSessionArgs sArgs = SerializerSessionArgs.create().schema(schema);
- SerializerSession session = serializer.createSession(sArgs);
- try (Closeable c = session.isWriterSerializer() ? new OutputStreamWriter(os, UTF8) : os) {
- session.serialize(output, c);
- }
- }
- } catch (SerializeException e) {
- throw new org.apache.juneau.rest.client.RestCallException(e);
- }
- }
- }
-
- @Override /* BasicHttpEntity */
- public boolean isRepeatable() {
- return true;
- }
-
- @Override /* BasicHttpEntity */
- public InputStream getContent() {
- if (outputBytes == null) {
- try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
- writeTo(baos);
- outputBytes = baos.toByteArray();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return new ByteArrayInputStream(outputBytes);
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RetryOn.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RetryOn.java
deleted file mode 100644
index b72fe50..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/RetryOn.java
+++ /dev/null
@@ -1,69 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import org.apache.http.*;
-import org.apache.http.client.*;
-
-/**
- * Used to determine whether a request should be retried based on the HTTP response code.
- *
- * <p>
- * Subclasses should override either the {@link #onCode(int)} method (if you only care about the HTTP status code)
- * or {@link #onResponse(HttpResponse)} (if you want full access to the HTTP response object.
- *
- * @deprecated Use {@link org.apache.juneau.rest.client2.RestClientBuilder#retryHandler(HttpRequestRetryHandler)}.
- */
-@Deprecated
-public abstract class RetryOn {
-
- /**
- * Default RetryOn that returns <jk>true</jk> of any HTTP response >= 400 is received.
- */
- public static final RetryOn DEFAULT = new RetryOn() {
- @Override /* RetryOn */
- public boolean onCode(int httpResponseCode) {
- return httpResponseCode <= 0 || httpResponseCode >= 400;
- }
- };
-
- /**
- * Default RetryOn that returns <jk>true</jk> if the HTTP connection could not be made.
- */
- public static final RetryOn CONNECTION_LOST = new RetryOn() {
- @Override /* RetryOn */
- public boolean onCode(int httpResponseCode) {
- return httpResponseCode <= 0;
- }
- };
-
- /**
- * Subclasses should override this method to determine whether the HTTP response is retryable.
- *
- * @param response The HTTP response object. May be <jk>null</jk> if a connection could not be made.
- * @return <jk>true</jk> if the specified response code is retryable.
- */
- protected boolean onResponse(HttpResponse response) {
- return onCode(response == null || response.getStatusLine() == null ? -1 : response.getStatusLine().getStatusCode());
- }
-
- /**
- * Subclasses should override this method to determine whether the HTTP response is retryable.
- *
- * @param httpResponseCode The HTTP response code. <c>-1</c> if a connection could not be made.
- * @return <jk>true</jk> if the specified response code is retryable.
- */
- protected boolean onCode(int httpResponseCode) {
- return false;
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/SerializedNameValuePair.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/SerializedNameValuePair.java
deleted file mode 100644
index 1817e61..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/SerializedNameValuePair.java
+++ /dev/null
@@ -1,80 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import static org.apache.juneau.httppart.HttpPartType.*;
-
-import org.apache.http.*;
-import org.apache.juneau.*;
-import org.apache.juneau.httppart.*;
-import org.apache.juneau.oapi.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.urlencoding.*;
-
-/**
- * Subclass of {@link NameValuePair} for serializing POJOs as URL-encoded form post entries using the
- * {@link UrlEncodingSerializer class}.
- *
- * <h5 class='section'>Example:</h5>
- * <p class='bcode w800'>
- * NameValuePairs params = <jk>new</jk> NameValuePairs()
- * .append(<jk>new</jk> SerializedNameValuePair(<js>"myPojo"</js>, pojo, UrlEncodingSerializer.<jsf>DEFAULT_SIMPLE</jsf>))
- * .append(<jk>new</jk> BasicNameValuePair(<js>"someOtherParam"</js>, <js>"foobar"</js>));
- * request.setEntity(<jk>new</jk> UrlEncodedFormEntity(params));
- * </p>
- *
- * @deprecated Use {@link org.apache.juneau.http.SerializedNameValuePair}.
- */
-@Deprecated
-public final class SerializedNameValuePair implements NameValuePair {
- private String name;
- private Object value;
- private HttpPartSerializer serializer;
- private HttpPartSchema schema;
-
- /**
- * Constructor.
- *
- * @param name The parameter name.
- * @param value The POJO to serialize to the parameter value.
- * @param serializer
- * The serializer to use for serializing the value to a string value.
- * @param schema
- * The schema object that defines the format of the output.
- * <br>If <jk>null</jk>, defaults to the schema defined on the serializer.
- * <br>If that's also <jk>null</jk>, defaults to {@link HttpPartSchema#DEFAULT}.
- * <br>Only used if serializer is schema-aware (e.g. {@link OpenApiSerializer}).
- */
- public SerializedNameValuePair(String name, Object value, HttpPartSerializer serializer, HttpPartSchema schema) {
- this.name = name;
- this.value = value;
- this.serializer = serializer;
- this.schema = schema;
- }
-
- @Override /* NameValuePair */
- public String getName() {
- return name;
- }
-
- @Override /* NameValuePair */
- public String getValue() {
- try {
- return serializer.createPartSession(null).serialize(FORMDATA, schema, value);
- } catch (SchemaValidationException e) {
- throw new BasicRuntimeException(e, "Validation error on request form-data parameter ''{0}''=''{1}''", name, value);
- } catch (SerializeException e) {
- throw new BasicRuntimeException(e, "Serialization error on request form-data parameter ''{0}''", name);
- }
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/SimpleX509TrustManager.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/SimpleX509TrustManager.java
deleted file mode 100644
index 2521ac8..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/SimpleX509TrustManager.java
+++ /dev/null
@@ -1,69 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client;
-
-import java.security.*;
-import java.security.cert.*;
-
-import javax.net.ssl.*;
-
-/**
- * A trust manager that optionally allows for self-signed certificates.
- *
- * @deprecated No replacement.
- */
-@Deprecated
-public final class SimpleX509TrustManager implements X509TrustManager {
-
- private X509TrustManager baseTrustManager; // The JRE-provided trust manager used to validate certificates presented by a server.
-
- /**
- * Constructor.
- *
- * @param lax If <jk>true</jk>, allow self-signed and expired certificates.
- * @throws KeyStoreException Generic keystore exception.
- * @throws NoSuchAlgorithmException Unknown cryptographic algorithm.
- */
- public SimpleX509TrustManager(boolean lax) throws KeyStoreException, NoSuchAlgorithmException {
- if (! lax) {
- // Find the JRE-provided X509 trust manager.
- KeyStore ks = KeyStore.getInstance("jks");
- TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
- factory.init(ks);
- for (TrustManager tm : factory.getTrustManagers()) {
- if (tm instanceof X509TrustManager) {
- baseTrustManager = (X509TrustManager)tm; // Take the first X509TrustManager we find
- return;
- }
- }
- throw new IllegalStateException("Couldn't find JRE's X509TrustManager");
- }
- }
-
- @Override /* X509TrustManager */
- public X509Certificate[] getAcceptedIssuers() {
- return baseTrustManager == null ? new X509Certificate[0] : baseTrustManager.getAcceptedIssuers();
- }
-
- @Override /* X509TrustManager */
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- if (baseTrustManager != null)
- baseTrustManager.checkClientTrusted(chain, authType);
- }
-
- @Override /* X509TrustManager */
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- if (baseTrustManager != null)
- baseTrustManager.checkServerTrusted(chain, authType);
- }
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/MockHttpClientConnection.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/MockHttpClientConnection.java
deleted file mode 100644
index c65056d..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/MockHttpClientConnection.java
+++ /dev/null
@@ -1,123 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client.mock;
-
-import java.io.*;
-import java.util.*;
-
-import org.apache.http.*;
-import org.apache.http.entity.*;
-import org.apache.http.message.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.utils.*;
-
-/**
- * An implementation of {@link HttpClientConnection} specifically for use in mocked connections using the {@link MockHttpConnection} class.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use <c>org.apache.juneau.restmock2</c>
- * </div>
- *
- * This implementation is NOT thread safe.
- */
-@Deprecated
-public class MockHttpClientConnection implements HttpClientConnection {
-
- private final MockHttpConnection c;
- private volatile MockHttpRequest req;
- private volatile MockHttpResponse res;
-
- /**
- * Constructor.
- *
- * @param c The API for performing the connections.
- */
- public MockHttpClientConnection(MockHttpConnection c) {
- this.c = c;
- }
-
- @Override /* HttpClientConnection */
- public void close() throws IOException {}
-
- @Override /* HttpClientConnection */
- public boolean isOpen() {
- return true;
- }
-
- @Override /* HttpClientConnection */
- public boolean isStale() {
- return false;
- }
-
- @Override /* HttpClientConnection */
- public void setSocketTimeout(int timeout) {}
-
- @Override /* HttpClientConnection */
- public int getSocketTimeout() {
- return Integer.MAX_VALUE;
- }
-
- @Override /* HttpClientConnection */
- public void shutdown() throws IOException {}
-
- @Override /* HttpClientConnection */
- public HttpConnectionMetrics getMetrics() {
- return null;
- }
-
- @Override /* HttpClientConnection */
- public boolean isResponseAvailable(int timeout) throws IOException {
- return true;
- }
-
- @Override /* HttpClientConnection */
- public void sendRequestHeader(HttpRequest request) throws HttpException, IOException {
- try {
- RequestLine rl = request.getRequestLine();
- req = c.request(rl.getMethod(), rl.getUri(), null);
- for (Header h : request.getAllHeaders())
- req.header(h.getName(), h.getValue());
- } catch (Exception e) {
- throw new HttpException(e.getMessage(), e);
- }
- }
-
- @Override /* HttpClientConnection */
- public void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException {
- req.body(request.getEntity() == null ? "" : IOUtils.readBytes(request.getEntity().getContent(), 1024));
- }
-
- @Override /* HttpClientConnection */
- public HttpResponse receiveResponseHeader() throws HttpException, IOException {
- try {
- res = req.execute();
- HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, res.getStatus(), res.getMessage()));
- for (Map.Entry<String,String[]> e : res.getHeaders().entrySet())
- for (String hv : e.getValue())
- response.addHeader(e.getKey(), hv);
- return response;
- } catch (Exception e) {
- throw new HttpException(e.getMessage(), e);
- }
- }
-
- @Override /* HttpClientConnection */
- public void receiveResponseEntity(HttpResponse response) throws HttpException, IOException {
- BasicHttpEntity e = new BasicHttpEntity();
- e.setContent(new ByteArrayInputStream(res.getBody()));
- response.setEntity(e);
- }
-
- @Override /* HttpClientConnection */
- public void flush() throws IOException {}
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/MockHttpClientConnectionManager.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/MockHttpClientConnectionManager.java
deleted file mode 100644
index 53237e7..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/MockHttpClientConnectionManager.java
+++ /dev/null
@@ -1,82 +0,0 @@
-// ***************************************************************************************************************************
-// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
-// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
-// * to you 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 org.apache.juneau.rest.client.mock;
-
-import java.io.*;
-import java.util.concurrent.*;
-
-import org.apache.http.*;
-import org.apache.http.conn.*;
-import org.apache.http.conn.routing.*;
-import org.apache.http.protocol.*;
-import org.apache.juneau.utils.*;
-
-/**
- * An implementation of {@link HttpClientConnectionManager} specifically for use in mocked connections using the {@link MockHttpConnection} class.
- *
- * <div class='warn'>
- * <b>Deprecated</b> - Use <c>org.apache.juneau.restmock2</c>
- * </div>
- *
- * This implementation is NOT thread safe.
- */
-@Deprecated
-public class MockHttpClientConnectionManager implements HttpClientConnectionManager {
-
- final ConnectionRequest cr;
-
- /**
- * Constructor.
- *
- * @param c The mocked connection.
- */
- public MockHttpClientConnectionManager(final MockHttpConnection c) {
- final HttpClientConnection hcc = new MockHttpClientConnection(c);
- this.cr = new ConnectionRequest() {
- @Override
- public boolean cancel() {
- return false;
- }
- @Override
- public HttpClientConnection get(long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
- return hcc;
- }
- };
- }
-
- @Override /* HttpClientConnectionManager */
- public ConnectionRequest requestConnection(HttpRoute route, Object state) {
- return cr;
- }
-
- @Override /* HttpClientConnectionManager */
- public void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit) {}
-
- @Override /* HttpClientConnectionManager */
- public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context) throws IOException {}
-
- @Override /* HttpClientConnectionManager */
- public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {}
-
- @Override /* HttpClientConnectionManager */
- public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {}
-
- @Override /* HttpClientConnectionManager */
- public void closeIdleConnections(long idletime, TimeUnit tunit) {}
-
- @Override /* HttpClientConnectionManager */
- public void closeExpiredConnections() {}
-
- @Override /* HttpClientConnectionManager */
- public void shutdown() {}
-}
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/package-info.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/package-info.java
deleted file mode 100644
index dc23713..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/mock/package-info.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/***************************************************************************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
- * to you 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.
- *
- ***************************************************************************************************************************/
-
-/**
- * REST Client Mock API (deprecated)
- */
-package org.apache.juneau.rest.client.mock;
\ No newline at end of file
diff --git a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/package-info.java b/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/package-info.java
deleted file mode 100644
index 4c16fdd..0000000
--- a/juneau-rest/juneau-rest-client/src/main/java/org/apache/juneau/rest/client/package-info.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/***************************************************************************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
- * to you 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.
- *
- ***************************************************************************************************************************/
-
-/**
- * REST Client API
- */
-package org.apache.juneau.rest.client;
\ No newline at end of file