001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.rest.client.classic; 018 019import static java.lang.Character.isWhitespace; 020import static java.util.logging.Level.*; 021import static org.apache.juneau.commons.httppart.HttpPartType.*; 022import static org.apache.juneau.commons.lang.StateEnum.*; 023import static org.apache.juneau.commons.utils.CollectionUtils.*; 024import static org.apache.juneau.commons.utils.CollectionUtils.isEmpty; 025import static org.apache.juneau.commons.utils.Shorts.*; 026import static org.apache.juneau.commons.utils.StringUtils.*; 027import static org.apache.juneau.commons.utils.StringUtils.isEmpty; 028import static org.apache.juneau.commons.utils.ThrowableUtils.*; 029import static org.apache.juneau.http.HttpMethod.*; 030import static org.apache.juneau.http.classic.HttpEntities.*; 031import static org.apache.juneau.http.classic.HttpHeaders.*; 032import static org.apache.juneau.http.classic.HttpParts.*; 033import static org.apache.juneau.rest.RestSharedConstants.*; 034import static org.apache.juneau.rest.client.classic.RestOperation.*; 035 036import java.io.*; 037import java.lang.reflect.*; 038import java.lang.reflect.Proxy; 039import java.net.*; 040import java.nio.charset.*; 041import java.util.*; 042import java.util.concurrent.*; 043import java.util.concurrent.atomic.*; 044import java.util.function.*; 045import java.util.logging.*; 046import java.util.regex.*; 047 048import javax.net.ssl.*; 049 050import org.apache.http.*; 051import org.apache.http.NameValuePair; 052import org.apache.http.auth.*; 053import org.apache.http.client.*; 054import org.apache.http.client.CookieStore; 055import org.apache.http.client.config.*; 056import org.apache.http.client.entity.*; 057import org.apache.http.client.methods.*; 058import org.apache.http.client.utils.*; 059import org.apache.http.config.*; 060import org.apache.http.conn.*; 061import org.apache.http.conn.routing.*; 062import org.apache.http.conn.socket.*; 063import org.apache.http.conn.ssl.*; 064import org.apache.http.conn.util.*; 065import org.apache.http.cookie.*; 066import org.apache.http.impl.client.*; 067import org.apache.http.impl.conn.*; 068import org.apache.http.params.*; 069import org.apache.http.protocol.*; 070import org.apache.http.ssl.SSLContexts; 071import org.apache.juneau.commons.*; 072import org.apache.juneau.commons.collections.*; 073import org.apache.juneau.commons.function.*; 074import org.apache.juneau.commons.http.*; 075import org.apache.juneau.commons.httppart.*; 076import org.apache.juneau.commons.inject.*; 077import org.apache.juneau.commons.reflect.*; 078import org.apache.juneau.http.classic.entity.*; 079import org.apache.juneau.http.classic.header.*; 080import org.apache.juneau.http.classic.part.*; 081import org.apache.juneau.http.classic.remote.RrpcInterfaceMeta; 082import org.apache.juneau.http.classic.resource.*; 083import org.apache.juneau.http.remote.*; 084import org.apache.juneau.marshall.*; 085import org.apache.juneau.marshall.bson.*; 086import org.apache.juneau.marshall.cbor.*; 087import org.apache.juneau.marshall.hjson.*; 088import org.apache.juneau.marshall.hocon.*; 089import org.apache.juneau.marshall.html.*; 090import org.apache.juneau.marshall.httppart.*; 091import org.apache.juneau.marshall.ini.*; 092import org.apache.juneau.marshall.jcs.*; 093import org.apache.juneau.marshall.json.*; 094import org.apache.juneau.marshall.json5.*; 095import org.apache.juneau.marshall.json5l.*; 096import org.apache.juneau.marshall.jsonl.*; 097import org.apache.juneau.marshall.markdown.*; 098import org.apache.juneau.marshall.marshaller.*; 099import org.apache.juneau.marshall.marshaller.Uon; 100import org.apache.juneau.marshall.msgpack.*; 101import org.apache.juneau.marshall.oapi.*; 102import org.apache.juneau.marshall.parquet.*; 103import org.apache.juneau.marshall.parser.*; 104import org.apache.juneau.marshall.parser.ParseException; 105import org.apache.juneau.marshall.plaintext.*; 106import org.apache.juneau.marshall.prototext.*; 107import org.apache.juneau.marshall.serializer.*; 108import org.apache.juneau.marshall.toml.*; 109import org.apache.juneau.marshall.uon.*; 110import org.apache.juneau.marshall.urlencoding.*; 111import org.apache.juneau.marshall.xml.*; 112import org.apache.juneau.rest.*; 113import org.apache.juneau.rest.client.classic.assertion.*; 114import org.apache.juneau.rest.client.classic.remote.*; 115 116/** 117 * Utility class for interfacing with remote REST interfaces. 118 * 119 * <p> 120 * Built upon the feature-rich Apache HttpClient library, the Juneau RestClient API adds support for fluent-style 121 * REST calls and the ability to perform marshalling of POJOs to and from HTTP parts. 122 * 123 * <h2 class='figure'>Example:</h2> 124 * <p class='bjava'> 125 * <jc>// Create a basic REST client with JSON support and download a bean.</jc> 126 * MyBean <jv>bean</jv> = RestClient.<jsm>create</jsm>() 127 * .json5() 128 * .build() 129 * .get(<jsf>URI</jsf>) 130 * .run() 131 * .assertStatus().asCode().is(200) 132 * .assertHeader(<js>"Content-Type"</js>).matchesSimple(<js>"application/json*"</js>) 133 * .getContent().as(MyBean.<jk>class</jk>); 134 * </p> 135 * 136 * <p> 137 * Breaking apart the fluent call, we can see the classes being used: 138 * <p class='bjava'> 139 * RestClient.Builder<?> <jv>builder</jv> = RestClient.<jsm>create</jsm>().json5(); 140 * RestClient <jv>client</jv> = <jv>builder</jv>.build(); 141 * RestRequest <jv>req</jv> = <jv>client</jv>.get(<jsf>URI</jsf>); 142 * RestResponse <jv>res</jv> = <jv>req</jv>.run(); 143 * RestResponseStatusLineAssertion <jv>statusLineAssertion</jv> = <jv>res</jv>.assertStatus(); 144 * FluentIntegerAssertion<RestResponse> <jv>codeAssertion</jv> = <jv>statusLineAssertion</jv>.asCode(); 145 * <jv>res</jv> = <jv>codeAssertion</jv>.is(200); 146 * FluentStringAssertion<RestResponse> <jv>headerAssertion</jv> = <jv>res</jv>.assertHeader(<js>"Content-Type"</js>); 147 * <jv>res</jv> = <jv>headerAssertion</jv>.matchesSimple(<js>"application/json*"</js>); 148 * RestResponseBody <jv>content</jv> = <jv>res</jv>.getContent(); 149 * MyBean <jv>bean</jv> = <jv>content</jv>.as(MyBean.<jk>class</jk>); 150 * </p> 151 * 152 * <p> 153 * It additionally provides support for creating remote proxy interfaces using REST as the transport medium. 154 * 155 * <h3 class='figure'>Example:</h3> 156 * <p class='bjava'> 157 * <jc>// Define a Remote proxy for interacting with a REST interface.</jc> 158 * <ja>@Remote</ja>(path=<js>"/petstore"</js>) 159 * <jk>public interface</jk> PetStore { 160 * 161 * <ja>@RemotePost</ja>(<js>"/pets"</js>) 162 * Pet addPet( 163 * <ja>@Content</ja> CreatePet <jv>pet</jv>, 164 * <ja>@Header</ja>(<js>"E-Tag"</js>) UUID <jv>etag</jv>, 165 * <ja>@Query</ja>(<js>"debug"</js>) <jk>boolean</jk> <jv>debug</jv> 166 * ); 167 * } 168 * 169 * <jc>// Use a RestClient with default JSON 5 support.</jc> 170 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().json5().build(); 171 * 172 * PetStore <jv>store</jv> = <jv>client</jv>.getRemote(PetStore.<jk>class</jk>, <js>"http://localhost:10000"</js>); 173 * CreatePet <jv>createPet</jv> = <jk>new</jk> CreatePet(<js>"Fluffy"</js>, 9.99); 174 * Pet <jv>pet</jv> = <jv>store</jv>.addPet(<jv>createPet</jv>, UUID.<jsm>randomUUID</jsm>(), <jk>true</jk>); 175 * </p> 176 * 177 * <p> 178 * The classes are closely tied to Apache HttpClient, yet provide lots of additional functionality: 179 * <ul class='javatree'> 180 * <li class='jc'>{@link RestClient} <jk>extends</jk> {@link HttpClient}, creates {@link RestRequest} objects. 181 * <li class='jc'>{@link RestRequest} <jk>extends</jk> {@link HttpUriRequest}, creates {@link RestResponse} objects. 182 * <li class='jc'>{@link RestResponse} creates {@link ResponseContent} and {@link ResponseHeader} objects. 183 * <li class='jc'>{@link ResponseContent} <jk>extends</jk> {@link HttpEntity} 184 * <li class='jc'>{@link ResponseHeader} <jk>extends</jk> {@link Header} 185 * </ul> 186 * 187 * 188 * <p> 189 * Instances of this class are built using the {@link Builder} class which can be constructed using 190 * the {@link #create() RestClient.create()} method as shown above. 191 * 192 * <p> 193 * Clients are typically created with a root URI so that relative URIs can be used when making requests. 194 * This is done using the {@link Builder#rootUrl(Object)} method. 195 * 196 * <h3 class='figure'>Example:</h3> 197 * <p class='bjava'> 198 * <jc>// Create a client where all URIs are relative to localhost.</jc> 199 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().json().rootUrl(<js>"http://localhost:5000"</js>).build(); 200 * 201 * <jc>// Use relative paths.</jc> 202 * String <jv>body</jv> = <jv>client</jv>.get(<js>"/subpath"</js>).run().getContent().asString(); 203 * </p> 204 * 205 * <p> 206 * The {@link RestClient} class creates {@link RestRequest} objects using the following methods: 207 * 208 * <ul class='javatree'> 209 * <li class='jc'>{@link RestClient} 210 * <ul> 211 * <li class='jm'>{@link RestClient#get(Object) get(uri)} / {@link RestClient#get() get()} 212 * <li class='jm'>{@link RestClient#put(Object,Object) put(uri,body)} / {@link RestClient#put(Object) put(uri)} 213 * <li class='jm'>{@link RestClient#post(Object) post(uri,body)} / {@link RestClient#post(Object) post(uri)} 214 * <li class='jm'>{@link RestClient#patch(Object,Object) patch(uri,body)} / {@link RestClient#patch(Object) patch(uri)} 215 * <li class='jm'>{@link RestClient#delete(Object) delete(uri)} 216 * <li class='jm'>{@link RestClient#head(Object) head(uri)} 217 * <li class='jm'>{@link RestClient#options(Object) options(uri)} 218 * <li class='jm'>{@link RestClient#formPost(Object,Object) formPost(uri,body)} / {@link RestClient#formPost(Object) formPost(uri)} 219 * <li class='jm'>{@link RestClient#formPostPairs(Object,String...) formPostPairs(uri,parameters...)} 220 * <li class='jm'>{@link RestClient#request(String,Object,Object) request(method,uri,body)} 221 * </ul> 222 * </ul> 223 * 224 * <p> 225 * The {@link RestRequest} class creates {@link RestResponse} objects using the following methods: 226 * 227 * <ul class='javatree'> 228 * <li class='jc'>{@link RestRequest} 229 * <ul> 230 * <li class='jm'>{@link RestRequest#run() run()} 231 * <li class='jm'>{@link RestRequest#complete() complete()} 232 * </ul> 233 * </ul> 234 * 235 * <p> 236 * The distinction between the two methods is that {@link RestRequest#complete() complete()} automatically consumes the response body and 237 * {@link RestRequest#run() run()} does not. Note that you must consume response bodies in order for HTTP connections to be freed up 238 * for reuse! The {@link InputStream InputStreams} returned by the {@link ResponseContent} object are auto-closing once 239 * they are exhausted, so it is often not necessary to explicitly close them. 240 * 241 * <p> 242 * The following examples show the distinction between the two calls: 243 * 244 * <p class='bjava'> 245 * <jc>// Consuming the response, so use run().</jc> 246 * String <jv>body</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).run().getContent().asString(); 247 * 248 * <jc>// Only interested in response status code, so use complete().</jc> 249 * <jk>int</jk> <jv>status</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).complete().getStatusCode(); 250 * </p> 251 * 252 * 253 * <h2 class='topic'>POJO Marshalling</h2> 254 * 255 * <p> 256 * By default, JSON support is provided for HTTP request and response bodies. 257 * Other languages can be specified using any of the following builder methods: 258 * <ul class='javatree'> 259 * <li class='jc'>{@link Builder} 260 * <ul> 261 * <li class='jm'>{@link Builder#json() json()} 262 * <li class='jm'>{@link Builder#json5() json5()} 263 * <li class='jm'>{@link Builder#xml() xml()} 264 * <li class='jm'>{@link Builder#html() html()} 265 * <li class='jm'>{@link Builder#plainText() plainText()} 266 * <li class='jm'>{@link Builder#bson() bson()} 267 * <li class='jm'>{@link Builder#msgPack() msgPack()} 268 * <li class='jm'>{@link Builder#uon() uon()} 269 * <li class='jm'>{@link Builder#urlEnc() urlEnc()} 270 * <li class='jm'>{@link Builder#openApi() openApi()} 271 * </ul> 272 * </ul> 273 * 274 * <h3 class='figure'>Example:</h3> 275 * <p class='bjava'> 276 * <jc>// Create a basic REST client with JSON 5 support.</jc> 277 * <jc>// Typically easier to use when performing unit tests.</jc> 278 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().json5().build(); 279 * </p> 280 * 281 * <p> 282 * Clients can also support multiple languages: 283 * 284 * <h3 class='figure'>Example:</h3> 285 * <p class='bjava'> 286 * <jc>// Create a REST client with support for multiple languages.</jc> 287 * RestClient <jv>client1</jv> = RestClient.<jsm>create</jsm>().json().xml().openApi().build(); 288 * 289 * <jc>// Create a REST client with support for all supported languages.</jc> 290 * RestClient <jv>client2</jv> = RestClient.<jsm>create</jsm>().universal().build(); 291 * </p> 292 * 293 * <p> 294 * When using clients with multiple language support, you must specify the <c>Content-Type</c> header on requests 295 * with bodies to specify which serializer should be selected. 296 * 297 * <p class='bjava'> 298 * <jc>// Create a REST client with support for multiple languages.</jc> 299 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().universal().build(); 300 * 301 * <jv>client</jv> 302 * .post(<jsf>URI</jsf>, <jv>myBean</jv>) 303 * .contentType(<js>"application/json"</js>) 304 * .complete() 305 * .assertStatus().is(200); 306 * </p> 307 * 308 * <p> 309 * Languages can also be specified per-request. 310 * 311 * <p class='bjava'> 312 * <jc>// Create a REST client with no default languages supported.</jc> 313 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().build(); 314 * 315 * <jc>// Use JSON for this request.</jc> 316 * <jv>client</jv> 317 * .post(<jsf>URI</jsf>, <jv>myBean</jv>) 318 * .json() 319 * .complete() 320 * .assertStatus().is(200); 321 * </p> 322 * 323 * 324 * <p> 325 * The {@link Builder} class provides convenience methods for setting common serializer and parser 326 * settings. 327 * 328 * <h3 class='figure'>Example:</h3> 329 * <p class='bjava'> 330 * <jc>// Create a basic REST client with JSON support.</jc> 331 * <jc>// Use single-quotes and whitespace.</jc> 332 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().json().sq().ws().build(); 333 * </p> 334 * 335 * <p> 336 * Other methods are also provided for specifying the serializers and parsers used for lower-level marshalling support: 337 * <ul class='javatree'> 338 * <li class='jc'>{@link Builder} 339 * <ul> 340 * <li class='jm'>{@link Builder#serializer(Serializer) serializer(Serializer)} 341 * <li class='jm'>{@link Builder#parser(Parser) parser(Parser)} 342 * <li class='jm'>{@link Builder#marshaller(Marshaller) marshaller(Marshaller)} 343 * </ul> 344 * </ul> 345 * 346 * <p> 347 * HTTP parts (headers, query parameters, form data...) are serialized and parsed using the {@link HttpPartSerializer} 348 * and {@link HttpPartParser} APIs. By default, clients are configured to use {@link OpenApiSerializer} and 349 * {@link OpenApiParser}. These can be overridden using the following methods: 350 * <ul class='javatree'> 351 * <li class='jc'>{@link Builder} 352 * <ul> 353 * <li class='jm'>{@link Builder#partSerializer(Class) partSerializer(Class<? extends HttpPartSerializer>)} 354 * <li class='jm'>{@link Builder#partParser(Class) partParser(Class<? extends HttpPartParser>)} 355 * </ul> 356 * </ul> 357 * 358 * 359 * <h2 class='topic'>Request Headers</h2> 360 * <p> 361 * Per-client or per-request headers can be specified using the following methods: 362 * <ul class='javatree'> 363 * <li class='jc'>{@link Builder} 364 * <ul> 365 * <li class='jm'>{@link Builder#headers() headerData()} 366 * <li class='jm'>{@link Builder#header(String,String) header(String,Object)} 367 * <li class='jm'>{@link Builder#header(String,Supplier) header(String,Supplier<?>)} 368 * <li class='jm'>{@link Builder#headers(Header...) headers(Header...)} 369 * <li class='jm'>{@link Builder#headersDefault(Header...) defaultHeaders(Header...)} 370 * </ul> 371 * <li class='jc'>{@link RestRequest} 372 * <ul> 373 * <li class='jm'>{@link RestRequest#header(String,Object) header(String,Object)} 374 * <li class='jm'>{@link RestRequest#headers(Header...) headers(Header...)} 375 * <li class='jm'>{@link RestRequest#headersBean(Object) headersBean(Object)} 376 * <li class='jm'>{@link RestRequest#headerPairs(String...) headerPairs(String...)} 377 * </ul> 378 * </ul> 379 * 380 * <p> 381 * The supplier methods are particularly useful for header values whose values may change over time (such as <c>Authorization</c> headers 382 * which may need to change every few minutes). 383 * </p> 384 * 385 * <h3 class='figure'>Example:</h3> 386 * <p class='bjava'> 387 * <jc>// Create a client that adds a dynamic Authorization header to every request.</jc> 388 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().header(<js>"Authorization"</js>, ()->getMyAuthToken()).build(); 389 * </p> 390 * 391 * <p> 392 * The {@link HttpPartSchema} API allows you to define OpenAPI schemas to POJO data structures on both requests 393 * and responses. 394 * 395 * <h3 class='figure'>Example:</h3> 396 * <p class='bjava'> 397 * <jc>// Create a client that adds a header "Foo: bar|baz" to every request.</jc> 398 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>() 399 * .header(<js>"Foo"</js>, AList.<jsm>of</jsm>(<js>"bar"</js>,<js>"baz"</js>), <jsf>T_ARRAY_PIPES</jsf>) 400 * .build(); 401 * </p> 402 * 403 * <p> 404 * The methods with {@link ListOperation} parameters allow you to control whether new headers get appended, prepended, or 405 * replace existing headers with the same name. 406 * 407 * <h3 class='section'>Notes:</h3><ul> 408 * <li class='note'>Methods that pass in POJOs convert values to strings using the part serializers. Methods that pass in <c>Header</c> or 409 * <c>NameValuePair</c> objects use the values returned by that bean directly. 410 * </ul> 411 * 412 * 413 * <h2 class='topic'>Request Query Parameters</h2> 414 * <p> 415 * Per-client or per-request query parameters can be specified using the following methods: 416 * <ul class='javatree'> 417 * <li class='jc'>{@link Builder} 418 * <ul> 419 * <li class='jm'>{@link Builder#queryData() queryData()} 420 * <li class='jm'>{@link Builder#queryData(String,String) queryData(String,String)} 421 * <li class='jm'>{@link Builder#queryData(String,Supplier) queryData(String,Supplier<?>)} 422 * <li class='jm'>{@link Builder#queryData(NameValuePair...) queryData(NameValuePair...)} 423 * <li class='jm'>{@link Builder#queryDataDefault(NameValuePair...) defaultQueryData(NameValuePair...)} 424 * </ul> 425 * <li class='jc'>{@link RestRequest} 426 * <ul> 427 * <li class='jm'>{@link RestRequest#queryData(String,Object) queryData(String,Object)} 428 * <li class='jm'>{@link RestRequest#queryData(NameValuePair...) queryData(NameValuePair...)} 429 * <li class='jm'>{@link RestRequest#queryDataBean(Object) queryDataBean(Object)} 430 * <li class='jm'>{@link RestRequest#queryCustom(Object) queryCustom(Object)} 431 * <li class='jm'>{@link RestRequest#queryDataPairs(String...) queryDataPairs(String...)} 432 * </ul> 433 * </ul> 434 * 435 * <h3 class='figure'>Example:</h3> 436 * <p class='bjava'> 437 * <jc>// Create a client that adds a ?foo=bar query parameter to every request.</jc> 438 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().query(<js>"foo"</js>, <js>"bar"</js>).build(); 439 * 440 * <jc>// Or do it on every request.</jc> 441 * String <jv>response</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).query(<js>"foo"</js>, <js>"bar"</js>).run().getContent().asString(); 442 * </p> 443 * 444 * <h3 class='section'>Notes:</h3><ul> 445 * <li class='note'>Like header values, dynamic values and OpenAPI schemas are supported. 446 * <li class='note'>Methods that pass in POJOs convert values to strings using the part serializers. Methods that pass in <c>NameValuePair</c> 447 * objects use the values returned by that bean directly. 448 * </ul> 449 * 450 * 451 * <h2 class='topic'>Request Form Data</h2> 452 * 453 * <p> 454 * Per-client or per-request form-data parameters can be specified using the following methods: 455 * <ul class='javatree'> 456 * <li class='jc'>{@link Builder} 457 * <ul> 458 * <li class='jm'>{@link Builder#formData() formData()} 459 * <li class='jm'>{@link Builder#formData(String,String) formData(String,String)} 460 * <li class='jm'>{@link Builder#formData(String,Supplier) formData(String,Supplier<?>)} 461 * <li class='jm'>{@link Builder#formData(NameValuePair...) formDatas(NameValuePair...)} 462 * <li class='jm'>{@link Builder#formDataDefault(NameValuePair...) defaultFormData(NameValuePair...)} 463 * </ul> 464 * <li class='jc'>{@link RestRequest} 465 * <ul> 466 * <li class='jm'>{@link RestRequest#formData(String,Object) formData(String,Object)} 467 * <li class='jm'>{@link RestRequest#formData(NameValuePair...) formData(NameValuePair...)} 468 * <li class='jm'>{@link RestRequest#formDataBean(Object) formDataBean(Object)} 469 * <li class='jm'>{@link RestRequest#formDataCustom(Object) formDataCustom(Object)} 470 * <li class='jm'>{@link RestRequest#formDataPairs(String...) formDataPairs(String...)} 471 * </ul> 472 * </ul> 473 * 474 * <h3 class='section'>Notes:</h3><ul> 475 * <li class='note'>Like header values, dynamic values and OpenAPI schemas are supported. 476 * <li class='note'>Methods that pass in POJOs convert values to strings using the part serializers. Methods that pass in <c>NameValuePair</c> 477 * objects use the values returned by that bean directly. 478 * </ul> 479 * 480 * 481 * <h2 class='topic'>Request Body</h2> 482 * 483 * <p> 484 * The request body can either be passed in with the client creator method (e.g. {@link RestClient#post(Object,Object) post(uri,body)}), 485 * or can be specified via the following methods: 486 * 487 * <ul class='javatree'> 488 * <li class='jc'>{@link RestRequest} 489 * <ul> 490 * <li class='jm'>{@link RestRequest#content(Object) body(Object)} 491 * <li class='jm'>{@link RestRequest#content(Object,HttpPartSchema) body(Object,HttpPartSchema)} 492 * </ul> 493 * </ul> 494 * 495 * <p> 496 * The request body can be any of the following types: 497 * <ul class='javatree'> 498 * <li class='jc'> 499 * {@link Object} - POJO to be converted to text using the {@link Serializer} defined on the client or request. 500 * <li class='jc'> 501 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 502 * <li class='jc'> 503 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 504 * <li class='jc'> 505 * {@link HttpResource} - Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. 506 * <li class='jc'> 507 * {@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 508 * <li class='jc'> 509 * {@link PartList} - Converted to a URL-encoded FORM post. 510 * <li class='jc'> 511 * {@link Supplier} - A supplier of anything on this list. 512 * </ul> 513 * 514 * <h3 class='section'>Notes:</h3><ul> 515 * <li class='note'>If the serializer on the client or request is explicitly set to <jk>null</jk>, POJOs will be converted to strings 516 * using the registered part serializer as content type <js>"text/plain</js>. If the part serializer is also <jk>null</jk>, 517 * POJOs will be converted to strings using {@link ClassMeta#toString(Object)} which typically just calls {@link Object#toString()}. 518 * </ul> 519 * 520 * 521 * <h2 class='topic'>Response Status</h2> 522 * 523 * <p> 524 * After execution using {@link RestRequest#run()} or {@link RestRequest#complete()}, the following methods can be used 525 * to get the response status: 526 * 527 * <ul class='javatree'> 528 * <li class='jc'>{@link RestResponse} 529 * <ul> 530 * <li class='jm'><c>{@link RestResponse#getStatusLine() getStatusLine()} <jk>returns</jk> {@link StatusLine}</c> 531 * <li class='jm'><c>{@link RestResponse#getStatusCode() getStatusCode()} <jk>returns</jk> <jk>int</jk></c> 532 * <li class='jm'><c>{@link RestResponse#getReasonPhrase() getReasonPhrase()} <jk>returns</jk> String</c> 533 * <li class='jm'><c>{@link RestResponse#assertStatus() assertStatus()} <jk>returns</jk> {@link FluentResponseStatusLineAssertion}</c> 534 * </ul> 535 * </ul> 536 * 537 * <h3 class='figure'>Example:</h3> 538 * <p class='bjava'> 539 * <jc>// Only interested in status code.</jc> 540 * <jk>int</jk> <jv>statusCode</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).complete().getStatusCode(); 541 * </p> 542 * 543 * <p> 544 * Equivalent methods with mutable parameters are provided to allow access to status values without breaking fluent call chains. 545 * 546 * <h3 class='figure'>Example:</h3> 547 * <p class='bjava'> 548 * <jc>// Interested in multiple values.</jc> 549 * Holder<Integer> <jv>statusCode</jv> = Holder.<jsm>create</jsm>(); 550 * Holder<String> <jv>reasonPhrase</jv> = Holder.<jsm>create</jsm>(); 551 * 552 * <jv>client</jv>.get(<jsf>URI</jsf>).complete().getStatusCode(<jv>statusCode</jv>).getReasonPhrase(<jv>reasonPhrase</jv>); 553 * System.<jsf>err</jsf>.println(<js>"statusCode="</js>+<jv>statusCode</jv>.get()+<js>", reasonPhrase="</js>+<jv>reasonPhrase</jv>.get()); 554 * </p> 555 * 556 * <h3 class='section'>Notes:</h3><ul> 557 * <li class='note'>If you are only interested in the response status and not the response body, be sure to use {@link RestRequest#complete()} instead 558 * of {@link RestRequest#run()} to make sure the response body gets automatically cleaned up. Otherwise you must 559 * consume the response yourself. 560 * </ul> 561 * 562 * <p> 563 * The assertion method is provided for quickly asserting status codes in fluent calls. 564 * 565 * <h3 class='figure'>Example:</h3> 566 * <p class='bjava'> 567 * <jc>// Status assertion using a static value.</jc> 568 * String <jv>body</jv> = <jv>client</jv>.get(<jsf>URI</jsf>) 569 * .run() 570 * .assertStatus().asCode().isBetween(200,399) 571 * .getContent().asString(); 572 * 573 * <jc>// Status assertion using a predicate.</jc> 574 * String <jv>body</jv> = <jv>client</jv>.get(<jsf>URI</jsf>) 575 * .run() 576 * .assertStatus().asCode().is(<jv>x</jv> -> <jv>x</jv><400) 577 * .getContent().asString(); 578 * </p> 579 * 580 * 581 * <h2 class='topic'>Response Headers</h2> 582 * 583 * <p> 584 * Response headers are accessed through the following methods: 585 * 586 * <ul class='javatree'> 587 * <li class='jc'>{@link RestResponse} 588 * <ul> 589 * <li class='jm'><c>{@link RestResponse#getHeaders(String) getHeaders(String)} <jk>returns</jk> {@link ResponseHeader}[]</c> 590 * <li class='jm'><c>{@link RestResponse#getFirstHeader(String) getFirstHeader(String)} <jk>returns</jk> {@link ResponseHeader}</c> 591 * <li class='jm'><c>{@link RestResponse#getLastHeader(String) getLastHeader(String)} <jk>returns</jk> {@link ResponseHeader}</c> 592 * <li class='jm'><c>{@link RestResponse#getAllHeaders() getAllHeaders()} <jk>returns</jk> {@link ResponseHeader}[]</c> 593 * <li class='jm'><c>{@link RestResponse#getStringHeader(String) getStringHeader(String)} <jk>returns</jk> String</c> 594 * <li class='jm'><c>{@link RestResponse#containsHeader(String) containsHeader(String)} <jk>returns</jk> <jk>boolean</jk></c> 595 * </ul> 596 * </ul> 597 * 598 * <p> 599 * The {@link RestResponse#getFirstHeader(String)} and {@link RestResponse#getLastHeader(String)} methods return an empty {@link ResponseHeader} object instead of<jk>null</jk>. 600 * This allows it to be used more easily in fluent calls. 601 * 602 * <h3 class='figure'>Example:</h3> 603 * <p class='bjava'> 604 * <jc>// See if response contains Location header.</jc> 605 * <jk>boolean</jk> <jv>hasLocationHeader</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).complete().getLastHeader(<js>"Location"</js>).exists(); 606 * </p> 607 * 608 * <p> 609 * The {@link ResponseHeader} class extends from the HttpClient {@link Header} class and provides several convenience 610 * methods: 611 * 612 * <ul class='javatree'> 613 * <li class='jc'>{@link ResponseHeader} 614 * <ul> 615 * <li class='jm'><c>{@link ResponseHeader#isPresent() isPresent()} <jk>returns</jk> <jk>boolean</jk></c> 616 * <li class='jm'><c>{@link ResponseHeader#asString() asString()} <jk>returns</jk> String</c> 617 * <li class='jm'><c>{@link ResponseHeader#as(Type,Type...) as(Type,Type...)} <jk>returns</jk> T</c> 618 * <li class='jm'><c>{@link ResponseHeader#as(Class) as(Class<T>)} <jk>returns</jk> T</c> 619 * <li class='jm'><c>{@link ResponseHeader#asMatcher(Pattern) asMatcher(Pattern)} <jk>returns</jk> {@link Matcher}</c> 620 * <li class='jm'><c>{@link ResponseHeader#asMatcher(String) asMatcher(String)} <jk>returns</jk> {@link Matcher}</c> 621 * <li class='jm'><c>{@link ResponseHeader#asHeader(Class) asHeader(Class<T <jk>extends</jk> BasicHeader> c)} <jk>returns</jk> {@link BasicHeader}</c> 622 * <li class='jm'><c>{@link ResponseHeader#asStringHeader() asStringHeader()} <jk>returns</jk> {@link BasicStringHeader}</c> 623 * <li class='jm'><c>{@link ResponseHeader#asIntegerHeader() asIntegerHeader()} <jk>returns</jk> {@link BasicIntegerHeader}</c> 624 * <li class='jm'><c>{@link ResponseHeader#asLongHeader() asLongHeader()} <jk>returns</jk> {@link BasicLongHeader}</c> 625 * <li class='jm'><c>{@link ResponseHeader#asDateHeader() asDateHeader()} <jk>returns</jk> {@link BasicDateHeader}</c> 626 * <li class='jm'><c>{@link ResponseHeader#asCsvHeader() asCsvHeader()} <jk>returns</jk> {@link BasicCsvHeader}</c> 627 * <li class='jm'><c>{@link ResponseHeader#asEntityTagsHeader() asEntityTagsHeader()} <jk>returns</jk> {@link BasicEntityTagsHeader}</c> 628 * <li class='jm'><c>{@link ResponseHeader#asStringRangesHeader() asStringRangesHeader()} <jk>returns</jk> {@link BasicStringRangesHeader}</c> 629 * <li class='jm'><c>{@link ResponseHeader#asUriHeader() asUriHeader()} <jk>returns</jk> {@link BasicUriHeader}</c> 630 * </ul> 631 * </ul> 632 * 633 * <p> 634 * The {@link ResponseHeader#schema(HttpPartSchema)} method allows you to perform parsing of OpenAPI formats for 635 * header parts. 636 * 637 * <h3 class='figure'>Example:</h3> 638 * <p class='bjava'> 639 * <jc>// Parse the header "Foo: bar|baz".</jc> 640 * List<String> <jv>fooHeader</jv> = <jv>client</jv> 641 * .get(<jsf>URI</jsf>) 642 * .complete() 643 * .getHeader(<js>"Foo"</js>).schema(<jsf>T_ARRAY_PIPES</jsf>).as(List.<jk>class</jk>, String.<jk>class</jk>); 644 * </p> 645 * 646 * <p> 647 * Assertion methods are also provided for fluent-style calls: 648 * 649 * <ul class='javatree'> 650 * <li class='jc'>{@link ResponseHeader} 651 * <ul> 652 * <li class='jm'><c>{@link ResponseHeader#assertValue() assertValue()} <jk>returns</jk> {@link FluentResponseHeaderAssertion}</c> 653 * </ul> 654 * </ul> 655 * 656 * <p> 657 * Note how in the following example, the fluent assertion returns control to the {@link RestResponse} object after 658 * the assertion has been completed: 659 * 660 * <h3 class='figure'>Example:</h3> 661 * <p class='bjava'> 662 * <jc>// Assert the response content type is any sort of JSON.</jc> 663 * String <jv>body</jv> = <jv>client</jv>.get(<jsf>URI</jsf>) 664 * .run() 665 * .getHeader(<js>"Content-Type"</js>).assertValue().matchesSimple(<js>"application/json*"</js>) 666 * .getContent().asString(); 667 * </p> 668 * 669 * 670 * <h2 class='topic'>Response Body</h2> 671 * 672 * <p> 673 * The response body is accessed through the following method: 674 * 675 * <ul class='javatree'> 676 * <li class='jc'>{@link RestResponse} 677 * <ul> 678 * <li class='jm'><c>{@link RestResponse#getContent() getContent()} <jk>returns</jk> {@link ResponseContent}</c> 679 * </ul> 680 * </ul> 681 * 682 * <p> 683 * The {@link ResponseContent} class extends from the HttpClient {@link HttpEntity} class and provides several convenience 684 * methods: 685 * 686 * <ul class='javatree'> 687 * <li class='jc'>{@link ResponseContent} 688 * <ul> 689 * <li class='jm'><c>{@link ResponseContent#asInputStream() asInputStream()} <jk>returns</jk> InputStream</c> 690 * <li class='jm'><c>{@link ResponseContent#asReader() asReader()} <jk>returns</jk> Reader</c> 691 * <li class='jm'><c>{@link ResponseContent#asReader(Charset) asReader(Charset)} <jk>returns</jk> Reader</c> 692 * <li class='jm'><c>{@link ResponseContent#pipeTo(OutputStream) pipeTo(OutputStream)} <jk>returns</jk> {@link RestResponse}</c> 693 * <li class='jm'><c>{@link ResponseContent#pipeTo(Writer) pipeTo(Writer)} <jk>returns</jk> {@link RestResponse}</c> 694 * <li class='jm'><c>{@link ResponseContent#as(Type,Type...) as(Type,Type...)} <jk>returns</jk> T</c> 695 * <li class='jm'><c>{@link ResponseContent#as(Class) as(Class<T>)} <jk>returns</jk> T</c> 696 * <li class='jm'><c>{@link ResponseContent#asFuture(Class) asFuture(Class<T>)} <jk>returns</jk> Future<T></c> 697 * <li class='jm'><c>{@link ResponseContent#asFuture(Type,Type...) asFuture(Type,Type...)} <jk>returns</jk> Future<T></c> 698 * <li class='jm'><c>{@link ResponseContent#asString() asString()} <jk>returns</jk> String</c> 699 * <li class='jm'><c>{@link ResponseContent#asStringFuture() asStringFuture()} <jk>returns</jk> Future<String></c> 700 * <li class='jm'><c>{@link ResponseContent#asAbbreviatedString(int) asAbbreviatedString(int)} <jk>returns</jk> String</c> 701 * <li class='jm'><c>{@link ResponseContent#asMatcher(Pattern) asMatcher(Pattern)} <jk>returns</jk> {@link Matcher}</c> 702 * <li class='jm'><c>{@link ResponseContent#asMatcher(String) asMatcher(String)} <jk>returns</jk> {@link Matcher}</c> 703 * </ul> 704 * </ul> 705 * 706 * <br> 707 * 708 * <h3 class='figure'>Examples:</h3> 709 * <p class='bjava'> 710 * <jc>// Parse into a linked-list of strings.</jc> 711 * List<String> <jv>list1</jv> = <jv>client</jv> 712 * .get(<jsf>URI</jsf>) 713 * .run() 714 * .getContent().as(LinkedList.<jk>class</jk>, String.<jk>class</jk>); 715 * 716 * <jc>// Parse into a linked-list of beans.</jc> 717 * List<MyBean> <jv>list2</jv> = <jv>client</jv> 718 * .get(<jsf>URI</jsf>) 719 * .run() 720 * .getContent().as(LinkedList.<jk>class</jk>, MyBean.<jk>class</jk>); 721 * 722 * <jc>// Parse into a linked-list of linked-lists of strings.</jc> 723 * List<List<String>> <jv>list3</jv> = <jv>client</jv> 724 * .get(<jsf>URI</jsf>) 725 * .run() 726 * .getContent().as(LinkedList.<jk>class</jk>, LinkedList.<jk>class</jk>, String.<jk>class</jk>); 727 * 728 * <jc>// Parse into a map of string keys/values.</jc> 729 * Map<String,String> <jv>map1</jv> = <jv>client</jv> 730 * .get(<jsf>URI</jsf>) 731 * .run() 732 * .getContent().as(TreeMap.<jk>class</jk>, String.<jk>class</jk>, String.<jk>class</jk>); 733 * 734 * <jc>// Parse into a map containing string keys and values of lists containing beans.</jc> 735 * Map<String,List<MyBean>> <jv>map2</jv> = <jv>client</jv> 736 * .get(<jsf>URI</jsf>) 737 * .run() 738 * .getContent().as(TreeMap.<jk>class</jk>, String.<jk>class</jk>, List.<jk>class</jk>, MyBean.<jk>class</jk>); 739 * </p> 740 * 741 * <p> 742 * The response body can only be consumed once unless it has been cached into memory. In many cases, the body is 743 * automatically cached when using the assertions methods or methods such as {@link ResponseContent#asString()}. 744 * However, methods that involve reading directly from the input stream cannot be called twice. 745 * In these cases, the {@link RestResponse#cacheContent()} and {@link ResponseContent#cache()} methods are provided 746 * to cache the response body in memory so that you can perform several operations against it. 747 * 748 * <p class='bjava'> 749 * <jc>// Cache the response body so we can access it twice.</jc> 750 * InputStream <jv>inputStream</jv> = <jv>client</jv> 751 * .get(<jsf>URI</jsf>) 752 * .run() 753 * .cacheBody() 754 * .getContent().pipeTo(<jv>someOtherStream</jv>) 755 * .getContent().asInputStream(); 756 * </p> 757 * 758 * <p> 759 * Assertion methods are also provided for fluent-style calls: 760 * 761 * <ul class='javatree'> 762 * <li class='jc'>{@link ResponseContent} 763 * <ul> 764 * <li class='jm'><c>{@link ResponseContent#assertValue() assertValue()} <jk>returns</jk> {@link FluentResponseBodyAssertion}</c> 765 * </ul> 766 * </ul> 767 * 768 * <br> 769 * 770 * <h3 class='figure'>Example:</h3> 771 * <p class='bjava'> 772 * <jc>// Assert that the body contains the string "Success".</jc> 773 * String <jv>body</jv> = <jv>client</jv> 774 * .get(<jsf>URI</jsf>) 775 * .run() 776 * .getContent().assertString().contains(<js>"Success"</js>) 777 * .getContent().asString(); 778 * </p> 779 * 780 * <p> 781 * Object assertions allow you to parse the response body into a POJO and then perform various tests on that resulting 782 * POJO. 783 * 784 * <h3 class='figure'>Example:</h3> 785 * <p class='bjava'> 786 * <jc>// Parse bean into POJO and then validate that it was parsed correctly.</jc> 787 * MyBean <jv>bean</jv> = <jv>client</jv>.get(<jsf>URI</jsf>) 788 * .run() 789 * .getContent().assertObject(MyBean.<jk>class</jk>).asJson().is(<js>"{foo:'bar'}"</js>) 790 * .getContent().as(MyBean.<jk>class</jk>); 791 * </p> 792 * 793 * 794 * <h2 class='topic'>Custom Call Handlers</h2> 795 * 796 * <p> 797 * The {@link RestCallHandler} interface provides the ability to provide custom handling of requests. 798 * 799 * <ul class='javatree'> 800 * <li class='jc'>{@link Builder} 801 * <ul> 802 * <li class='jm'>{@link Builder#callHandler() callHandler()} 803 * </ul> 804 * <li class='jic'>{@link RestCallHandler} 805 * <ul> 806 * <li class='jm'><c>{@link RestCallHandler#run(HttpHost,HttpRequest,HttpContext) run(HttpHost,HttpRequest,HttpContext)} <jk>returns</jk> HttpResponse</c> 807 * </ul> 808 * </ul> 809 * 810 * <p> 811 * Note that there are other ways of accomplishing this such as extending the {@link RestClient} class and overriding 812 * the {@link #run(HttpHost,HttpRequest,HttpContext)} method 813 * or by defining your own {@link HttpRequestExecutor}. Using this interface is often simpler though. 814 * 815 * 816 * <h2 class='topic'>Interceptors</h2> 817 * 818 * <p> 819 * The {@link RestCallInterceptor} API provides a quick way of intercepting and manipulating requests and responses beyond 820 * the existing {@link HttpRequestInterceptor} and {@link HttpResponseInterceptor} APIs. 821 * 822 * <ul class='javatree'> 823 * <li class='jc'>{@link Builder} 824 * <ul> 825 * <li class='jm'>{@link Builder#interceptors(Object...) interceptors(Object...)} 826 * </ul> 827 * <li class='jc'>{@link RestRequest} 828 * <ul> 829 * <li class='jm'>{@link RestRequest#interceptors(RestCallInterceptor...) interceptors(RestCallInterceptor...)} 830 * </ul> 831 * <li class='jic'>{@link RestCallInterceptor} 832 * <ul> 833 * <li class='jm'>{@link RestCallInterceptor#onInit(RestRequest) onInit(RestRequest)} 834 * <li class='jm'>{@link RestCallInterceptor#onConnect(RestRequest,RestResponse) onConnect(RestRequest,RestResponse)} 835 * <li class='jm'>{@link RestCallInterceptor#onClose(RestRequest,RestResponse) onClose(RestRequest,RestResponse)} 836 * </ul> 837 * </ul> 838 * 839 * 840 * <h2 class='topic'>Logging / Debugging</h2> 841 * 842 * <p> 843 * The following methods provide logging of requests and responses: 844 * 845 * <ul class='javatree'> 846 * <li class='jc'>{@link Builder} 847 * <ul> 848 * <li class='jm'>{@link Builder#logger(Logger) logger(Logger)} 849 * <li class='jm'>{@link Builder#logToConsole() logToConsole()} 850 * <li class='jm'>{@link Builder#logRequests(DetailLevel,Level,BiPredicate) logRequests(DetailLevel,Level,BiPredicate)} 851 * </ul> 852 * </ul> 853 * 854 * <p> 855 * The following example shows the results of logging all requests that end with <c>/bean</c>. 856 * 857 * <h3 class='figure'>Examples:</h3> 858 * <p class='bjava'> 859 * MyBean <jv>bean</jv> = RestClient 860 * .<jsm>create</jsm>() 861 * .json5() 862 * .logRequests(DetailLevel.<jsf>FULL</jsf>, Level.<jsf>SEVERE</jsf>, (<jv>req</jv>,<jv>res</jv>)-><jv>req</jv>.getUri().endsWith(<js>"/bean"</js>)) 863 * .logToConsole() 864 * .build() 865 * .post(<js>"http://localhost/bean"</js>, <jv>anotherBean</jv>) 866 * .run() 867 * .getContent().as(MyBean.<jk>class</jk>); 868 * </p> 869 * 870 * <p> 871 * This produces the following console output: 872 * 873 * <p class='bconsole'> 874 * === HTTP Call (outgoing) ====================================================== 875 * === REQUEST === 876 * POST http://localhost/bean 877 * ---request headers--- 878 * Accept: application/json5 879 * ---request entity--- 880 * Content-Type: application/json5 881 * ---request content--- 882 * {f:1} 883 * === RESPONSE === 884 * HTTP/1.1 200 885 * ---response headers--- 886 * Content-Type: application/json 887 * ---response content--- 888 * {f:1} 889 * === END =======================================================================", 890 * </p> 891 * 892 * 893 * <p class='notes'> 894 * It should be noted that if you enable request logging detail level {@link DetailLevel#FULL}, response bodies will be cached by default which may introduce 895 * a performance penalty. 896 * 897 * <p> 898 * Additionally, the following method is also provided for enabling debug mode: 899 * 900 * <ul class='javatree'> 901 * <li class='jc'>{@link Builder} 902 * <ul> 903 * <li class='jm'>{@link Builder#debug() debug()} 904 * </ul> 905 * </ul> 906 * 907 * <p> 908 * Enabling debug mode has the following effects: 909 * <ul> 910 * <li>{@link org.apache.juneau.marshall.Context.Builder#debug() Context.Builder#debug()} is enabled. 911 * <li>{@link Builder#detectLeaks()} is enabled. 912 * <li>{@link Builder#logToConsole()} is called. 913 * </ul> 914 * 915 * 916 * <h2 class='topic'>REST Proxies</h2> 917 * 918 * <p> 919 * One of the more powerful features of the REST client class is the ability to produce Java interface proxies against 920 * arbitrary remote REST resources. 921 * 922 * <h3 class='figure'>Example:</h3> 923 * <p class='bjava'> 924 * <jc>// Define a Remote proxy for interacting with a REST interface.</jc> 925 * <ja>@Remote</ja>(path=<js>"/petstore"</js>) 926 * <jk>public interface</jk> PetStore { 927 * 928 * <ja>@RemotePost</ja>(<js>"/pets"</js>) 929 * Pet addPet( 930 * <ja>@Content</ja> CreatePet <jv>pet</jv>, 931 * <ja>@Header</ja>(<js>"E-Tag"</js>) UUID <jv>etag</jv>, 932 * <ja>@Query</ja>(<js>"debug"</js>) <jk>boolean</jk> <jv>debug</jv> 933 * ); 934 * } 935 * 936 * <jc>// Use a RestClient with default JSON 5 support.</jc> 937 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().json5().build()) 938 * 939 * PetStore <jv>store</jv> = <jv>client</jv>.getRemote(PetStore.<jk>class</jk>, <js>"http://localhost:10000"</js>); 940 * CreatePet <jv>createPet</jv> = <jk>new</jk> CreatePet(<js>"Fluffy"</js>, 9.99); 941 * Pet <jv>pet</jv> = <jv>store</jv>.addPet(<jv>createPet</jv>, UUID.<jsm>randomUUID</jsm>(), <jk>true</jk>); 942 * </p> 943 * 944 * <p> 945 * The methods to retrieve remote interfaces are: 946 * 947 * <ul class='javatree'> 948 * <li class='jc'>{@link RestClient} 949 * <ul> 950 * <li class='jm'><c>{@link RestClient#getRemote(Class) getRemote(Class<T>)} <jk>returns</jk> T</c> 951 * <li class='jm'><c>{@link RestClient#getRemote(Class,Object) getRemote(Class<T>,Object)} <jk>returns</jk> T</c> 952 * <li class='jm'><c>{@link RestClient#getRemote(Class,Object,Serializer,Parser) getRemote(Class<T>,Object,Serializer,Parser)} <jk>returns</jk> T</c> 953 * <li class='jm'><c>{@link RestClient#getRrpcInterface(Class) getRrpcInterface(Class<T>)} <jk>returns</jk> T</c> 954 * <li class='jm'><c>{@link RestClient#getRrpcInterface(Class,Object) getRrpcInterface(Class<T>,Object)} <jk>returns</jk> T</c> 955 * <li class='jm'><c>{@link RestClient#getRrpcInterface(Class,Object,Serializer,Parser) getRrpcInterface(Class<T>,Object,Serializer,Parser)} <jk>returns</jk> T</c> 956 * </ul> 957 * </ul> 958 * 959 * <p> 960 * Two basic types of remote interfaces are provided: 961 * 962 * <ul class='spaced-list'> 963 * <li>{@link Remote @Remote}-annotated interfaces. These can be defined against arbitrary external REST resources. 964 * <li>RPC-over-REST interfaces. These are Java interfaces that allow you to make method calls on server-side POJOs. 965 * </ul> 966 * 967 * <p> 968 * Refer to the following documentation on both flavors: 969 * 970 * <ul class='doctree'> 971 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestProxies">REST Proxies</a> 972 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestRpc">REST/RPC</a> 973 * </ul> 974 * 975 * <br> 976 * <hr> 977 * <h2 class='topic'>Customizing Apache HttpClient</h2> 978 * 979 * <p> 980 * Several methods are provided for customizing the underlying HTTP client and client builder classes: 981 * <ul class='javatree'> 982 * <li class='jc'>{@link Builder} 983 * <ul> 984 * <li class='jm'>{@link Builder#httpClientBuilder(HttpClientBuilder) httpClientBuilder(HttpClientBuilder)} - Set the client builder yourself. 985 * <li class='jm'>{@link Builder#createHttpClientBuilder() createHttpClientBuilder()} - Override to create the client builder. 986 * <li class='jm'>{@link Builder#createHttpClient() createHttpClient()} - Override to create the client. 987 * <li class='jm'>{@link Builder#createConnectionManager() createConnectionManager()} - Override to create the connection management. 988 * </ul> 989 * </ul> 990 * 991 * <p> 992 * Additionally, all methods on the <c>HttpClientBuilder</c> class have been extended with fluent setters. 993 * 994 * <h3 class='figure'>Example:</h3> 995 * <p class='bjava'> 996 * <jc>// Create a client with customized HttpClient settings.</jc> 997 * MyBean <jv>bean</jv> = RestClient 998 * .<jsm>create</jsm>() 999 * .disableRedirectHandling() 1000 * .connectionManager(<jv>myConnectionManager</jv>) 1001 * .addInterceptorFirst(<jv>myHttpRequestInterceptor</jv>) 1002 * .build(); 1003 * </p> 1004 * 1005 * <p> 1006 * Refer to the {@link HttpClientBuilder HTTP Client Builder API} for more information. 1007 * 1008 * 1009 * <h2 class='topic'>Extending RestClient</h2> 1010 * 1011 * <p> 1012 * The <c>RestClient</c> API has been designed to allow for the ability to be easily extended. 1013 * The following example that overrides the primary run method shows how this can be done. 1014 * 1015 * <h3 class='figure'>Example:</h3> 1016 * <p class='bjava'> 1017 * <jk>public class</jk> MyRestClient <jk>extends</jk> RestClient { 1018 * 1019 * <jc>// Must provide this constructor!</jc> 1020 * <jk>public</jk> MyRestClient(RestClient.Builder<?> <jv>builder</jv>) { 1021 * <jk>super</jk>(<jv>builder</jv>); 1022 * } 1023 * 1024 * <jd>/** Optionally override to customize builder settings before initialization. </jd> 1025 * <ja>@Override</ja> 1026 * <jk>protected void</jk> init(RestClient.Builder<?>) {...} 1027 * 1028 * <jd>/** Optionally override to provide post-initialization (e.g. setting up SAML handshakes, etc...). </jd> 1029 * <ja>@Override</ja> 1030 * <jk>protected void</jk> init() {...} 1031 * 1032 * <jd>/** Optionally override to customize requests when they're created (e.g. add headers to each request). </jd> 1033 * <ja>@Override</ja> 1034 * <jk>protected</jk> RestRequest request(RestOperation) {...} 1035 * 1036 * <jd>/** Optionally override to implement your own call handling. </jd> 1037 * <ja>@Override</ja> 1038 * <jk>protected</jk> HttpResponse run(HttpHost, HttpRequest, HttpContext) {...} 1039 * 1040 * <jd>/** Optionally override to customize requests before they're executed. </jd> 1041 * <ja>@Override</ja> 1042 * <jk>protected void</jk> onCallInit(RestRequest) {...} 1043 * 1044 * <jd>/** Optionally override to customize responses as soon as a connection is made. </jd> 1045 * <ja>@Override</ja> 1046 * <jk>protected void</jk> onCallConnect(RestRequest, RestResponse) {...} 1047 * 1048 * <jd>/** Optionally override to perform any call cleanup. </jd> 1049 * <ja>@Override</ja> 1050 * <jk>protected void</jk> onCallClose(RestRequest, RestResponse) {...} 1051 * } 1052 * 1053 * <jc>// Instantiate your client.</jc> 1054 * MyRestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().json().build(MyRestClient.<jk>class</jk>); 1055 * </p> 1056 * 1057 * <p> 1058 * The {@link RestRequest} and {@link RestResponse} objects can also be extended and integrated by overriding the 1059 * {@link RestClient#createRequest(URI,String,boolean)} and {@link RestClient#createResponse(RestRequest,HttpResponse,Parser)} methods. 1060 * 1061 * <h3 class='section'>Notes:</h3><ul> 1062 * <li class='note'>This class is thread safe and reusable. 1063 * </ul> 1064 * 1065 * <h3 class='section'>See Also:</h3><ul> 1066 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauRestClient">juneau-rest-client-classic</a> 1067 * </ul> 1068 */ 1069@SuppressWarnings({ 1070 "java:S106", // System.err is the intentional default fallback for the configurable console PrintStream 1071 "java:S112", // Builder.interceptors(Class...), executeRemoteWithRetry(), materializeRemote() and throwRemoteError() declare throws Exception because remote-proxy calls surface arbitrary checked exceptions 1072 "java:S115", // Constants use UPPER_snakeCase naming convention 1073 "java:S1133", // Deprecated override required by HttpClient interface 1074 "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants 1075 "java:S3776", // buildRemoteRequest(), executeRemoteWithRetry(), callback() and getRrpcInterface() are branch-heavy remote-call orchestration; splitting them would obscure the flow 1076 "java:S6539", // Monster class; RestClient is intentionally a single fluent builder/client aggregating config, call orchestration, and remote-proxy wiring 1077 "rawtypes", // Raw types necessary for generic type handling. 1078 "resource", // Resource management handled externally 1079 "unchecked" // Casts in getInstance() (Class<? extends Serializer/Parser>) and in the getRemote()/getRrpcInterface() Proxy.newProxyInstance results are guarded by isAssignableFrom checks and the proxied interface type 1080}) 1081public class RestClient extends MarshallingContextable implements HttpClient, Closeable { 1082 1083 // Argument name constants for reqnn 1084 private static final String HEADER_ACCEPT = org.apache.juneau.http.header.Accept.NAME; 1085 private static final String HEADER_CONTENT_TYPE = org.apache.juneau.http.header.ContentType.NAME; 1086 1087 /** 1088 * Builder class. 1089 */ 1090 @SuppressWarnings({ 1091 "java:S119" // 'SELF' (CRTP self-type) is intentional and clearer than a single-letter name. 1092 }) 1093 public abstract static class Builder<SELF extends Builder<SELF>> extends MarshallingContextable.Builder<SELF> { 1094 1095 private BeanInstantiator.Builder<RestCallHandler> callHandler; 1096 private final WritableBeanStore beanStore = new BasicBeanStore(); 1097 private BiPredicate<RestRequest,RestResponse> logRequestsPredicate; 1098 private boolean detectLeaks; 1099 private boolean allowPrivateUrls; 1100 private final List<String> allowedAddressRanges = new ArrayList<>(); 1101 private boolean executorServiceShutdownOnClose; 1102 private boolean ignoreErrors; 1103 private boolean keepHttpClientOpen; 1104 private boolean logToConsole; 1105 private boolean pooled; 1106 private boolean skipEmptyFormData; 1107 private boolean skipEmptyHeaderData; 1108 private boolean skipEmptyQueryData; 1109 private CloseableHttpClient httpClient; 1110 private DetailLevel logRequests; 1111 private ExecutorService executorService; 1112 private HeaderList headerData; 1113 private HttpClientBuilder httpClientBuilder; 1114 private HttpClientConnectionManager connectionManager; 1115 // The instance the default createConnectionManager() last returned; only that one can be given a pinned twin. 1116 private HttpClientConnectionManager defaultConnectionManager; 1117 // The socket-factory registry and pool settings of defaultConnectionManager, which its pinned twin shares. 1118 private Registry<ConnectionSocketFactory> defaultRegistry; 1119 private PoolSettings defaultPoolSettings; 1120 // TLS and pool settings, applied to both pools of the connection manager the default createConnectionManager() 1121 // builds (HttpClientBuilder ignores its own copies once a connection manager is set). 1122 private HostnameVerifier sslHostnameVerifier; 1123 private LayeredConnectionSocketFactory sslSocketFactory; 1124 private SSLContext sslContext; 1125 private int maxConnPerRoute; 1126 private int maxConnTotal; 1127 private ConnectionConfig defaultConnectionConfig; 1128 private SocketConfig defaultSocketConfig; 1129 private PublicSuffixMatcher publicSuffixMatcher; 1130 private long connTimeToLive; 1131 private TimeUnit connTimeToLiveTimeUnit; 1132 private boolean systemProperties; 1133 // Set by the default createHttpClient() to the two-pool router it installed for SSRF-guard-active @Remote calls. 1134 private SsrfGuardConnectionManager ssrfGuard; 1135 // Set by the default createHttpClient(): whether the default createConnectionManager() (not an override, which may 1136 // hand the same instance to several clients) created both of ssrfGuard's pools, which no caller can then reach, 1137 // so the client shuts them down on close() even when the connection manager is shared. 1138 private boolean ownsConnectionManager; 1139 private HttpPartParser.Creator partParser; 1140 private HttpPartSerializer.Creator partSerializer; 1141 private Level logRequestsLevel; 1142 private Logger logger; 1143 private PartList formData; 1144 private PartList pathData; 1145 private PartList queryData; 1146 private ParserSet.Builder parsers; 1147 private Predicate<Integer> errorCodes = x -> x <= 0 || x >= 400; 1148 private PrintStream console; 1149 private SerializerSet.Builder serializers; 1150 private Supplier<String> rootUrl; 1151 private UrlEncodingSerializer.Builder urlEncodingSerializer; 1152 List<RestCallInterceptor> interceptors; 1153 1154 /** 1155 * Constructor. 1156 */ 1157 protected Builder() {} 1158 1159 /** 1160 * Appends an <c>Accept</c> header on this request. 1161 * 1162 * <p> 1163 * This is a shortcut for calling <c>headerData().append(Accept.<jsm>of</jsm>(<jv>value</jv>))</c>. 1164 * 1165 * @param value 1166 * The new header value. 1167 * <br>Can be <jk>null</jk> (no Accept header will be added). 1168 * @return This object. 1169 * @see #headers() 1170 */ 1171 public SELF accept(String value) { 1172 return headers(Accept.of(value)); 1173 } 1174 1175 /** 1176 * Sets the value for the <c>Accept-Charset</c> request header on all requests. 1177 * 1178 * <p> 1179 * This is a shortcut for calling <c>headerData().append(AcceptCharset.<jsm>of</jsm>(<jv>value</jv>))</c>. 1180 * 1181 * @param value The new header value. 1182 * <br>Can be <jk>null</jk> (no Accept-Charset header will be added). 1183 * @return This object. 1184 * @see #headers() 1185 */ 1186 public SELF acceptCharset(String value) { 1187 return headers(AcceptCharset.of(value)); 1188 } 1189 1190 /** 1191 * <i><l>Serializer</l> configuration property: </i> Add <js>"_type"</js> properties when needed. 1192 * 1193 * <p> 1194 * When enabled, <js>"_type"</js> properties will be added to beans if their type cannot be inferred 1195 * through reflection. 1196 * 1197 * <p> 1198 * This is used to recreate the correct objects during parsing if the object types cannot be inferred. 1199 * <br>For example, when serializing a <c>Map<String,Object></c> field where the bean class cannot be determined from 1200 * the type of the values. 1201 * 1202 * <p> 1203 * Note the differences between the following settings: 1204 * <ul class='javatree'> 1205 * <li class='jf'>{@link #addRootType()} - Affects whether <js>'_type'</js> is added to root node. 1206 * <li class='jf'>{@link #addBeanTypes()} - Affects whether <js>'_type'</js> is added to any nodes. 1207 * </ul> 1208 * 1209 * <h4 class='section'>Example:</h4> 1210 * <p class='bjava'> 1211 * <jc>// Create a JSON client that adds _type to nodes in the request body.</jc> 1212 * RestClient <jv>client</jv> = RestClient 1213 * .<jsm>create</jsm>() 1214 * .json() 1215 * .addBeanTypes() 1216 * .build(); 1217 * 1218 * <jc>// Our map of beans to serialize.</jc> 1219 * <ja>@Marshalled</ja>(typeName=<js>"mybean"</js>) 1220 * <jk>public class</jk> MyBean { 1221 * <jk>public</jk> String <jf>foo</jf> = <js>"bar"</js>; 1222 * } 1223 * 1224 * AMap <jv>map</jv> = AMap.of(<js>"foo"</js>, <jk>new</jk> MyBean()); 1225 * 1226 * <jc>// Request body will contain: {"foo":{"_type":"mybean","foo":"bar"}}</jc> 1227 * <jv>client</jv> 1228 * .post(<js>"http://localhost:10000/foo"</js>, <jv>map</jv>) 1229 * .run(); 1230 * </p> 1231 * 1232 * <h4 class='section'>See Also:</h4><ul> 1233 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#addBeanTypes() Serializer.Builder#addBeanTypes()} 1234 * </ul> 1235 * 1236 * @return This object. 1237 */ 1238 public SELF addBeanTypes() { 1239 serializers().forEach(Serializer.Builder::addBeanTypes); 1240 return self(); 1241 } 1242 1243 /** 1244 * Adds this protocol interceptor to the head of the protocol processing list. 1245 * 1246 * <h4 class='section'>Notes:</h4><ul> 1247 * <li class='note'>This value can be overridden by the {@link #httpProcessor(HttpProcessor)} method. 1248 * </ul> 1249 * 1250 * @param itcp New property value. 1251 * <br>Cannot be <jk>null</jk>. 1252 * @return This object. 1253 * @see HttpClientBuilder#addInterceptorFirst(HttpRequestInterceptor) 1254 */ 1255 public SELF addInterceptorFirst(HttpRequestInterceptor itcp) { 1256 httpClientBuilder().addInterceptorFirst(reqnn("itcp", itcp)); 1257 return self(); 1258 } 1259 1260 /** 1261 * Adds this protocol interceptor to the head of the protocol processing list. 1262 * 1263 * <h4 class='section'>Notes:</h4><ul> 1264 * <li class='note'>This value can be overridden by the {@link #httpProcessor(HttpProcessor)} method. 1265 * </ul> 1266 * 1267 * @param itcp New property value. 1268 * <br>Cannot be <jk>null</jk>. 1269 * @return This object. 1270 * @see HttpClientBuilder#addInterceptorFirst(HttpResponseInterceptor) 1271 */ 1272 public SELF addInterceptorFirst(HttpResponseInterceptor itcp) { 1273 httpClientBuilder().addInterceptorFirst(reqnn("itcp", itcp)); 1274 return self(); 1275 } 1276 1277 /** 1278 * Adds this protocol interceptor to the tail of the protocol processing list. 1279 * 1280 * <h4 class='section'>Notes:</h4><ul> 1281 * <li class='note'>This value can be overridden by the {@link #httpProcessor(HttpProcessor)} method. 1282 * </ul> 1283 * 1284 * @param itcp New property value. 1285 * <br>Cannot be <jk>null</jk>. 1286 * @return This object. 1287 * @see HttpClientBuilder#addInterceptorLast(HttpRequestInterceptor) 1288 */ 1289 public SELF addInterceptorLast(HttpRequestInterceptor itcp) { 1290 httpClientBuilder().addInterceptorLast(reqnn("itcp", itcp)); 1291 return self(); 1292 } 1293 1294 /** 1295 * Adds this protocol interceptor to the tail of the protocol processing list. 1296 * 1297 * <h4 class='section'>Notes:</h4><ul> 1298 * <li class='note'>This value can be overridden by the {@link #httpProcessor(HttpProcessor)} method. 1299 * </ul> 1300 * 1301 * @param itcp New property value. 1302 * <br>Cannot be <jk>null</jk>. 1303 * @return This object. 1304 * @see HttpClientBuilder#addInterceptorLast(HttpResponseInterceptor) 1305 */ 1306 public SELF addInterceptorLast(HttpResponseInterceptor itcp) { 1307 httpClientBuilder().addInterceptorLast(reqnn("itcp", itcp)); 1308 return self(); 1309 } 1310 1311 /** 1312 * <i><l>Serializer</l> configuration property: </i> Add type attribute to root nodes. 1313 * 1314 * <p> 1315 * When enabled, <js>"_type"</js> properties will be added to top-level beans. 1316 * 1317 * <p> 1318 * When disabled, it is assumed that the parser knows the exact Java POJO type being parsed, and therefore top-level 1319 * type information that might normally be included to determine the data type will not be serialized. 1320 * 1321 * <p> 1322 * For example, when serializing a top-level POJO with a {@link Marshalled#typeName() @Marshalled(typeName)} value, a 1323 * <js>'_type'</js> attribute will only be added when this setting is enabled. 1324 * 1325 * <p> 1326 * Note the differences between the following settings: 1327 * <ul class='javatree'> 1328 * <li class='jf'>{@link #addRootType()} - Affects whether <js>'_type'</js> is added to root node. 1329 * <li class='jf'>{@link #addBeanTypes()} - Affects whether <js>'_type'</js> is added to any nodes. 1330 * </ul> 1331 * 1332 * <h4 class='section'>Example:</h4> 1333 * <p class='bjava'> 1334 * <jc>// Create a JSON client that adds _type to root node.</jc> 1335 * RestClient <jv>client</jv> = RestClient 1336 * .<jsm>create</jsm>() 1337 * .json() 1338 * .addRootType() 1339 * .build(); 1340 * 1341 * <jc>// Our bean to serialize.</jc> 1342 * <ja>@Marshalled</ja>(typeName=<js>"mybean"</js>) 1343 * <jk>public class</jk> MyBean { 1344 * <jk>public</jk> String <jf>foo</jf> = <js>"bar"</js>; 1345 * } 1346 * 1347 * <jc>// Request body will contain: {"_type":"mybean","foo":"bar"}</jc> 1348 * <jv>client</jv> 1349 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 1350 * .run(); 1351 * </p> 1352 * 1353 * <h4 class='section'>See Also:</h4><ul> 1354 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#addRootType() Serializer.Builder#addRootType()} 1355 * </ul> 1356 * 1357 * @return This object. 1358 */ 1359 public SELF addRootType() { 1360 serializers().forEach(Serializer.Builder::addRootType); 1361 return self(); 1362 } 1363 1364 /** 1365 * Assigns {@link BackoffManager} instance. 1366 * 1367 * @param backoffManager New property value. 1368 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1369 * @return This object. 1370 * @see HttpClientBuilder#setBackoffManager(BackoffManager) 1371 */ 1372 public SELF backoffManager(BackoffManager backoffManager) { 1373 httpClientBuilder().setBackoffManager(backoffManager); 1374 return self(); 1375 } 1376 1377 /** 1378 * Set up this client to use BASIC auth. 1379 * 1380 * <h4 class='section'>Example:</h4> 1381 * <p class='bjava'> 1382 * <jc>// Construct a client that uses BASIC authentication.</jc> 1383 * RestClient <jv>client</jv> = RestClient 1384 * .<jsm>create</jsm>() 1385 * .basicAuth(<js>"http://localhost"</js>, 80, <js>"me"</js>, <js>"mypassword"</js>) 1386 * .build(); 1387 * </p> 1388 * 1389 * @param host The auth scope hostname. 1390 * <br>Can be <jk>null</jk> (will use <js>"*"</js> as the hostname). 1391 * @param port The auth scope port. 1392 * @param user The username. 1393 * <br>Can be <jk>null</jk> (will use empty string). 1394 * @param pw The password. 1395 * <br>Can be <jk>null</jk> (will use empty string). 1396 * @return This object. 1397 */ 1398 public SELF basicAuth(String host, int port, String user, String pw) { 1399 var scope = new AuthScope(host, port); 1400 var up = new UsernamePasswordCredentials(user, pw); 1401 var p = new BasicCredentialsProvider(); 1402 p.setCredentials(scope, up); 1403 defaultCredentialsProvider(p); 1404 return self(); 1405 } 1406 1407 @Override /* Overridden from Context.Builder<?> */ 1408 public RestClient build() { 1409 // Validated here, ahead of the reflective construction, so a bad entry surfaces as the IllegalArgumentException itself. 1410 RemoteUrlPolicy.AllowedRanges.of(allowedAddressRanges.toArray(new String[0])); 1411 return build(RestClient.class); 1412 } 1413 1414 /** 1415 * Returns the creator for the rest call handler. 1416 * 1417 * <p> 1418 * Allows you to provide a custom handler for making HTTP calls. 1419 * 1420 * <h4 class='section'>Example:</h4> 1421 * <p class='bjava'> 1422 * <jc>// Create a client that handles processing of requests using a custom handler.</jc> 1423 * <jk>public class</jk> MyRestCallHandler <jk>implements</jk> RestCallHandler { 1424 * 1425 * <ja>@Override</ja> 1426 * <jk>public</jk> HttpResponse run(HttpHost <jv>target</jv>, HttpRequest <jv>request</jv>, HttpContext <jv>context</jv>) <jk>throws</jk> IOException { 1427 * <jc>// Custom handle requests.</jc> 1428 * } 1429 * } 1430 * 1431 * RestClient <jv>client</jv> = RestClient 1432 * .<jsm>create</jsm>() 1433 * .callHandler(MyRestCallHandler.<jk>class</jk>) 1434 * .build(); 1435 * </p> 1436 * 1437 * <h4 class='section'>Notes:</h4><ul> 1438 * <li class='warn'>The SSRF guard of {@code @Remote} calls travels on the request's {@link HttpContext}, and a 1439 * custom handler may copy the request, or send it with another context, without it. So a client with any handler other than 1440 * {@link BasicRestCallHandler} itself, or with a {@code BasicRestCallHandler} bound to a different client 1441 * (through {@code impl(...)}), refuses every SSRF-guard-active {@code @Remote} call (one without the 1442 * {@link #allowPrivateUrls(boolean) allowPrivateUrls} opt-in). Ordinary requests are unaffected. 1443 * <li class='note'> 1444 * The {@link RestClient#run(HttpHost, HttpRequest, HttpContext)} method can also be overridden to produce the same results. 1445 * The same SSRF restriction applies: a client whose class overrides that method or either 1446 * {@code execute(...)} overload it dispatches to refuses SSRF-guard-active {@code @Remote} calls too. 1447 * <li class='note'> 1448 * Use {@link org.apache.juneau.commons.inject.BeanInstantiator.Builder BeanInstantiator.Builder} <c>impl(Object)</c> to specify an already instantiated instance. 1449 * <li class='note'> 1450 * Use {@link org.apache.juneau.commons.inject.BeanInstantiator.Builder BeanInstantiator.Builder} <c>type(Class)</c> to specify a subtype to instantiate. 1451 * <br>Subclass must have a public constructor that takes in any args available 1452 * in the bean store of this builder (including {@link RestClient} itself). 1453 * </ul> 1454 * 1455 * <h4 class='section'>See Also:</h4><ul> 1456 * <li class='jic'>{@link RestCallHandler} 1457 * </ul> 1458 * 1459 * @return The instantiator for the rest call handler. 1460 */ 1461 public final BeanInstantiator.Builder<RestCallHandler> callHandler() { 1462 if (callHandler == null) 1463 callHandler = createCallHandler(); 1464 return callHandler; 1465 } 1466 1467 /** 1468 * REST call handler class. 1469 * 1470 * <p> 1471 * Specifies a custom handler for making HTTP calls. 1472 * 1473 * <p> 1474 * This is a shortcut for <c>callHandler().type(<jv>value</jv>)</c>. 1475 * 1476 * @param value 1477 * The new value for this setting. 1478 * <br>Cannot be <jk>null</jk>. 1479 * @return This object. 1480 * @see #callHandler() 1481 */ 1482 public SELF callHandler(Class<? extends RestCallHandler> value) { 1483 callHandler().type(reqnn("value", value)); 1484 return self(); 1485 } 1486 1487 /** 1488 * Sets the client version by setting the value for the <js>"Client-Version"</js> header. 1489 * 1490 * <p> 1491 * This is a shortcut for calling <c>headerData().append(ClientVersion.<jsm>of</jsm>(<jv>value</jv>))</c>. 1492 * 1493 * @param value The version string (e.g. <js>"1.2.3"</js>) 1494 * <br>Can be <jk>null</jk> (no Client-Version header will be added). 1495 * @return This object. 1496 * @see #headers() 1497 */ 1498 public SELF clientVersion(String value) { 1499 return headers(ClientVersion.of(value)); 1500 } 1501 1502 /** 1503 * Assigns {@link ConnectionBackoffStrategy} instance. 1504 * 1505 * @param connectionBackoffStrategy New property value. 1506 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1507 * @return This object. 1508 * @see HttpClientBuilder#setConnectionBackoffStrategy(ConnectionBackoffStrategy) 1509 */ 1510 public SELF connectionBackoffStrategy(ConnectionBackoffStrategy connectionBackoffStrategy) { 1511 httpClientBuilder().setConnectionBackoffStrategy(connectionBackoffStrategy); 1512 return self(); 1513 } 1514 1515 /** 1516 * Assigns {@link HttpClientConnectionManager} instance. 1517 * 1518 * <h4 class='section'>Notes:</h4><ul> 1519 * <li class='warn'>This client cannot pin the connections of a connection manager it did not create, so a 1520 * client built with one refuses every SSRF-guard-active {@code @Remote} call (one without the 1521 * {@link #allowPrivateUrls(boolean) allowPrivateUrls} opt-in). Ordinary requests are unaffected. 1522 * </ul> 1523 * 1524 * @param value New property value. 1525 * <br>Can be <jk>null</jk> (value will not be set, a default connection manager will be created). 1526 * @return This object. 1527 * @see HttpClientBuilder#setConnectionManager(HttpClientConnectionManager) 1528 */ 1529 public SELF connectionManager(HttpClientConnectionManager value) { 1530 connectionManager = value; 1531 httpClientBuilder().setConnectionManager(value); 1532 return self(); 1533 } 1534 1535 /** 1536 * Defines the connection manager is to be shared by multiple client instances. 1537 * 1538 * <h4 class='section'>Notes:</h4><ul> 1539 * <li class='note'>If the connection manager is shared its life-cycle is expected to be managed by the caller and it will not be shut down if the client is closed. 1540 * This applies to a connection manager supplied through {@link #connectionManager(HttpClientConnectionManager)} 1541 * or returned by an overridden {@link #createConnectionManager()} (even one that calls {@code super}, since the 1542 * override may hand the same instance to several clients). The connection manager the default 1543 * {@link #createConnectionManager()} builds for a client cannot be reached by the caller, so it is never 1544 * shared: {@link RestClient#close()} shuts it down. 1545 * <li class='note'>The client's internal pool for SSRF-guard-active {@code @Remote} calls (see {@link #createConnectionManager()}) 1546 * is never shared, and {@link RestClient#close()} still shuts it down. Combined with {@link #keepHttpClientOpen()}, 1547 * though, nothing shuts that internal pool (or the default connection manager) down; their connections stay 1548 * open until they are closed as idle or the JVM exits. 1549 * </ul> 1550 * 1551 * @param shared New property value. 1552 * @return This object. 1553 * @see HttpClientBuilder#setConnectionManagerShared(boolean) 1554 */ 1555 public SELF connectionManagerShared(boolean shared) { 1556 httpClientBuilder().setConnectionManagerShared(shared); 1557 return self(); 1558 } 1559 1560 /** 1561 * Assigns {@link ConnectionReuseStrategy} instance. 1562 * 1563 * @param reuseStrategy New property value. 1564 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1565 * @return This object. 1566 * @see HttpClientBuilder#setConnectionReuseStrategy(ConnectionReuseStrategy) 1567 */ 1568 public SELF connectionReuseStrategy(ConnectionReuseStrategy reuseStrategy) { 1569 httpClientBuilder().setConnectionReuseStrategy(reuseStrategy); 1570 return self(); 1571 } 1572 1573 /** 1574 * Sets maximum time to live for persistent connections. 1575 * 1576 * <h4 class='section'>Notes:</h4><ul> 1577 * <li class='note'>It is applied to both pools of the connection manager the default {@link #createConnectionManager()} 1578 * builds. It has no effect on a connection manager supplied through 1579 * {@link #connectionManager(HttpClientConnectionManager)} or an overridden {@link #createConnectionManager()}. 1580 * <li class='note'>A positive value makes that connection manager a {@link PoolingHttpClientConnectionManager}, as 1581 * {@link #pooled()} does: {@link BasicHttpClientConnectionManager} has no time-to-live. 1582 * </ul> 1583 * 1584 * @param connTimeToLive New property value. 1585 * @param connTimeToLiveTimeUnit New property value. 1586 * <br>Cannot be <jk>null</jk>. 1587 * @return This object. 1588 * @see HttpClientBuilder#setConnectionTimeToLive(long,TimeUnit) 1589 */ 1590 public SELF connectionTimeToLive(long connTimeToLive, TimeUnit connTimeToLiveTimeUnit) { 1591 this.connTimeToLive = connTimeToLive; 1592 this.connTimeToLiveTimeUnit = connTimeToLiveTimeUnit; 1593 httpClientBuilder().setConnectionTimeToLive(connTimeToLive, connTimeToLiveTimeUnit); 1594 return self(); 1595 } 1596 1597 /** 1598 * Console print stream 1599 * 1600 * <p> 1601 * Allows you to redirect the console output to a different print stream. 1602 * 1603 * @param value 1604 * The new value for this setting. 1605 * <br>Can be <jk>null</jk> (defaults to <c>System.err</c>). 1606 * @return This object. 1607 */ 1608 public SELF console(PrintStream value) { 1609 console = value; 1610 return self(); 1611 } 1612 1613 /** 1614 * Assigns a map of {@link org.apache.http.client.entity.InputStreamFactory InputStreamFactories} to be used for automatic content decompression. 1615 * 1616 * @param contentDecoderMap New property value. 1617 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1618 * @return This object. 1619 * @see HttpClientBuilder#setContentDecoderRegistry(Map) 1620 */ 1621 public SELF contentDecoderRegistry(Map<String,InputStreamFactory> contentDecoderMap) { 1622 httpClientBuilder().setContentDecoderRegistry(contentDecoderMap); 1623 return self(); 1624 } 1625 1626 /** 1627 * Sets the value for the <c>Content-Type</c> request header on all requests. 1628 * 1629 * <p> 1630 * This is a shortcut for calling <c>headerData().append(ContentType.<jsm>of</jsm>(<jv>value</jv>))</c>. 1631 * 1632 * <p> 1633 * This overrides the media type specified on the serializer. 1634 * 1635 * @param value The new header value. 1636 * <br>Can be <jk>null</jk> (no Content-Type header will be added). 1637 * @return This object. 1638 * @see #headers() 1639 */ 1640 public SELF contentType(String value) { 1641 return headers(ContentType.of(value)); 1642 } 1643 1644 @Override /* Overridden from Context.Builder<?> */ 1645 public SELF copy() { 1646 throw new NoSuchMethodError("Not implemented."); 1647 } 1648 1649 /** 1650 * Sets the value for the <c>Debug</c> request header on all requests. 1651 * 1652 * <p> 1653 * This is a shortcut for calling <c>headerData().append(Debug.<jsm>of</jsm>(<jv>value</jv>))</c>. 1654 * 1655 * @return This object. 1656 * @see #headers() 1657 */ 1658 @Override 1659 public SELF debug() { 1660 super.debug(); 1661 serializers().forEach(Serializer.Builder::debug); 1662 return headers(Debug.TRUE); 1663 } 1664 1665 /** 1666 * <i><l>Parser</l> configuration property: </i> Debug output lines. 1667 * 1668 * <p> 1669 * When parse errors occur, this specifies the number of lines of input before and after the 1670 * error location to be printed as part of the exception message. 1671 * 1672 * <h4 class='section'>Example:</h4> 1673 * <p class='bjava'> 1674 * <jc>// Create a parser whose exceptions print out 100 lines before and after the parse error location.</jc> 1675 * RestClient <jv>client</jv> = RestClient 1676 * .<jsm>create</jsm>() 1677 * .json() 1678 * .debug() <jc>// Enable debug mode to capture Reader contents as strings.</jc> 1679 * .debugOuputLines(100) 1680 * .build(); 1681 * 1682 * <jc>// Try to parse some bad JSON.</jc> 1683 * <jk>try</jk> { 1684 * <jv>client</jv> 1685 * .get(<js>"/pathToBadJson"</js>) 1686 * .run() 1687 * .getContent().as(Object.<jk>class</jk>); <jc>// Try to parse it.</jc> 1688 * } <jk>catch</jk> (RestCallException <jv>e</jv>) { 1689 * System.<jsf>err</jsf>.println(<jv>e</jv>.getMessage()); <jc>// Will display 200 lines of the output.</jc> 1690 * } 1691 * </p> 1692 * 1693 * <h4 class='section'>See Also:</h4><ul> 1694 * <li class='jm'>{@link org.apache.juneau.marshall.parser.Parser.Builder#debugOutputLines(int) Parser.Builder#debugOutputLines(int)} 1695 * </ul> 1696 * 1697 * @param value 1698 * The new value for this property. 1699 * <br>The default value is <c>5</c>. 1700 * @return This object. 1701 */ 1702 public SELF debugOutputLines(int value) { 1703 parsers().forEach(x -> x.debugOutputLines(value)); 1704 return self(); 1705 } 1706 1707 /** 1708 * Assigns default {@link org.apache.http.auth.AuthScheme} registry which will be used for request execution if not explicitly set in the client execution context. 1709 * 1710 * @param authSchemeRegistry New property value. 1711 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1712 * @return This object. 1713 * @see HttpClientBuilder#setDefaultAuthSchemeRegistry(Lookup) 1714 */ 1715 public SELF defaultAuthSchemeRegistry(Lookup<AuthSchemeProvider> authSchemeRegistry) { 1716 httpClientBuilder().setDefaultAuthSchemeRegistry(authSchemeRegistry); 1717 return self(); 1718 } 1719 1720 /** 1721 * Assigns default {@link ConnectionConfig}. 1722 * 1723 * <h4 class='section'>Notes:</h4><ul> 1724 * <li class='note'>It is applied to both pools of the connection manager the default {@link #createConnectionManager()} 1725 * builds. It has no effect on a connection manager supplied through 1726 * {@link #connectionManager(HttpClientConnectionManager)} or an overridden {@link #createConnectionManager()}. 1727 * </ul> 1728 * 1729 * @param config New property value. 1730 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1731 * @return This object. 1732 * @see HttpClientBuilder#setDefaultConnectionConfig(ConnectionConfig) 1733 */ 1734 public SELF defaultConnectionConfig(ConnectionConfig config) { 1735 this.defaultConnectionConfig = config; 1736 httpClientBuilder().setDefaultConnectionConfig(config); 1737 return self(); 1738 } 1739 1740 /** 1741 * Assigns default {@link CookieSpec} registry which will be used for request execution if not explicitly set in the client execution context. 1742 * 1743 * @param cookieSpecRegistry New property value. 1744 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1745 * @return This object. 1746 * @see HttpClientBuilder#setDefaultCookieSpecRegistry(Lookup) 1747 */ 1748 public SELF defaultCookieSpecRegistry(Lookup<CookieSpecProvider> cookieSpecRegistry) { 1749 httpClientBuilder().setDefaultCookieSpecRegistry(cookieSpecRegistry); 1750 return self(); 1751 } 1752 1753 /** 1754 * Assigns default {@link CookieStore} instance which will be used for request execution if not explicitly set in the client execution context. 1755 * 1756 * @param cookieStore New property value. 1757 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1758 * @return This object. 1759 * @see HttpClientBuilder#setDefaultCookieStore(CookieStore) 1760 */ 1761 public SELF defaultCookieStore(CookieStore cookieStore) { 1762 httpClientBuilder().setDefaultCookieStore(cookieStore); 1763 return self(); 1764 } 1765 1766 /** 1767 * Assigns default {@link CredentialsProvider} instance which will be used for request execution if not explicitly set in the client execution context. 1768 * 1769 * @param credentialsProvider New property value. 1770 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1771 * @return This object. 1772 * @see HttpClientBuilder#setDefaultCredentialsProvider(CredentialsProvider) 1773 */ 1774 public SELF defaultCredentialsProvider(CredentialsProvider credentialsProvider) { 1775 httpClientBuilder().setDefaultCredentialsProvider(credentialsProvider); 1776 return self(); 1777 } 1778 1779 /** 1780 * Assigns default {@link RequestConfig} instance which will be used for request execution if not explicitly set in the client execution context. 1781 * 1782 * @param config New property value. 1783 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1784 * @return This object. 1785 * @see HttpClientBuilder#setDefaultRequestConfig(RequestConfig) 1786 */ 1787 public SELF defaultRequestConfig(RequestConfig config) { 1788 httpClientBuilder().setDefaultRequestConfig(config); 1789 return self(); 1790 } 1791 1792 /** 1793 * Assigns default {@link SocketConfig}. 1794 * 1795 * <h4 class='section'>Notes:</h4><ul> 1796 * <li class='note'>It is applied to both pools of the connection manager the default {@link #createConnectionManager()} 1797 * builds. It has no effect on a connection manager supplied through 1798 * {@link #connectionManager(HttpClientConnectionManager)} or an overridden {@link #createConnectionManager()}. 1799 * </ul> 1800 * 1801 * @param config New property value. 1802 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 1803 * @return This object. 1804 * @see HttpClientBuilder#setDefaultSocketConfig(SocketConfig) 1805 */ 1806 public SELF defaultSocketConfig(SocketConfig config) { 1807 this.defaultSocketConfig = config; 1808 httpClientBuilder().setDefaultSocketConfig(config); 1809 return self(); 1810 } 1811 1812 /** 1813 * <i><l>RestClient</l> configuration property: </i> Enable leak detection. 1814 * 1815 * <p> 1816 * Enable client and request/response leak detection. 1817 * 1818 * <p> 1819 * Causes messages to be logged to the console if clients or request/response objects are not properly closed 1820 * when the <c>finalize</c> methods are invoked. 1821 * 1822 * <p> 1823 * Automatically enabled with {@link org.apache.juneau.marshall.Context.Builder#debug() Context.Builder#debug()}. 1824 * 1825 * <h4 class='section'>Example:</h4> 1826 * <p class='bjava'> 1827 * <jc>// Create a client that logs a message if </jc> 1828 * RestClient <jv>client</jv> = RestClient 1829 * .<jsm>create</jsm>() 1830 * .detectLeaks() 1831 * .logToConsole() <jc>// Also log the error message to System.err</jc> 1832 * .build(); 1833 * 1834 * <jv>client</jv>.closeQuietly(); <jc>// Customized HttpClient won't be closed.</jc> 1835 * </p> 1836 * 1837 * @return This object. 1838 */ 1839 public SELF detectLeaks() { 1840 detectLeaks = true; 1841 return self(); 1842 } 1843 1844 /** 1845 * Opts every {@code @Remote}/{@code @Url} call made through this client out of the default deny-private SSRF 1846 * guardrail (see {@code org.apache.juneau.http.remote.RemoteUrlPolicy}), for local-dev/intranet targets that 1847 * are intentionally private. 1848 * 1849 * <p> 1850 * The effective per-call value is the logical OR of this setting, the 1851 * {@code RestClient.allowPrivateUrls} system property, and the {@code @Remote}/{@code @RemoteOp} 1852 * {@code allowPrivateUrls} annotation attribute: any one of the three opting in is sufficient. The {@code http}/ 1853 * {@code https} scheme requirement is unaffected. 1854 * 1855 * @param value {@code true} to allow private/loopback/link-local/metadata {@code @Remote} targets. Default {@code false}. 1856 * @return This object. 1857 */ 1858 public SELF allowPrivateUrls(boolean value) { 1859 allowPrivateUrls = value; 1860 return self(); 1861 } 1862 1863 /** 1864 * Allows this client's SSRF-guarded {@code @Remote}/{@code @Url} calls to reach hosts inside the given 1865 * special-purpose address ranges that the default policy denies (see {@code org.apache.juneau.http.remote.RemoteUrlPolicy}). 1866 * 1867 * <p> 1868 * Same narrow semantics and validation as the JVM-wide {@code RestClient.allowAddressRanges} system property: each 1869 * entry is a CIDR range or single address (parsed without DNS) that must lie inside {@code 192.0.0.0/24}, 1870 * {@code 198.18.0.0/15}, {@code 224.0.0.0/4}, {@code 240.0.0.0/4} or {@code ff00::/8}. It never re-opens 1871 * loopback, link-local/cloud-metadata, private, unspecified or any other deny. 1872 * 1873 * <p> 1874 * The effective allow-list is the union of this setting and the system property. Repeated calls accumulate. 1875 * An invalid entry fails {@link #build()} with an {@link IllegalArgumentException}. 1876 * 1877 * @param value The CIDR ranges or addresses to allow. Can be <jk>null</jk> or empty (no effect). 1878 * @return This object. 1879 */ 1880 public SELF allowAddressRanges(String...value) { 1881 if (nn(value)) 1882 Collections.addAll(allowedAddressRanges, value); 1883 return self(); 1884 } 1885 1886 /** 1887 * <i><l>BeanTraverse</l> configuration property: </i> Automatically detect POJO recursions. 1888 * 1889 * <p> 1890 * When enabled, specifies that recursions should be checked for during traversal. 1891 * 1892 * <p> 1893 * Recursions can occur when traversing models that aren't true trees but rather contain loops. 1894 * <br>In general, unchecked recursions cause stack-overflow-errors. 1895 * <br>These show up as {@link MarshallingRecursionException MarshallingRecursionException} with the message <js>"Depth too deep. Stack overflow occurred."</js>. 1896 * 1897 * <h4 class='section'>Notes:</h4><ul> 1898 * <li class='note'> 1899 * Checking for recursion can cause a small performance penalty. 1900 * </ul> 1901 * 1902 * <h4 class='section'>Example:</h4> 1903 * <p class='bjava'> 1904 * <jc>// Create a JSON client that automatically checks for recursions.</jc> 1905 * RestClient <jv>client</jv> = RestClient 1906 * .<jsm>create</jsm>() 1907 * .json() 1908 * .detectRecursions() 1909 * .build(); 1910 * 1911 * <jc>// Create a POJO model with a recursive loop.</jc> 1912 * <jk>public class</jk> A { 1913 * <jk>public</jk> Object <jf>f</jf>; 1914 * } 1915 * A <jv>a</jv> = <jk>new</jk> A(); 1916 * <jv>a</jv>.<jf>f</jf> = <jv>a</jv>; 1917 * 1918 * <jk>try</jk> { 1919 * <jc>// Throws a RestCallException with an inner SerializeException and not a StackOverflowError</jc> 1920 * <jv>client</jv> 1921 * .post(<js>"http://localhost:10000/foo"</js>, <jv>a</jv>) 1922 * .run(); 1923 * } <jk>catch</jk> (RestCallException <jv>e</jv>} { 1924 * <jc>// Handle exception.</jc> 1925 * } 1926 * </p> 1927 * 1928 * <h4 class='section'>See Also:</h4><ul> 1929 * <li class='jm'>{@link org.apache.juneau.marshall.MarshallingTraverseContext.Builder#detectRecursions() MarshallingTraverseContext.Builder#detectRecursions()} 1930 * </ul> 1931 * 1932 * @return This object. 1933 */ 1934 public SELF detectRecursions() { 1935 serializers().forEach(Serializer.Builder::detectRecursions); 1936 return self(); 1937 } 1938 1939 /** 1940 * Disables authentication scheme caching. 1941 * 1942 * <h4 class='section'>Notes:</h4><ul> 1943 * <li class='note'>This value can be overridden by the {@link #httpProcessor(HttpProcessor)} method. 1944 * </ul> 1945 * 1946 * @return This object. 1947 * @see HttpClientBuilder#disableAuthCaching() 1948 */ 1949 public SELF disableAuthCaching() { 1950 httpClientBuilder().disableAuthCaching(); 1951 return self(); 1952 } 1953 1954 /** 1955 * Disables automatic request recovery and re-execution. 1956 * 1957 * @return This object. 1958 * @see HttpClientBuilder#disableAutomaticRetries() 1959 */ 1960 public SELF disableAutomaticRetries() { 1961 httpClientBuilder().disableAutomaticRetries(); 1962 return self(); 1963 } 1964 1965 /** 1966 * Disables connection state tracking. 1967 * 1968 * @return This object. 1969 * @see HttpClientBuilder#disableConnectionState() 1970 */ 1971 public SELF disableConnectionState() { 1972 httpClientBuilder().disableConnectionState(); 1973 return self(); 1974 } 1975 1976 /** 1977 * Disables automatic content decompression. 1978 * 1979 * <h4 class='section'>Notes:</h4><ul> 1980 * <li class='note'>This value can be overridden by the {@link #httpProcessor(HttpProcessor)} method. 1981 * </ul> 1982 * 1983 * @return This object. 1984 * @see HttpClientBuilder#disableContentCompression() 1985 */ 1986 public SELF disableContentCompression() { 1987 httpClientBuilder().disableContentCompression(); 1988 return self(); 1989 } 1990 1991 /** 1992 * Disables state (cookie) management. 1993 * 1994 * <h4 class='section'>Notes:</h4><ul> 1995 * <li class='note'>This value can be overridden by the {@link #httpProcessor(HttpProcessor)} method. 1996 * </ul> 1997 * 1998 * @return This object. 1999 * @see HttpClientBuilder#disableCookieManagement() 2000 */ 2001 public SELF disableCookieManagement() { 2002 httpClientBuilder().disableCookieManagement(); 2003 return self(); 2004 } 2005 2006 /** 2007 * Disables automatic redirect handling. 2008 * 2009 * @return This object. 2010 * @see HttpClientBuilder#disableRedirectHandling() 2011 */ 2012 public SELF disableRedirectHandling() { 2013 httpClientBuilder().disableRedirectHandling(); 2014 return self(); 2015 } 2016 2017 /** 2018 * Errors codes predicate. 2019 * 2020 * <p> 2021 * Defines a predicate to test for error codes. 2022 * 2023 * <h4 class='section'>Example:</h4> 2024 * <p class='bjava'> 2025 * <jc>// Create a client that considers any 300+ responses to be errors.</jc> 2026 * RestClient <jv>client</jv> = RestClient 2027 * .<jsm>create</jsm>() 2028 * .errorCodes(<jv>x</jv> -> <jv>x</jv>>=300) 2029 * .build(); 2030 * </p> 2031 * 2032 * @param value 2033 * The new value for this setting. 2034 * <br>The default value is <code>x -> x >= 400</code>. 2035 * <br>Cannot be <jk>null</jk>. 2036 * @return This object. 2037 */ 2038 public SELF errorCodes(Predicate<Integer> value) { 2039 errorCodes = reqnn("value", value); 2040 return self(); 2041 } 2042 2043 /** 2044 * Makes this instance of {@link HttpClient} proactively evict expired connections from the connection pool using a background thread. 2045 * 2046 * <h4 class='section'>Notes:</h4><ul> 2047 * <li class='note'>One MUST explicitly close HttpClient with {@link CloseableHttpClient#close()} in order to stop and release the background thread. 2048 * <li class='note'>This method has no effect if the instance of {@link HttpClient} is configured to use a shared connection manager. 2049 * <li class='note'>This method may not be used when the instance of {@link HttpClient} is created inside an EJB container. 2050 * </ul> 2051 * 2052 * @return This object. 2053 * @see HttpClientBuilder#evictExpiredConnections() 2054 */ 2055 public SELF evictExpiredConnections() { 2056 httpClientBuilder().evictExpiredConnections(); 2057 return self(); 2058 } 2059 2060 /** 2061 * Makes this instance of {@link HttpClient} proactively evict idle connections from the connection pool using a background thread. 2062 * 2063 * <h4 class='section'>Notes:</h4><ul> 2064 * <li class='note'>One MUST explicitly close HttpClient with {@link CloseableHttpClient#close()} in order to stop and release the background thread. 2065 * <li class='note'>This method has no effect if the instance of {@link HttpClient} is configured to use a shared connection manager. 2066 * <li class='note'>This method may not be used when the instance of {@link HttpClient} is created inside an EJB container. 2067 * </ul> 2068 * 2069 * @param maxIdleTime New property value. 2070 * @param maxIdleTimeUnit New property value. 2071 * <br>Cannot be <jk>null</jk>. 2072 * @return This object. 2073 * @see HttpClientBuilder#evictIdleConnections(long,TimeUnit) 2074 */ 2075 public SELF evictIdleConnections(long maxIdleTime, TimeUnit maxIdleTimeUnit) { 2076 httpClientBuilder().evictIdleConnections(maxIdleTime, maxIdleTimeUnit); 2077 return self(); 2078 } 2079 2080 /** 2081 * <i><l>RestClient</l> configuration property: </i> Executor service. 2082 * 2083 * <p> 2084 * Defines the executor service to use when calling future methods on the {@link RestRequest} class. 2085 * 2086 * <p> 2087 * This executor service is used to create {@link Future} objects on the following methods: 2088 * <ul> 2089 * <li class='jm'>{@link RestRequest#runFuture()} 2090 * <li class='jm'>{@link RestRequest#completeFuture()} 2091 * <li class='jm'>{@link ResponseContent#asFuture(Class)} (and similar methods) 2092 * </ul> 2093 * 2094 * <p> 2095 * The default executor service is a single-threaded {@link ThreadPoolExecutor} with a 30 second timeout 2096 * and a queue size of 10. 2097 * 2098 * <h4 class='section'>Example:</h4> 2099 * <p class='bjava'> 2100 * <jc>// Create a client with a customized executor service.</jc> 2101 * RestClient <jv>client</jv> = RestClient 2102 * .<jsm>create</jsm>() 2103 * .executorService(<jk>new</jk> ThreadPoolExecutor(1, 1, 30, TimeUnit.<jsf>SECONDS</jsf>, <jk>new</jk> ArrayBlockingQueue<Runnable>(10)), <jk>true</jk>) 2104 * .build(); 2105 * 2106 * <jc>// Use it to asynchronously run a request.</jc> 2107 * Future<RestResponse> <jv>responseFuture</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).runFuture(); 2108 * 2109 * <jc>// Do some other stuff.</jc> 2110 * 2111 * <jc>// Now read the response.</jc> 2112 * String <jv>body</jv> = <jv>responseFuture</jv>.get().getContent().asString(); 2113 * 2114 * <jc>// Use it to asynchronously retrieve a response.</jc> 2115 * Future<MyBean> <jv>myBeanFuture</jv> = <jv>client</jv> 2116 * .get(<jsf>URI</jsf>) 2117 * .run() 2118 * .getContent().asFuture(MyBean.<jk>class</jk>); 2119 * 2120 * <jc>// Do some other stuff.</jc> 2121 * 2122 * <jc>// Now read the response.</jc> 2123 * MyBean <jv>bean</jv> = <jv>myBeanFuture</jv>.get(); 2124 * </p> 2125 * 2126 * @param executorService The executor service. 2127 * <br>Can be <jk>null</jk> (a default executor service will be created if needed). 2128 * @param shutdownOnClose Call {@link ExecutorService#shutdown()} when {@link RestClient#close()} is called. 2129 * @return This object. 2130 */ 2131 public SELF executorService(ExecutorService executorService, boolean shutdownOnClose) { 2132 this.executorService = executorService; 2133 this.executorServiceShutdownOnClose = shutdownOnClose; 2134 return self(); 2135 } 2136 2137 /** 2138 * Returns the builder for the list of form data parameters that get applied to all requests created by this builder. 2139 * 2140 * <p> 2141 * This is the primary method for accessing the form data parameter list. 2142 * On first call, the builder is created via the method {@link #createFormData()}. 2143 * 2144 * <h4 class='section'>Example:</h4> 2145 * <p class='bjava'> 2146 * <jc>// Create a client that adds a "foo=bar" form-data parameter on every request.</jc> 2147 * RestClient.Builder<?> <jv>builder</jv> = RestClient.<jsm>create</jsm>(); 2148 * <jv>builder</jv>.formData().setDefault(<js>"foo"</js>, <js>"bar"</js>)); 2149 * RestClient <jv>client</jv> = <jv>builder</jv>.build(); 2150 * </p> 2151 * 2152 * <p> 2153 * The following convenience methods are also provided for updating the parameters: 2154 * <ul> 2155 * <li class='jm'>{@link #formData(NameValuePair...)} 2156 * <li class='jm'>{@link #formDataDefault(NameValuePair...)} 2157 * <li class='jm'>{@link #formData(String,String)} 2158 * <li class='jm'>{@link #formData(String,Supplier)} 2159 * </ul> 2160 * 2161 * @return The form data list builder. 2162 */ 2163 public final PartList formData() { 2164 if (formData == null) 2165 formData = createFormData(); 2166 return formData; 2167 } 2168 2169 /** 2170 * Appends multiple form-data parameters to the request bodies of all URL-encoded form posts. 2171 * 2172 * <h4 class='section'>Example:</h4> 2173 * <p class='bjava'> 2174 * <jk>import static</jk> org.apache.juneau.http.HttpParts.*; 2175 * 2176 * RestClient <jv>client</jv> = RestClient 2177 * .<jsm>create</jsm>() 2178 * .formData( 2179 * <jsm>stringPart</jsm>(<js>"foo"</js>, <js>"bar"</js>), 2180 * <jsm>booleanPart</jsm>(<js>"baz"</js>, <jk>true</jk>) 2181 * ) 2182 * .build(); 2183 * </p> 2184 * 2185 * <p> 2186 * This is a shortcut for calling <c>formData().append(<jv>parts</jv>)</c>. 2187 * 2188 * @param parts 2189 * The form-data parameters. 2190 * <br>Can contain <jk>null</jk> values (ignored). 2191 * @return This object. 2192 * @see #formData() 2193 */ 2194 public SELF formData(NameValuePair...parts) { 2195 formData().append(parts); 2196 return self(); 2197 } 2198 2199 /** 2200 * Appends a form-data parameter to all request bodies. 2201 * 2202 * <h4 class='section'>Example:</h4> 2203 * <p class='bjava'> 2204 * RestClient <jv>client</jv> = RestClient 2205 * .<jsm>create</jsm>() 2206 * .formData(<js>"foo"</js>, <js>"bar"</js>) 2207 * .build(); 2208 * </p> 2209 * 2210 * <p> 2211 * This is a shortcut for calling <c>formData().append(<jv>name</jv>,<jv>value</jv>)</c>. 2212 * 2213 * @param name The parameter name. 2214 * <br>Cannot be <jk>null</jk>. 2215 * @param value The parameter value. 2216 * <br>Can be <jk>null</jk> (null value will be serialized). 2217 * @return This object. 2218 * @see #formData() 2219 */ 2220 public SELF formData(String name, String value) { 2221 formData().append(name, value); 2222 return self(); 2223 } 2224 2225 /** 2226 * Appends a form-data parameter with a dynamic value to all request bodies. 2227 * 2228 * <h4 class='section'>Example:</h4> 2229 * <p class='bjava'> 2230 * RestClient <jv>client</jv> = RestClient 2231 * .<jsm>create</jsm>() 2232 * .formData(<js>"foo"</js>, ()-><js>"bar"</js>) 2233 * .build(); 2234 * </p> 2235 * 2236 * <p> 2237 * This is a shortcut for calling <c>formData().append(<jv>name</jv>,<jv>value</jv>)</c>. 2238 * 2239 * @param name The parameter name. 2240 * <br>Cannot be <jk>null</jk>. 2241 * @param value The parameter value supplier. 2242 * <br>Can be <jk>null</jk> (null value will be serialized). 2243 * @return This object. 2244 * @see #formData() 2245 */ 2246 public SELF formData(String name, Supplier<String> value) { 2247 formData().append(name, value); 2248 return self(); 2249 } 2250 2251 /** 2252 * Sets default form-data parameter values. 2253 * 2254 * <p> 2255 * Uses default values for specified parameters if not otherwise specified on the outgoing requests. 2256 * 2257 * <h4 class='section'>Example:</h4> 2258 * <p class='bjava'> 2259 * RestClient <jv>client</jv> = RestClient 2260 * .<jsm>create</jsm>() 2261 * .formDataDefault(<jsm>stringPart</jsm>(<js>"foo"</js>, ()-><js>"bar"</js>)); 2262 * .build(); 2263 * </p> 2264 * 2265 * <p> 2266 * This is a shortcut for calling <c>formData().setDefault(<jv>parts</jv>)</c>. 2267 * 2268 * @param parts The parts. 2269 * <br>Can contain <jk>null</jk> values (ignored). 2270 * @return This object. 2271 * @see #formData() 2272 */ 2273 public SELF formDataDefault(NameValuePair...parts) { 2274 formData().setDefault(parts); 2275 return self(); 2276 } 2277 2278 /** 2279 * Returns the root URI defined for this client. 2280 * 2281 * <p> 2282 * Returns <jk>null</jk> in lieu of an empty string. 2283 * Trailing slashes are trimmed. 2284 * 2285 * @return The root URI defined for this client. 2286 */ 2287 public String getRootUri() { return rootUrl != null ? rootUrl.get() : null; } 2288 2289 /** 2290 * Returns the root URL supplier set on this builder. 2291 * 2292 * @return The root URL supplier, or <jk>null</jk> if not set. 2293 */ 2294 public Supplier<String> getRootUrlSupplier() { return rootUrl; } 2295 2296 /** 2297 * Appends a header to all requests. 2298 * 2299 * <h4 class='section'>Example:</h4> 2300 * <p class='bjava'> 2301 * RestClient <jv>client</jv> = RestClient 2302 * .<jsm>create</jsm>() 2303 * .header(<js>"Foo"</js>, <js>"bar"</js>); 2304 * .build(); 2305 * </p> 2306 * 2307 * <p> 2308 * This is a shortcut for calling <c>headerData().append(<jv>name</jv>,<jv>value</jv>)</c>. 2309 * 2310 * @param name The header name. 2311 * <br>Cannot be <jk>null</jk>. 2312 * @param value The header value. 2313 * <br>Can be <jk>null</jk> (null value will be serialized). 2314 * @return This object. 2315 * @see #headers() 2316 */ 2317 public SELF header(String name, String value) { 2318 headers().append(name, value); 2319 return self(); 2320 } 2321 2322 /** 2323 * Appends a header to all requests using a dynamic value. 2324 * 2325 * <h4 class='section'>Example:</h4> 2326 * <p class='bjava'> 2327 * RestClient <jv>client</jv> = RestClient 2328 * .<jsm>create</jsm>() 2329 * .header(<js>"Foo"</js>, ()-><js>"bar"</js>); 2330 * .build(); 2331 * </p> 2332 * 2333 * <p> 2334 * This is a shortcut for calling <c>headerData().append(<jv>name</jv>,<jv>value</jv>)</c>. 2335 * 2336 * @param name The header name. 2337 * <br>Cannot be <jk>null</jk>. 2338 * @param value The header value supplier. 2339 * <br>Can be <jk>null</jk> (null value will be serialized). 2340 * @return This object. 2341 * @see #headers() 2342 */ 2343 public SELF header(String name, Supplier<String> value) { 2344 headers().append(name, value); 2345 return self(); 2346 } 2347 2348 /** 2349 * Returns the builder for the list of headers that get applied to all requests created by this builder. 2350 * 2351 * <p> 2352 * This is the primary method for accessing the request header list. 2353 * On first call, the builder is created via the method {@link #createHeaderData()}. 2354 * 2355 * <h4 class='section'>Example:</h4> 2356 * <p class='bjava'> 2357 * <jc>// Create a client that adds a "Foo: bar" header on every request.</jc> 2358 * RestClient.Builder<?> <jv>builder</jv> = RestClient.<jsm>create</jsm>(); 2359 * <jv>builder</jv>.headerData().setDefault(<js>"Foo"</js>, <js>"bar"</js>)); 2360 * RestClient <jv>client</jv> = <jv>builder</jv>.build(); 2361 * </p> 2362 * 2363 * <p> 2364 * The following convenience methods are also provided for updating the headers: 2365 * <ul> 2366 * <li class='jm'>{@link #headers(Header...)} 2367 * <li class='jm'>{@link #headersDefault(Header...)} 2368 * <li class='jm'>{@link #header(String,String)} 2369 * <li class='jm'>{@link #header(String,Supplier)} 2370 * <li class='jm'>{@link #mediaType(String)} 2371 * <li class='jm'>{@link #mediaType(MediaType)} 2372 * <li class='jm'>{@link #accept(String)} 2373 * <li class='jm'>{@link #acceptCharset(String)} 2374 * <li class='jm'>{@link #clientVersion(String)} 2375 * <li class='jm'>{@link #contentType(String)} 2376 * <li class='jm'>{@link #debug()} 2377 * <li class='jm'>{@link #noTrace()} 2378 * </ul> 2379 * 2380 * @return The header list builder. 2381 */ 2382 public final HeaderList headers() { 2383 if (headerData == null) 2384 headerData = createHeaderData(); 2385 return headerData; 2386 } 2387 2388 /** 2389 * Appends multiple headers to all requests. 2390 * 2391 * <h4 class='section'>Example:</h4> 2392 * <p class='bjava'> 2393 * <jk>import static</jk> org.apache.juneau.http.HttpHeaders.*; 2394 * 2395 * RestClient <jv>client</jv> = RestClient 2396 * .<jsm>create</jsm>() 2397 * .headers( 2398 * <jsf>ACCEPT_TEXT_XML</jsf>, 2399 * <jsm>stringHeader</jsm>(<js>"Foo"</js>, <js>"bar"</js>) 2400 * ) 2401 * .build(); 2402 * </p> 2403 * 2404 * <p> 2405 * This is a shortcut for calling <c>headerData().append(<jv>parts</jv>)</c>. 2406 * 2407 * @param parts 2408 * The header to set. 2409 * <br>Can contain <jk>null</jk> values (ignored). 2410 * @return This object. 2411 * @see #headers() 2412 */ 2413 public SELF headers(Header...parts) { 2414 headers().append(parts); 2415 return self(); 2416 } 2417 2418 /** 2419 * Sets default header values. 2420 * 2421 * <p> 2422 * Uses default values for specified headers if not otherwise specified on the outgoing requests. 2423 * 2424 * <h4 class='section'>Example:</h4> 2425 * <p class='bjava'> 2426 * RestClient <jv>client</jv> = RestClient 2427 * .<jsm>create</jsm>() 2428 * .headersDefault(<jsm>stringHeader</jsm>(<js>"Foo"</js>, ()-><js>"bar"</js>)); 2429 * .build(); 2430 * </p> 2431 * 2432 * <p> 2433 * This is a shortcut for calling <c>headerData().setDefault(<jv>parts</jv>)</c>. 2434 * 2435 * @param parts The header values. 2436 * <br>Can contain <jk>null</jk> values (ignored). 2437 * @return This object. 2438 * @see #headers() 2439 */ 2440 public SELF headersDefault(Header...parts) { 2441 headers().setDefault(parts); 2442 return self(); 2443 } 2444 2445 /** 2446 * Sets a default request header with serializer session options (JSON5 map) for all requests. 2447 * 2448 * <p> 2449 * This is a shortcut for <c>headersDefault(basicHeader({@link RestSharedConstants#HEADER_JuneauSerializerOptions}, <jv>json5</jv>))</c>. 2450 * 2451 * @param json5 2452 * Serializer session options in JSON5 form. 2453 * <br>Can be <jk>null</jk> (default is not set by this method). 2454 * @return This object. 2455 */ 2456 public SELF serializerSessionOptionsHeader(String json5) { 2457 if (json5 != null) 2458 headersDefault(basicHeader(HEADER_JuneauSerializerOptions, json5)); 2459 return self(); 2460 } 2461 2462 /** 2463 * Sets a default request header with parser session options (JSON5 map) for all requests. 2464 * 2465 * <p> 2466 * This is a shortcut for <c>headersDefault(basicHeader({@link RestSharedConstants#HEADER_JuneauParserOptions}, <jv>json5</jv>))</c>. 2467 * 2468 * @param json5 2469 * Parser session options in JSON5 form. 2470 * <br>Can be <jk>null</jk> (default is not set by this method). 2471 * @return This object. 2472 */ 2473 public SELF parserSessionOptionsHeader(String json5) { 2474 if (json5 != null) 2475 headersDefault(basicHeader(HEADER_JuneauParserOptions, json5)); 2476 return self(); 2477 } 2478 2479 /** 2480 * Convenience for {@link #serializerSessionOptionsHeader(String)} using a map serialized with JSON5. 2481 * 2482 * @param properties 2483 * Property names and values for serializer session options. 2484 * <br>Can be <jk>null</jk> (treated as an empty map). 2485 * @return This object. 2486 */ 2487 public SELF serializerSessionOptionsHeader(Map<String,?> properties) { 2488 try { 2489 return serializerSessionOptionsHeader(isEmpty(properties) ? null : Json5.of(properties)); 2490 } catch (SerializeException e) { 2491 throw rex(e, "Could not serialize serializer session options header"); 2492 } 2493 } 2494 2495 /** 2496 * Convenience for {@link #parserSessionOptionsHeader(String)} using a map serialized with JSON5. 2497 * 2498 * @param properties 2499 * Property names and values for parser session options. 2500 * <br>Can be <jk>null</jk> (treated as an empty map). 2501 * @return This object. 2502 */ 2503 public SELF parserSessionOptionsHeader(Map<String,?> properties) { 2504 try { 2505 return parserSessionOptionsHeader(isEmpty(properties) ? null : Json5.of(properties)); 2506 } catch (SerializeException e) { 2507 throw rex(e, "Could not serialize parser session options header"); 2508 } 2509 } 2510 2511 /** 2512 * Convenience method for specifying HTML as the marshalling transmission media type. 2513 * 2514 * <p> 2515 * POJOs are converted to HTML without any sort of doc wrappers. 2516 * 2517 * <p> 2518 * {@link HtmlSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 2519 * <ul> 2520 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 2521 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 2522 * </ul> 2523 * <p> 2524 * {@link HtmlParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 2525 * <ul> 2526 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 2527 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 2528 * </ul> 2529 * <p> 2530 * <c>Accept</c> request header will be set to <js>"text/html"</js> unless overridden 2531 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 2532 * <p> 2533 * <c>Content-Type</c> request header will be set to <js>"text/html"</js> unless overridden 2534 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 2535 * <p> 2536 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 2537 * <ul> 2538 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 2539 * last-enabled language if the headers are not set. 2540 * </ul> 2541 * <p> 2542 * Identical to calling <c>serializer(HtmlSerializer.<jk>class</jk>).parser(HtmlParser.<jk>class</jk>)</c>. 2543 * 2544 * <h4 class='section'>Example:</h4> 2545 * <p class='bjava'> 2546 * <jc>// Construct a client that uses HTML marshalling.</jc> 2547 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().html().build(); 2548 * </p> 2549 * 2550 * @return This object. 2551 */ 2552 public SELF html() { 2553 return serializer(HtmlSerializer.class).parser(HtmlParser.class); 2554 } 2555 2556 /** 2557 * Convenience method for specifying HTML DOC as the marshalling transmission media type. 2558 * 2559 * <p> 2560 * POJOs are converted to fully renderable HTML pages. 2561 * 2562 * <p> 2563 * {@link HtmlDocSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 2564 * <ul> 2565 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()} or 2566 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 2567 * </ul> 2568 * <p> 2569 * {@link HtmlParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 2570 * <ul> 2571 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 2572 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 2573 * </ul> 2574 * <p> 2575 * <c>Accept</c> request header will be set to <js>"text/html"</js> unless overridden 2576 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 2577 * <p> 2578 * <c>Content-Type</c> request header will be set to <js>"text/html"</js> unless overridden 2579 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 2580 * <p> 2581 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 2582 * <ul> 2583 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 2584 * last-enabled language if the headers are not set. 2585 * </ul> 2586 * <p> 2587 * Identical to calling <c>serializer(HtmlDocSerializer.<jk>class</jk>).parser(HtmlParser.<jk>class</jk>)</c>. 2588 * 2589 * <h4 class='section'>Example:</h4> 2590 * <p class='bjava'> 2591 * <jc>// Construct a client that uses HTML Doc marshalling.</jc> 2592 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().htmlDoc().build(); 2593 * </p> 2594 * 2595 * @return This object. 2596 */ 2597 public SELF htmlDoc() { 2598 return serializer(HtmlDocSerializer.class).parser(HtmlParser.class); 2599 } 2600 2601 /** 2602 * Convenience method for specifying Stripped HTML DOC as the marshalling transmission media type. 2603 * 2604 * <p> 2605 * Same as {@link #htmlDoc()} but without the header and body tags and page title and description. 2606 * 2607 * <p> 2608 * {@link HtmlStrippedDocSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 2609 * <ul> 2610 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 2611 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 2612 * </ul> 2613 * <p> 2614 * {@link HtmlParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 2615 * <ul> 2616 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 2617 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 2618 * </ul> 2619 * <p> 2620 * <c>Accept</c> request header will be set to <js>"text/html+stripped"</js> unless overridden 2621 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 2622 * <p> 2623 * <c>Content-Type</c> request header will be set to <js>"text/html+stripped"</js> unless overridden 2624 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 2625 * <p> 2626 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 2627 * <ul> 2628 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 2629 * last-enabled language if the headers are not set. 2630 * </ul> 2631 * <p> 2632 * Identical to calling <c>serializer(HtmlStrippedDocSerializer.<jk>class</jk>).parser(HtmlParser.<jk>class</jk>)</c>. 2633 * 2634 * <h4 class='section'>Example:</h4> 2635 * <p class='bjava'> 2636 * <jc>// Construct a client that uses HTML Stripped Doc marshalling.</jc> 2637 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().htmlStrippedDoc().build(); 2638 * </p> 2639 * 2640 * @return This object. 2641 */ 2642 public SELF htmlStrippedDoc() { 2643 return serializer(HtmlStrippedDocSerializer.class).parser(HtmlParser.class); 2644 } 2645 2646 /** 2647 * Sets the {@link HttpClient} to be used to handle all HTTP communications with the target server. 2648 * 2649 * <p> 2650 * This can be used to bypass the client created by {@link #createHttpClient()} method. 2651 * 2652 * <h4 class='section'>Example:</h4> 2653 * <p class='bjava'> 2654 * <jc>// Construct a client that uses a customized HttpClient.</jc> 2655 * RestClient <jv>client</jv> = RestClient 2656 * .<jsm>create</jsm>() 2657 * .httpClient(HttpClientBuilder.<jsm>create</jsm>().build()) 2658 * .build(); 2659 * </p> 2660 * 2661 * <h4 class='section'>Notes:</h4><ul> 2662 * <li class='warn'>A prebuilt client is used as-is: the redirect credential guard (which strips {@code Authorization}, 2663 * {@code Cookie} and similar headers on a cross-origin redirect) and the SSRF guardrail are installed on the 2664 * builder that {@link #createHttpClient()} uses, so they are not present on a client passed here. Build it from 2665 * {@link #httpClientBuilder()} instead, or disable redirect following on the prebuilt client. 2666 * </ul> 2667 * 2668 * @param value The {@link HttpClient} to be used to handle all HTTP communications with the target server. 2669 * <br>Can be <jk>null</jk> (a default client will be created). 2670 * @return This object. 2671 */ 2672 public SELF httpClient(CloseableHttpClient value) { 2673 httpClient = value; 2674 return self(); 2675 } 2676 2677 /** 2678 * Returns the HTTP client builder. 2679 * 2680 * @return The HTTP client builder. 2681 */ 2682 public final HttpClientBuilder httpClientBuilder() { 2683 if (httpClientBuilder == null) 2684 httpClientBuilder = createHttpClientBuilder(); 2685 return httpClientBuilder; 2686 } 2687 2688 /** 2689 * Sets the {@link HttpClientBuilder} that will be used to create the {@link HttpClient} used by {@link RestClient}. 2690 * 2691 * <p> 2692 * This can be used to bypass the builder created by {@link #createHttpClientBuilder()} method. 2693 * 2694 * <h4 class='section'>Example:</h4> 2695 * <p class='bjava'> 2696 * <jc>// Construct a client that uses a customized HttpClientBuilder.</jc> 2697 * RestClient <jv>client</jv> = RestClient 2698 * .<jsm>create</jsm>() 2699 * .httpClientBuilder(HttpClientBuilder.<jsm>create</jsm>()) 2700 * .build(); 2701 * </p> 2702 * 2703 * <h4 class='section'>Notes:</h4><ul> 2704 * <li class='note'>The TLS and connection-pool settings Apache {@link HttpClientBuilder} applies only to a 2705 * connection manager it builds itself 2706 * ({@link HttpClientBuilder#setSSLContext(SSLContext) setSSLContext}, 2707 * {@link HttpClientBuilder#setSSLSocketFactory(LayeredConnectionSocketFactory) setSSLSocketFactory}, 2708 * {@link HttpClientBuilder#setSSLHostnameVerifier(HostnameVerifier) setSSLHostnameVerifier}, 2709 * {@link HttpClientBuilder#setPublicSuffixMatcher(PublicSuffixMatcher) setPublicSuffixMatcher}, 2710 * {@link HttpClientBuilder#setMaxConnTotal(int) setMaxConnTotal}, 2711 * {@link HttpClientBuilder#setMaxConnPerRoute(int) setMaxConnPerRoute}, 2712 * {@link HttpClientBuilder#setConnectionTimeToLive(long, TimeUnit) setConnectionTimeToLive}, 2713 * {@link HttpClientBuilder#setDefaultSocketConfig(SocketConfig) setDefaultSocketConfig}, 2714 * {@link HttpClientBuilder#setDefaultConnectionConfig(ConnectionConfig) setDefaultConnectionConfig}, 2715 * {@link HttpClientBuilder#setDnsResolver(DnsResolver) setDnsResolver} and 2716 * {@link HttpClientBuilder#useSystemProperties() useSystemProperties}) are read from the given builder and 2717 * applied to the connection manager the default {@link #createConnectionManager()} builds (see there). 2718 * <li class='note'>These connection-manager settings, made through a method of this builder before this method is 2719 * called, are applied too, and win over the same setting on the given builder: 2720 * {@link #sslContext(SSLContext) sslContext}, 2721 * {@link #sslSocketFactory(LayeredConnectionSocketFactory) sslSocketFactory}, 2722 * {@link #sslHostnameVerifier(HostnameVerifier) sslHostnameVerifier}, 2723 * {@link #publicSuffixMatcher(PublicSuffixMatcher) publicSuffixMatcher} (for the default hostname verifier only: 2724 * its use for cookies is lost with the replaced builder), 2725 * {@link #maxConnTotal(int) maxConnTotal}, {@link #maxConnPerRoute(int) maxConnPerRoute}, {@link #pooled() pooled}, 2726 * {@link #connectionTimeToLive(long, TimeUnit) connectionTimeToLive}, 2727 * {@link #defaultSocketConfig(SocketConfig) defaultSocketConfig}, 2728 * {@link #defaultConnectionConfig(ConnectionConfig) defaultConnectionConfig} and the TLS and 2729 * {@code http.maxConnections} system properties of {@link #useSystemProperties()}. Every other setting made 2730 * through this builder before this method is called (interceptors, proxy, the rest of 2731 * {@code useSystemProperties()}, and so on) was made on the replaced builder and is lost. 2732 * <li class='note'>For these connection-manager settings, a value set through a method of this builder always wins 2733 * over the same setting on the {@code HttpClientBuilder}, whichever was set last: unlike Apache's own 2734 * last-write-wins, a later {@code httpClientBuilder().setDefaultSocketConfig(...)} (and so on) does not 2735 * override an earlier {@link #defaultSocketConfig(SocketConfig) defaultSocketConfig(...)}. 2736 * <li class='note'>As in Apache {@code HttpClientBuilder}, an SSL socket factory wins over an SSL context wherever 2737 * each was set: a {@link HttpClientBuilder#setSSLSocketFactory(LayeredConnectionSocketFactory) setSSLSocketFactory} 2738 * on the given builder wins over an earlier {@link #sslContext(SSLContext) sslContext}. 2739 * <li class='warn'>A socket factory set with {@code setSSLSocketFactory} on the given builder is used for 2740 * SSRF-guard-active {@code @Remote} calls too, and must connect to exactly the address it is given (see 2741 * {@link #sslSocketFactory(LayeredConnectionSocketFactory)}). 2742 * <li class='warn'>A client built by an {@code HttpClientBuilder} subclass that overrides (or inherits an override 2743 * of) {@code build()}, {@code createMainExec(...)}, {@code decorateMainExec(...)} or 2744 * {@code decorateProtocolExec(...)} refuses every SSRF-guard-active {@code @Remote} call: the override may 2745 * build the client around another connection manager or request executor. 2746 * </ul> 2747 * 2748 * @param value The {@link HttpClientBuilder} that will be used to create the {@link HttpClient} used by {@link RestClient}. 2749 * <br>Can be <jk>null</jk> (a default builder will be created). 2750 * @return This object. 2751 */ 2752 public SELF httpClientBuilder(HttpClientBuilder value) { 2753 httpClientBuilder = value; 2754 return self(); 2755 } 2756 2757 /** 2758 * Assigns {@link HttpProcessor} instance. 2759 * 2760 * <h4 class='section'>Notes:</h4><ul> 2761 * <li class='warn'>The processor replaces all of the client's request interceptors, among them the ones that 2762 * enforce the SSRF guard and strip credentials on cross-origin redirects. So a client with one refuses every 2763 * SSRF-guard-active {@code @Remote} call (one without the {@link #allowPrivateUrls(boolean) allowPrivateUrls} 2764 * opt-in). Add interceptors with {@link HttpClientBuilder#addInterceptorLast(HttpRequestInterceptor)} on the 2765 * {@link #httpClientBuilder() HttpClientBuilder} instead. 2766 * <li class='warn'>For the same reason the redirect credential guard is not applied: credential headers are then 2767 * forwarded on a cross-origin redirect unless redirect following is disabled. 2768 * </ul> 2769 * 2770 * @param httpprocessor New property value. 2771 * @return This object. 2772 * @see HttpClientBuilder#setHttpProcessor(HttpProcessor) 2773 */ 2774 public SELF httpProcessor(HttpProcessor httpprocessor) { 2775 httpClientBuilder().setHttpProcessor(httpprocessor); 2776 return self(); 2777 } 2778 2779 /** 2780 * Ignore errors. 2781 * 2782 * <p> 2783 * When enabled, HTTP error response codes (e.g. <l>>=400</l>) will not cause a {@link RestCallException} to 2784 * be thrown. 2785 * <p> 2786 * Note that this is equivalent to <c>builder.errorCodes(x -> <jk>false</jk>);</c> 2787 * 2788 * <h4 class='section'>Example:</h4> 2789 * <p class='bjava'> 2790 * <jc>// Create a client that doesn't throws a RestCallException when a 500 error occurs.</jc> 2791 * RestClient 2792 * .<jsm>create</jsm>() 2793 * .ignoreErrors() 2794 * .build() 2795 * .get(<js>"/error"</js>) <jc>// Throws a 500 error</jc> 2796 * .run() 2797 * .assertStatus().is(500); 2798 * </p> 2799 * 2800 * @return This object. 2801 */ 2802 public SELF ignoreErrors() { 2803 ignoreErrors = true; 2804 return self(); 2805 } 2806 2807 /** 2808 * <i><l>BeanTraverse</l> configuration property: </i> Ignore recursion errors. 2809 * 2810 * <p> 2811 * When enabled, when we encounter the same object when traversing a tree, we set the value to <jk>null</jk>. 2812 * 2813 * <p> 2814 * For example, if a model contains the links A->B->C->A, then the JSON generated will look like 2815 * the following when <jsf>BEANTRAVERSE_ignoreRecursions</jsf> is <jk>true</jk>... 2816 * 2817 * <p class='bjson'> 2818 * {A:{B:{C:<jk>null</jk>}}} 2819 * </p> 2820 * 2821 * <h4 class='section'>Notes:</h4><ul> 2822 * <li class='note'> 2823 * Checking for recursion can cause a small performance penalty. 2824 * </ul> 2825 * 2826 * <h4 class='section'>Example:</h4> 2827 * <p class='bjava'> 2828 * <jc>// Create a JSON client that ignores recursions.</jc> 2829 * RestClient <jv>client</jv> = RestClient 2830 * .<jsm>create</jsm>() 2831 * .json() 2832 * .ignoreRecursions() 2833 * .build(); 2834 * 2835 * <jc>// Create a POJO model with a recursive loop.</jc> 2836 * <jk>public class</jk> A { 2837 * <jk>public</jk> Object <jf>f</jf>; 2838 * } 2839 * A <jv>a</jv> = <jk>new</jk> A(); 2840 * <jv>a</jv>.<jf>f</jf> = <jv>a</jv>; 2841 * 2842 * <jc>// Produces request body "{f:null}"</jc> 2843 * <jv>client</jv> 2844 * .post(<js>"http://localhost:10000/foo"</js>, <jv>a</jv>) 2845 * .run(); 2846 * </p> 2847 * 2848 * <h4 class='section'>See Also:</h4><ul> 2849 * <li class='jm'>{@link org.apache.juneau.marshall.MarshallingTraverseContext.Builder#ignoreRecursions() MarshallingTraverseContext.Builder#ignoreRecursions()} 2850 * </ul> 2851 * 2852 * @return This object. 2853 */ 2854 public SELF ignoreRecursions() { 2855 serializers().forEach(Serializer.Builder::ignoreRecursions); 2856 return self(); 2857 } 2858 2859 /** 2860 * <i><l>BeanTraverse</l> configuration property: </i> Initial depth. 2861 * 2862 * <p> 2863 * The initial indentation level at the root. 2864 * 2865 * <p> 2866 * Useful when constructing document fragments that need to be indented at a certain level when whitespace is enabled. 2867 * 2868 * <h4 class='section'>Example:</h4> 2869 * <p class='bjava'> 2870 * <jc>// Create a REST client with JSON serializer with whitespace enabled and an initial depth of 2.</jc> 2871 * RestClient <jv>client</jv> = RestClient 2872 * .<jsm>create</jsm>() 2873 * .json() 2874 * .ws() 2875 * .initialDepth(2) 2876 * .build(); 2877 * 2878 * <jc>// Our bean to serialize.</jc> 2879 * <jk>public class</jk> MyBean { 2880 * <jk>public</jk> String <jf>foo</jf> = <jk>null</jk>; 2881 * } 2882 * 2883 * <jc>// Produces request body "\t\t{\n\t\t\t'foo':'bar'\n\t\t}\n"</jc> 2884 * <jv>client</jv> 2885 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 2886 * .run(); 2887 * </p> 2888 * 2889 * <h4 class='section'>See Also:</h4><ul> 2890 * <li class='jm'>{@link org.apache.juneau.marshall.MarshallingTraverseContext.Builder#initialDepth(int) MarshallingTraverseContext.Builder#initialDepth(int)} 2891 * </ul> 2892 * 2893 * @param value 2894 * The new value for this property. 2895 * <br>The default is <c>0</c>. 2896 * @return This object. 2897 */ 2898 public SELF initialDepth(int value) { 2899 serializers().forEach(x -> x.initialDepth(value)); 2900 return self(); 2901 } 2902 2903 /** 2904 * <i><l>RestClient</l> configuration property: </i> Call interceptors. 2905 * 2906 * <p> 2907 * Adds an interceptor that can be called to hook into specified events in the lifecycle of a single request. 2908 * 2909 * <h4 class='section'>Example:</h4> 2910 * <p class='bjava'> 2911 * <jc>// Customized interceptor (note you can also extend from BasicRestCallInterceptor as well.</jc> 2912 * <jk>public class</jk> MyRestCallInterceptor <jk>implements</jk> RestCallInterceptor { 2913 * 2914 * <ja>@Override</ja> 2915 * <jk>public void</jk> onInit(RestRequest <jv>req</jv>) <jk>throws</jk> Exception { 2916 * <jc>// Intercept immediately after RestRequest object is created and all headers/query/form-data has been 2917 * // set on the request from the client.</jc> 2918 * } 2919 * 2920 * <ja>@Override</ja> 2921 * <jk>public void</jk> onConnect(RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) <jk>throws</jk> Exception { 2922 * <jc>// Intercept immediately after an HTTP response has been received.</jc> 2923 * } 2924 * 2925 * <ja>@Override</ja> 2926 * <jk>public void</jk> onClose(RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) <jk>throws</jk> Exception { 2927 * <jc>// Intercept when the response body is consumed.</jc> 2928 * } 2929 * } 2930 * 2931 * <jc>// Create a client with a customized interceptor.</jc> 2932 * RestClient <jv>client</jv> = RestClient 2933 * .<jsm>create</jsm>() 2934 * .interceptors(MyRestCallInterceptor.<jk>class</jk>) 2935 * .build(); 2936 * </p> 2937 * 2938 * <h4 class='section'>Notes:</h4><ul> 2939 * <li class='note'>The {@link RestClient#onCallInit(RestRequest)}, {@link RestClient#onCallConnect(RestRequest,RestResponse)}, and 2940 * {@link RestClient#onCallClose(RestRequest,RestResponse)} methods can also be overridden to produce the same results. 2941 * </ul> 2942 * 2943 * @param values 2944 * The values to add to this setting. 2945 * <br>Can be implementations of any of the following: 2946 * <ul> 2947 * <li class='jic'>{@link RestCallInterceptor} 2948 * <li class='jic'>{@link HttpRequestInterceptor} 2949 * <li class='jic'>{@link HttpResponseInterceptor} 2950 * </ul> 2951 * <br>Can contain <jk>null</jk> values (ignored). 2952 * @return This object. 2953 * @throws Exception If one or more interceptors could not be created. 2954 */ 2955 public SELF interceptors(Class<?>...values) throws Exception { 2956 for (var c : values) { 2957 if (c == null) 2958 continue; 2959 var ci = ClassInfo.of(c); 2960 if (nn(ci)) { 2961 if (ci.isAssignableToAny(RestCallInterceptor.class, HttpRequestInterceptor.class, HttpResponseInterceptor.class)) 2962 interceptors(ci.newInstance()); 2963 else 2964 throw new ConfigException("Invalid class of type '%s' passed to interceptors().", ci.getName()); 2965 } 2966 } 2967 return self(); 2968 } 2969 2970 /** 2971 * Call interceptors. 2972 * 2973 * <p> 2974 * Adds an interceptor that gets called immediately after a connection is made. 2975 * 2976 * <h4 class='section'>Example:</h4> 2977 * <p class='bjava'> 2978 * <jc>// Create a client with a customized interceptor.</jc> 2979 * RestClient <jv>client</jv> = RestClient 2980 * .<jsm>create</jsm>() 2981 * .interceptors( 2982 * <jk>new</jk> RestCallInterceptor() { 2983 * 2984 * <ja>@Override</ja> 2985 * <jk>public void</jk> onInit(RestRequest <jv>req</jv>) <jk>throws</jk> Exception { 2986 * <jc>// Intercept immediately after RestRequest object is created and all headers/query/form-data has been 2987 * // set on the request from the client.</jc> 2988 * } 2989 * 2990 * <ja>@Override</ja> 2991 * <jk>public void</jk> onConnect(RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) <jk>throws</jk> Exception { 2992 * <jc>// Intercept immediately after an HTTP response has been received.</jc> 2993 * } 2994 * 2995 * <ja>@Override</ja> 2996 * <jk>public void</jk> onClose(RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) <jk>throws</jk> Exception { 2997 * <jc>// Intercept when the response body is consumed.</jc> 2998 * } 2999 * } 3000 * ) 3001 * .build(); 3002 * </p> 3003 * 3004 * <h4 class='section'>Notes:</h4><ul> 3005 * <li class='note'>The {@link RestClient#onCallInit(RestRequest)}, {@link RestClient#onCallConnect(RestRequest,RestResponse)}, and 3006 * {@link RestClient#onCallClose(RestRequest,RestResponse)} methods can also be overridden to produce the same results. 3007 * </ul> 3008 * 3009 * @param value 3010 * The values to add to this setting. 3011 * <br>Can be implementations of any of the following: 3012 * <ul> 3013 * <li class='jic'>{@link RestCallInterceptor} 3014 * <li class='jic'>{@link HttpRequestInterceptor} 3015 * <li class='jic'>{@link HttpResponseInterceptor} 3016 * </ul> 3017 * <br>Can contain <jk>null</jk> values (ignored). 3018 * @return This object. 3019 */ 3020 public SELF interceptors(Object...value) { 3021 List<RestCallInterceptor> l = list(); 3022 for (var o : value) { 3023 if (o == null) 3024 continue; 3025 ClassInfo ci = ClassInfo.of(o); 3026 if (nn(ci)) { 3027 if (! ci.isAssignableToAny(HttpRequestInterceptor.class, HttpResponseInterceptor.class, RestCallInterceptor.class)) 3028 throw new ConfigException("Invalid object of type '%s' passed to interceptors().", ci.getName()); 3029 if (o instanceof HttpRequestInterceptor o2) 3030 addInterceptorLast(o2); 3031 if (o instanceof HttpResponseInterceptor o2) 3032 addInterceptorLast(o2); 3033 if (o instanceof RestCallInterceptor o2) 3034 l.add(o2); 3035 } 3036 } 3037 if (interceptors == null) 3038 interceptors = l; 3039 else 3040 interceptors.addAll(0, l); 3041 return self(); 3042 } 3043 3044 /** 3045 * Convenience method for specifying JSON as the marshalling transmission media type. 3046 * 3047 * <p> 3048 * {@link JsonSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 3049 * <ul> 3050 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 3051 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3052 * </ul> 3053 * <p> 3054 * {@link JsonParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 3055 * <ul> 3056 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 3057 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3058 * </ul> 3059 * <p> 3060 * <c>Accept</c> request header will be set to <js>"application/json"</js> unless overridden 3061 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}}. 3062 * <p> 3063 * <c>Content-Type</c> request header will be set to <js>"application/json"</js> unless overridden 3064 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 3065 * <p> 3066 * Can be combined with other marshaller setters such as {@link #xml()} to provide support for multiple languages. 3067 * <ul> 3068 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 3069 * last-enabled language if the headers are not set. 3070 * </ul> 3071 * <p> 3072 * Identical to calling <c>serializer(JsonSerializer.<jk>class</jk>).parser(JsonParser.<jk>class</jk>)</c>. 3073 * 3074 * <h4 class='section'>Example:</h4> 3075 * <p class='bjava'> 3076 * <jc>// Construct a client that uses JSON marshalling.</jc> 3077 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().json().build(); 3078 * </p> 3079 * 3080 * @return This object. 3081 */ 3082 public SELF json() { 3083 return serializer(JsonSerializer.class).parser(JsonParser.class); 3084 } 3085 3086 /** 3087 * Convenience method for specifying Simplified JSON as the marshalling transmission media type. 3088 * 3089 * <p> 3090 * Simplified JSON is typically useful for automated tests because you can do simple string comparison of results 3091 * without having to escape lots of quotes. 3092 * 3093 * <p> 3094 * {@link Json5Serializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 3095 * <ul> 3096 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 3097 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3098 * </ul> 3099 * <p> 3100 * {@link Json5Parser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 3101 * <ul> 3102 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 3103 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3104 * </ul> 3105 * <p> 3106 * <c>Accept</c> request header will be set to <js>"application/json5"</js> unless overridden 3107 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 3108 * <p> 3109 * <c>Content-Type</c> request header will be set to <js>"application/json5"</js> unless overridden 3110 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 3111 * <p> 3112 * A server that only handles JSON may reply <c>406 Not Acceptable</c> or <c>415 Unsupported Media Type</c> to these 3113 * JSON5 media types. 3114 * <p> 3115 * Can be combined with other marshaller setters such as {@link #xml()} to provide support for multiple languages. 3116 * <ul> 3117 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 3118 * last-enabled language if the headers are not set. 3119 * </ul> 3120 * <p> 3121 * Identical to calling <c>serializer(Json5Serializer.<jk>class</jk>).parser(Json5Parser.<jk>class</jk>)</c>. 3122 * 3123 * <h4 class='section'>Example:</h4> 3124 * <p class='bjava'> 3125 * <jc>// Construct a client that uses Simplified JSON marshalling.</jc> 3126 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().json5().build(); 3127 * </p> 3128 * 3129 * @return This object. 3130 */ 3131 public SELF json5() { 3132 return serializer(Json5Serializer.class).parser(Json5Parser.class); 3133 } 3134 3135 /** 3136 * Convenience method for specifying JCS (JSON Canonicalization Scheme, RFC 8785) as the marshalling transmission media type. 3137 * 3138 * <p> 3139 * {@link JcsSerializer} will be used to serialize POJOs to request bodies. 3140 * {@link JsonParser} will be used to parse POJOs from response bodies (JCS output is valid JSON). 3141 * <p> 3142 * <c>Accept</c> and <c>Content-Type</c> will be set to <js>"application/jcs+json"</js>. 3143 * <p> 3144 * Identical to calling <c>serializer(JcsSerializer.<jk>class</jk>).parser(JsonParser.<jk>class</jk>)</c>. 3145 * 3146 * @return This object. 3147 */ 3148 public SELF jcs() { 3149 return serializer(JcsSerializer.class).parser(JsonParser.class); 3150 } 3151 3152 /** 3153 * Assigns {@link ConnectionKeepAliveStrategy} instance. 3154 * 3155 * @param keepAliveStrategy New property value. 3156 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 3157 * @return This object. 3158 * @see HttpClientBuilder#setKeepAliveStrategy(ConnectionKeepAliveStrategy) 3159 */ 3160 public SELF keepAliveStrategy(ConnectionKeepAliveStrategy keepAliveStrategy) { 3161 httpClientBuilder().setKeepAliveStrategy(keepAliveStrategy); 3162 return self(); 3163 } 3164 3165 /** 3166 * <i><l>RestClient</l> configuration property: </i> Keep HttpClient open. 3167 * 3168 * <p> 3169 * Don't close this client when the {@link RestClient#close()} method is called. 3170 * 3171 * <h4 class='section'>Example:</h4> 3172 * <p class='bjava'> 3173 * <jc>// Create a client with a customized client and don't close the client service.</jc> 3174 * RestClient <jv>client</jv> = RestClient 3175 * .<jsm>create</jsm>() 3176 * .httpClient(<jv>myHttpClient</jv>) 3177 * .keepHttpClientOpen() 3178 * .build(); 3179 * 3180 * <jv>client</jv>.closeQuietly(); <jc>// Customized HttpClient won't be closed.</jc> 3181 * </p> 3182 * 3183 * <h4 class='section'>Notes:</h4><ul> 3184 * <li class='note'>When combined with {@link #connectionManagerShared(boolean) connectionManagerShared(true)}, the 3185 * client's internal pool for SSRF-guard-active {@code @Remote} calls (see {@link #createConnectionManager()}) and 3186 * the connection manager the default {@code createConnectionManager()} built are not shut down either, and 3187 * nothing else shuts them down; their connections stay open until they are closed as idle or the JVM exits. 3188 * </ul> 3189 * 3190 * @return This object. 3191 */ 3192 public SELF keepHttpClientOpen() { 3193 keepHttpClientOpen = true; 3194 return self(); 3195 } 3196 3197 /** 3198 * <i><l>Serializer</l> configuration property: </i> Don't trim null bean property values. 3199 * 3200 * <p> 3201 * When enabled, null bean values will be serialized to the output. 3202 * 3203 * <h4 class='section'>Notes:</h4><ul> 3204 * <li class='note'>Not enabling this setting will cause <c>Map</c>s with <jk>null</jk> values to be lost during parsing. 3205 * </ul> 3206 * 3207 * <h4 class='section'>Example:</h4> 3208 * <p class='bjava'> 3209 * <jc>// Create a REST client with JSON serializer that serializes null properties.</jc> 3210 * RestClient <jv>client</jv> = RestClient 3211 * .<jsm>create</jsm>() 3212 * .json() 3213 * .keepNullProperties() 3214 * .build(); 3215 * 3216 * <jc>// Our bean to serialize.</jc> 3217 * <jk>public class</jk> MyBean { 3218 * <jk>public</jk> String <jf>foo</jf> = <jk>null</jk>; 3219 * } 3220 * 3221 * <jc>// Request body will contain: {foo:null}</jc> 3222 * <jv>client</jv> 3223 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 3224 * .run(); 3225 * </p> 3226 * 3227 * <h4 class='section'>See Also:</h4><ul> 3228 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#keepNullProperties() Serializer.Builder#keepNullProperties()} 3229 * </ul> 3230 * 3231 * @return This object. 3232 */ 3233 public SELF keepNullProperties() { 3234 serializers().forEach(Serializer.Builder::keepNullProperties); 3235 return self(); 3236 } 3237 3238 /** 3239 * Logger. 3240 * 3241 * <p> 3242 * Specifies the logger to use for logging. 3243 * 3244 * <p> 3245 * If not specified, uses the following logger: 3246 * <p class='bjava'> 3247 * Logger.<jsm>getLogger</jsm>(RestClient.<jk>class</jk>.getName()); 3248 * </p> 3249 * 3250 * <h4 class='section'>Example:</h4> 3251 * <p class='bjava'> 3252 * <jc>// Construct a client that logs messages to a special logger.</jc> 3253 * RestClient <jv>client</jv> = RestClient 3254 * .<jsm>create</jsm>() 3255 * .logger(Logger.<jsm>getLogger</jsm>(<js>"MyLogger"</js>)) <jc>// Log to MyLogger logger.</jc> 3256 * .logToConsole() <jc>// Also log to console.</jc> 3257 * .logRequests(<jsf>FULL</jsf>, <jsf>WARNING</jsf>) <jc>// Log requests with full detail at WARNING level.</jc> 3258 * .build(); 3259 * </p> 3260 * 3261 * @param value The logger to use for logging. 3262 * <br>Can be <jk>null</jk> (defaults to <c>Logger.getLogger(RestClient.class.getName())</c>). 3263 * @return This object. 3264 */ 3265 public SELF logger(Logger value) { 3266 logger = value; 3267 return self(); 3268 } 3269 3270 /** 3271 * Log requests. 3272 * 3273 * <p> 3274 * Causes requests/responses to be logged at the specified log level at the end of the request. 3275 * 3276 * <p> 3277 * <jsf>SIMPLE</jsf> detail produces a log message like the following: 3278 * <p class='bconsole'> 3279 * POST http://localhost:10000/testUrl, HTTP/1.1 200 OK 3280 * </p> 3281 * 3282 * <p> 3283 * <jsf>FULL</jsf> detail produces a log message like the following: 3284 * <p class='bconsole'> 3285 * === HTTP Call (outgoing) ======================================================= 3286 * === REQUEST === 3287 * POST http://localhost:10000/testUrl 3288 * ---request headers--- 3289 * Debug: true 3290 * No-Trace: true 3291 * Accept: application/json 3292 * ---request entity--- 3293 * Content-Type: application/json 3294 * ---request content--- 3295 * {"foo":"bar","baz":123} 3296 * === RESPONSE === 3297 * HTTP/1.1 200 OK 3298 * ---response headers--- 3299 * Content-Type: application/json;charset=utf-8 3300 * Content-Length: 21 3301 * Server: Jetty(8.1.0.v20120127) 3302 * ---response content--- 3303 * {"message":"OK then"} 3304 * === END ======================================================================== 3305 * </p> 3306 * 3307 * <p> 3308 * By default, the message is logged to the default logger. It can be logged to a different logger via the 3309 * {@link #logger(Logger)} method or logged to the console using the 3310 * {@link #logToConsole()} method. 3311 * 3312 * @param detail The detail level of logging. 3313 * @param level The log level. 3314 * @param test A predicate to use per-request to see if the request should be logged. If <jk>null</jk>, always logs. 3315 * @return This object. 3316 */ 3317 public SELF logRequests(DetailLevel detail, Level level, BiPredicate<RestRequest,RestResponse> test) { 3318 logRequests = detail; 3319 logRequestsLevel = level; 3320 logRequestsPredicate = test; 3321 return self(); 3322 } 3323 3324 /** 3325 * Log to console. 3326 * 3327 * <p> 3328 * Specifies to log messages to the console. 3329 * 3330 * <h4 class='section'>Example:</h4> 3331 * <p class='bjava'> 3332 * <jc>// Construct a client that logs messages to a special logger.</jc> 3333 * RestClient <jv>client</jv> = RestClient 3334 * .<jsm>create</jsm>() 3335 * .logToConsole() 3336 * .logRequests(<jsf>FULL</jsf>, <jsf>INFO</jsf>) <jc>// Level is ignored when logging to console.</jc> 3337 * .build(); 3338 * </p> 3339 * 3340 * @return This object. 3341 */ 3342 public SELF logToConsole() { 3343 logToConsole = true; 3344 return self(); 3345 } 3346 3347 /** 3348 * <i><l>RestClient</l> configuration property: </i> Marshaller 3349 * 3350 * <p> 3351 * Shortcut for specifying the serializers and parsers 3352 * using the serializer and parser defined in a marshaller. 3353 * 3354 * <h4 class='section'>Notes:</h4><ul> 3355 * <li class='note'>When using this method that takes in a pre-instantiated serializers and parsers, the serializer property setters (e.g. {@link #sortCollections()}), 3356 * parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}), or bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class have no effect. 3357 * </ul> 3358 * 3359 * <h4 class='section'>Example:</h4> 3360 * <p class='bjava'> 3361 * <jc>// Create a client that uses Simplified-JSON transport using an existing marshaller.</jc> 3362 * RestClient <jv>client</jv> = RestClient 3363 * .<jsm>create</jsm>() 3364 * .marshaller(Json5.<jsf>DEFAULT_READABLE</jsf>) 3365 * .build(); 3366 * </p> 3367 * 3368 * @param value The values to add to this setting. 3369 * <br>Can be <jk>null</jk> (value will not be set, existing serializers and parsers will be kept). 3370 * @return This object. 3371 */ 3372 public SELF marshaller(Marshaller value) { 3373 if (nn(value)) 3374 serializer(value.getSerializer()).parser(value.getParser()); 3375 return self(); 3376 } 3377 3378 /** 3379 * <i><l>RestClient</l> configuration property: </i> Marshalls 3380 * 3381 * <p> 3382 * Shortcut for specifying the serializers and parsers 3383 * using the serializer and parser defined in a marshaller. 3384 * 3385 * <h4 class='section'>Notes:</h4><ul> 3386 * <li class='note'>When using this method that takes in a pre-instantiated serializers and parsers, the serializer property setters (e.g. {@link #sortCollections()}), 3387 * parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}), or bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class have no effect. 3388 * </ul> 3389 * 3390 * <h4 class='section'>Example:</h4> 3391 * <p class='bjava'> 3392 * <jc>// Create a client that uses JSON and XML transport using existing marshalls.</jc> 3393 * RestClient <jv>client</jv> = RestClient 3394 * .<jsm>create</jsm>() 3395 * .marshaller(Json.<jsf>DEFAULT_READABLE</jsf>, Xml.<jsf>DEFAULT_READABLE</jsf>) 3396 * .build(); 3397 * </p> 3398 * 3399 * @param value The values to add to this setting. 3400 * <br>Can contain <jk>null</jk> values (ignored). 3401 * @return This object. 3402 */ 3403 public SELF marshallers(Marshaller...value) { 3404 for (var m : value) 3405 if (nn(m)) 3406 serializer(m.getSerializer()).parser(m.getParser()); 3407 return self(); 3408 } 3409 3410 /** 3411 * Assigns maximum connection per route value. 3412 * 3413 * <h4 class='section'>Notes:</h4><ul> 3414 * <li class='note'>A positive value is applied to the connection manager the default 3415 * {@link #createConnectionManager()} builds, which is then always a {@link PoolingHttpClientConnectionManager} 3416 * (as if {@link #pooled()} had been called), and to its internal pool for SSRF-guard-active {@code @Remote} calls. 3417 * <li class='note'>It has no effect on a connection manager supplied through 3418 * {@link #connectionManager(HttpClientConnectionManager)} or an overridden {@link #createConnectionManager()}. 3419 * </ul> 3420 * 3421 * @param maxConnPerRoute New property value. 3422 * @return This object. 3423 * @see HttpClientBuilder#setMaxConnPerRoute(int) 3424 */ 3425 public SELF maxConnPerRoute(int maxConnPerRoute) { 3426 this.maxConnPerRoute = maxConnPerRoute; 3427 httpClientBuilder().setMaxConnPerRoute(maxConnPerRoute); 3428 return self(); 3429 } 3430 3431 /** 3432 * Assigns maximum total connection value. 3433 * 3434 * <h4 class='section'>Notes:</h4><ul> 3435 * <li class='note'>A positive value is applied to the connection manager the default 3436 * {@link #createConnectionManager()} builds, which is then always a {@link PoolingHttpClientConnectionManager} 3437 * (as if {@link #pooled()} had been called), and to its internal pool for SSRF-guard-active {@code @Remote} calls. 3438 * Each pool applies the limit on its own (see {@link #createConnectionManager()}). 3439 * <li class='note'>It has no effect on a connection manager supplied through 3440 * {@link #connectionManager(HttpClientConnectionManager)} or an overridden {@link #createConnectionManager()}. 3441 * </ul> 3442 * 3443 * @param maxConnTotal New property value. 3444 * @return This object. 3445 * @see HttpClientBuilder#setMaxConnTotal(int) 3446 */ 3447 public SELF maxConnTotal(int maxConnTotal) { 3448 this.maxConnTotal = maxConnTotal; 3449 httpClientBuilder().setMaxConnTotal(maxConnTotal); 3450 return self(); 3451 } 3452 3453 /** 3454 * <i><l>BeanTraverse</l> configuration property: </i> Max serialization depth. 3455 * 3456 * <p> 3457 * When enabled, abort traversal if specified depth is reached in the POJO tree. 3458 * 3459 * <p> 3460 * If this depth is exceeded, an exception is thrown. 3461 * 3462 * <p> 3463 * This prevents stack overflows from occurring when trying to traverse models with recursive references. 3464 * 3465 * <h4 class='section'>Example:</h4> 3466 * <p class='bjava'> 3467 * <jc>// Create a REST client with JSON serializer that throws an exception if the depth reaches greater than 20.</jc> 3468 * RestClient <jv>client</jv> = RestClient 3469 * .<jsm>create</jsm>() 3470 * .json() 3471 * .maxDepth(20) 3472 * .build(); 3473 * </p> 3474 * 3475 * <h4 class='section'>See Also:</h4><ul> 3476 * <li class='jm'>{@link org.apache.juneau.marshall.MarshallingTraverseContext.Builder#maxDepth(int) MarshallingTraverseContext.Builder#maxDepth(int)} 3477 * </ul> 3478 * 3479 * @param value 3480 * The new value for this property. 3481 * <br>The default is <c>100</c>. 3482 * @return This object. 3483 */ 3484 public SELF maxDepth(int value) { 3485 serializers().forEach(x -> x.maxDepth(value)); 3486 return self(); 3487 } 3488 3489 /** 3490 * <i><l>WriterSerializer</l> configuration property: </i> Maximum indentation. 3491 * 3492 * <p> 3493 * Specifies the maximum indentation level in the serialized document. 3494 * 3495 * <h4 class='section'>Notes:</h4><ul> 3496 * <li class='note'>This setting does not apply to the RDF serializers. 3497 * </ul> 3498 * 3499 * <h4 class='section'>Example:</h4> 3500 * <p class='bjava'> 3501 * <jc>// Create a REST client with JSON serializer that indents a maximum of 20 tabs.</jc> 3502 * RestClient <jv>client</jv> = RestClient 3503 * .<jsm>create</jsm>() 3504 * .json() 3505 * .ws() <jc>// Enable whitespace</jc> 3506 * .maxIndent(20) 3507 * .build(); 3508 * </p> 3509 * 3510 * <h4 class='section'>See Also:</h4><ul> 3511 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.WriterSerializer.Builder#maxIndent(int) WriterSerializer.Builder#maxIndent(int)} 3512 * </ul> 3513 * 3514 * @param value 3515 * The new value for this property. 3516 * <br>The default is <c>100</c>. 3517 * @return This object. 3518 */ 3519 public SELF maxIndent(int value) { 3520 serializers().forEachWS(x -> x.maxIndent(value)); 3521 return self(); 3522 } 3523 3524 /** 3525 * Appends the <c>Accept</c> and <c>Content-Type</c> headers on all requests made by this client. 3526 * 3527 * <p> 3528 * Headers are appended to the end of the current header list. 3529 * 3530 * <p> 3531 * This is a shortcut for calling <c>headerData().append(Accept.<jsm>of</jsm>(<jv>value</jv>), ContentType.<jsm>of</jsm>(<jv>value</jv>))</c>. 3532 * 3533 * @param value The new header values. 3534 * <br>Can be <jk>null</jk> (no Accept or Content-Type headers will be added). 3535 * @return This object. 3536 * @see #headers() 3537 */ 3538 @Override 3539 public SELF mediaType(MediaType value) { 3540 super.mediaType(value); 3541 return headers(Accept.of(value), ContentType.of(value)); 3542 } 3543 3544 /** 3545 * Appends the <c>Accept</c> and <c>Content-Type</c> headers on all requests made by this client. 3546 * 3547 * <p> 3548 * Headers are appended to the end of the current header list. 3549 * 3550 * <p> 3551 * This is a shortcut for calling <c>headerData().append(Accept.<jsm>of</jsm>(<jv>value</jv>), ContentType.<jsm>of</jsm>(<jv>value</jv>))</c>. 3552 * 3553 * @param value The new header values. 3554 * <br>Can be <jk>null</jk> (no Accept or Content-Type headers will be added). 3555 * @return This object. 3556 * @see #headers() 3557 */ 3558 public SELF mediaType(String value) { 3559 super.mediaType(MediaType.of(value)); 3560 return headers(Accept.of(value), ContentType.of(value)); 3561 } 3562 3563 /** 3564 * Convenience method for specifying BSON as the marshalling transmission media type. 3565 * 3566 * <p> 3567 * BSON (Binary JSON) is the format used by MongoDB. Identical to calling 3568 * <c>serializer(BsonSerializer.<jk>class</jk>).parser(BsonParser.<jk>class</jk>)</c>. 3569 * 3570 * @return This object. 3571 */ 3572 public SELF bson() { 3573 return serializer(BsonSerializer.class).parser(BsonParser.class); 3574 } 3575 3576 /** 3577 * Convenience method for specifying MessagePack as the marshalling transmission media type. 3578 * 3579 * <p> 3580 * MessagePack is a binary equivalent to JSON that takes up considerably less space than JSON. 3581 * 3582 * <p> 3583 * {@link MsgPackSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 3584 * <ul> 3585 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 3586 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3587 * </ul> 3588 * <p> 3589 * {@link MsgPackParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 3590 * <ul> 3591 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 3592 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3593 * </ul> 3594 * <p> 3595 * <c>Accept</c> request header will be set to <js>"application/msgpack"</js> unless overridden 3596 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 3597 * <p> 3598 * <c>Content-Type</c> request header will be set to <js>"application/msgpack"</js> unless overridden 3599 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 3600 * <p> 3601 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 3602 * <ul> 3603 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 3604 * last-enabled language if the headers are not set. 3605 * </ul> 3606 * <p> 3607 * Identical to calling <c>serializer(MsgPackSerializer.<jk>class</jk>).parser(MsgPackParser.<jk>class</jk>)</c>. 3608 * 3609 * <h4 class='section'>Example:</h4> 3610 * <p class='bjava'> 3611 * <jc>// Construct a client that uses MessagePack marshalling.</jc> 3612 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().msgPack().build(); 3613 * </p> 3614 * 3615 * @return This object. 3616 */ 3617 public SELF msgPack() { 3618 return serializer(MsgPackSerializer.class).parser(MsgPackParser.class); 3619 } 3620 3621 /** 3622 * When called, <c>No-Trace: true</c> is added to requests. 3623 * 3624 * <p> 3625 * This gives the opportunity for the servlet to not log errors on invalid requests. 3626 * This is useful for testing purposes when you don't want your log file to show lots of errors that are simply the 3627 * results of testing. 3628 * 3629 * <p> 3630 * It's up to the server to decide whether to allow for this. 3631 * The <c>BasicTestRestLogger</c> class watches for this header and prevents logging of status 400+ responses to 3632 * prevent needless logging of test scenarios. 3633 * 3634 * @return This object. 3635 * @see #headers() 3636 */ 3637 public SELF noTrace() { 3638 return headers(NoTrace.of(true)); 3639 } 3640 3641 /** 3642 * <i><l>OpenApiCommon</l> configuration property: </i> Default collection format for HTTP parts. 3643 * 3644 * <p> 3645 * Specifies the collection format to use for HTTP parts when not otherwise specified via {@link Schema#collectionFormat()} for the 3646 * OpenAPI serializer and parser on this client. 3647 * 3648 * <h4 class='section'>Example:</h4> 3649 * <p class='bjava'> 3650 * <jc>// Create a REST client with CSV format for http parts.</jc> 3651 * RestClient <jv>client</jv> = RestClient 3652 * .<jsm>create</jsm>() 3653 * .collectionFormat(<jsf>CSV</jsf>) 3654 * .build(); 3655 * 3656 * <jc>// An arbitrary data structure.</jc> 3657 * AList <jv>list</jv> = AList.<jsm>of</jsm>( 3658 * <js>"foo"</js>, 3659 * <js>"bar"</js>, 3660 * AMap.<jsm>of</jsm>( 3661 * <js>"baz"</js>, AList.<jsm>of</jsm>(<js>"qux"</js>,<js>"true"</js>,<js>"123"</js>) 3662 * ) 3663 * ); 3664 * 3665 * <jc>// Set a header with a comma-separated list.</jc> 3666 * <jv>client</jv> 3667 * .get(<js>"/uri"</js>) 3668 * .header(<js>"Foo"</js>, <jv>list</jv>) <jc>// Will be serialized as: foo=bar,baz=qux\,true\,123</jc> 3669 * .run(); 3670 * </p> 3671 * 3672 * <ul class='values javatree'> 3673 * <li class='jc'>{@link HttpPartCollectionFormat} 3674 * <ul> 3675 * <li class='jf'>{@link HttpPartCollectionFormat#CSV CSV} - (default) Comma-separated values (e.g. <js>"foo,bar"</js>). 3676 * <li class='jf'>{@link HttpPartCollectionFormat#SSV SSV} - Space-separated values (e.g. <js>"foo bar"</js>). 3677 * <li class='jf'>{@link HttpPartCollectionFormat#TSV TSV} - Tab-separated values (e.g. <js>"foo\tbar"</js>). 3678 * <li class='jf'>{@link HttpPartCollectionFormat#PIPES PIPES} - Pipe-separated values (e.g. <js>"foo|bar"</js>). 3679 * <li class='jf'>{@link HttpPartCollectionFormat#MULTI MULTI} - Corresponds to multiple parameter instances instead of multiple values for a single instance (e.g. <js>"foo=bar&foo=baz"</js>). 3680 * <li class='jf'>{@link HttpPartCollectionFormat#UONC UONC} - UON collection notation (e.g. <js>"@(foo,bar)"</js>). 3681 * </ul> 3682 * </ul> 3683 * 3684 * <h4 class='section'>See Also:</h4><ul> 3685 * <li class='jm'>{@link org.apache.juneau.marshall.oapi.OpenApiSerializer.Builder#collectionFormat(HttpPartCollectionFormat) OpenApiSerializer.Builder#collectionFormat(HttpPartCollectionFormat)} 3686 * <li class='jm'>{@link org.apache.juneau.marshall.oapi.OpenApiParser.Builder#collectionFormat(HttpPartCollectionFormat) OpenApiParser.Builder#collectionFormat(HttpPartCollectionFormat)} 3687 * </ul> 3688 * 3689 * @param value 3690 * The new value for this property. 3691 * <br>The default value is {@link HttpPartCollectionFormat#NO_COLLECTION_FORMAT}. 3692 * <br>Cannot be <jk>null</jk>. 3693 * @return This object. 3694 */ 3695 public SELF oapiCollectionFormat(HttpPartCollectionFormat value) { 3696 serializers().forEach(OpenApiSerializer.Builder.class, x -> x.collectionFormat(value)); 3697 parsers().forEach(OpenApiParser.Builder.class, x -> x.collectionFormat(value)); 3698 partSerializer().builder(OpenApiSerializer.Builder.class, x -> x.collectionFormat(value)); 3699 partParser().builder(OpenApiParser.Builder.class, x -> x.collectionFormat(value)); 3700 return self(); 3701 } 3702 3703 /** 3704 * <i><l>OpenApiCommon</l> configuration property: </i> Default OpenAPI format for HTTP parts. 3705 * 3706 * <p> 3707 * Specifies the format to use for HTTP parts when not otherwise specified via {@link Schema#format()} for 3708 * the OpenAPI serializer and parser on this client. 3709 * 3710 * <h4 class='section'>Example:</h4> 3711 * <p class='bjava'> 3712 * <jc>// Create a REST client with UON part serialization and parsing.</jc> 3713 * RestClient <jv>client</jv> = RestClient 3714 * .<jsm>create</jsm>() 3715 * .oapiFormat(<jsf>UON</jsf>) 3716 * .build(); 3717 * 3718 * <jc>// Set a header with a value in UON format.</jc> 3719 * <jv>client</jv> 3720 * .get(<js>"/uri"</js>) 3721 * .header(<js>"Foo"</js>, <js>"bar baz"</js>) <jc>// Will be serialized as: 'bar baz'</jc> 3722 * .run(); 3723 * </p> 3724 * 3725 * <ul class='values javatree'> 3726 * <li class='jc'>{@link HttpPartFormat} 3727 * <ul> 3728 * <li class='jf'>{@link HttpPartFormat#UON UON} - UON notation (e.g. <js>"'foo bar'"</js>). 3729 * <li class='jf'>{@link HttpPartFormat#INT32 INT32} - Signed 32 bits. 3730 * <li class='jf'>{@link HttpPartFormat#INT64 INT64} - Signed 64 bits. 3731 * <li class='jf'>{@link HttpPartFormat#FLOAT FLOAT} - 32-bit floating point number. 3732 * <li class='jf'>{@link HttpPartFormat#DOUBLE DOUBLE} - 64-bit floating point number. 3733 * <li class='jf'>{@link HttpPartFormat#BYTE BYTE} - BASE-64 encoded characters. 3734 * <li class='jf'>{@link HttpPartFormat#BINARY BINARY} - Hexadecimal encoded octets (e.g. <js>"00FF"</js>). 3735 * <li class='jf'>{@link HttpPartFormat#BINARY_SPACED BINARY_SPACED} - Spaced-separated hexadecimal encoded octets (e.g. <js>"00 FF"</js>). 3736 * <li class='jf'>{@link HttpPartFormat#DATE DATE} - An <a href='http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14'>RFC3339 full-date</a>. 3737 * <li class='jf'>{@link HttpPartFormat#DATE_TIME DATE_TIME} - An <a href='http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14'>RFC3339 date-time</a>. 3738 * <li class='jf'>{@link HttpPartFormat#PASSWORD PASSWORD} - Used to hint UIs the input needs to be obscured. 3739 * <li class='jf'>{@link HttpPartFormat#NO_FORMAT NO_FORMAT} - (default) Not specified. 3740 * </ul> 3741 * </ul> 3742 * 3743 * <h4 class='section'>See Also:</h4><ul> 3744 * <li class='jm'>{@link org.apache.juneau.marshall.oapi.OpenApiSerializer.Builder#format(HttpPartFormat) OpenApiSerializer.Builder#format(HttpPartFormat)} 3745 * <li class='jm'>{@link org.apache.juneau.marshall.oapi.OpenApiParser.Builder#format(HttpPartFormat) OpenApiParser.Builder#format(HttpPartFormat)} 3746 * </ul> 3747 * 3748 * @param value 3749 * The new value for this property. 3750 * <br>The default value is {@link HttpPartFormat#NO_FORMAT}. 3751 * <br>Cannot be <jk>null</jk>. 3752 * @return This object. 3753 */ 3754 public SELF oapiFormat(HttpPartFormat value) { 3755 serializers().forEach(OpenApiSerializer.Builder.class, x -> x.format(value)); 3756 parsers().forEach(OpenApiParser.Builder.class, x -> x.format(value)); 3757 partSerializer().builder(OpenApiSerializer.Builder.class).ifPresent(x -> x.format(value)); 3758 partParser().builder(OpenApiParser.Builder.class).ifPresent(x -> x.format(value)); 3759 return self(); 3760 } 3761 3762 /** 3763 * Convenience method for specifying OpenAPI as the marshalling transmission media type. 3764 * 3765 * <p> 3766 * OpenAPI is a language that allows serialization to formats that use {@link HttpPartSchema} objects to describe their structure. 3767 * 3768 * <p> 3769 * {@link OpenApiSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 3770 * <ul> 3771 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 3772 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3773 * <li>Typically the {@link RestRequest#content(Object, HttpPartSchema)} method will be used to specify the body of the request with the 3774 * schema describing it's structure. 3775 * </ul> 3776 * <p> 3777 * {@link OpenApiParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 3778 * <ul> 3779 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 3780 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3781 * <li>Typically the {@link ResponseContent#schema(HttpPartSchema)} method will be used to specify the structure of the response body. 3782 * </ul> 3783 * <p> 3784 * <c>Accept</c> request header will be set to <js>"text/openapi"</js> unless overridden 3785 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 3786 * <p> 3787 * <c>Content-Type</c> request header will be set to <js>"text/openapi"</js> unless overridden 3788 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 3789 * <p> 3790 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 3791 * <ul> 3792 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 3793 * last-enabled language if the headers are not set. 3794 * </ul> 3795 * <p> 3796 * Identical to calling <c>serializer(OpenApiSerializer.<jk>class</jk>).parser(OpenApiParser.<jk>class</jk>)</c>. 3797 * 3798 * <h4 class='section'>Example:</h4> 3799 * <p class='bjava'> 3800 * <jc>// Construct a client that uses OpenAPI marshalling.</jc> 3801 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().openApi().build(); 3802 * </p> 3803 * 3804 * @return This object. 3805 */ 3806 public SELF openApi() { 3807 return serializer(OpenApiSerializer.class).parser(OpenApiParser.class); 3808 } 3809 3810 /** 3811 * <i><l>UonSerializer</l> configuration property: </i> Parameter format. 3812 * 3813 * <p> 3814 * Specifies the format of parameters when using the {@link UrlEncodingSerializer} to serialize Form Posts. 3815 * 3816 * <p> 3817 * Specifies the format to use for GET parameter keys and values. 3818 * 3819 * <h4 class='section'>Example:</h4> 3820 * <p class='bjava'> 3821 * <jc>// Create a REST client with URL-Encoded serializer that serializes values in plain-text format.</jc> 3822 * RestClient <jv>client</jv> = RestClient 3823 * .<jsm>create</jsm>() 3824 * .urlEnc() 3825 * .paramFormat(<jsf>PLAINTEXT</jsf>) 3826 * .build(); 3827 * 3828 * <jc>// An arbitrary data structure.</jc> 3829 * AMap <jv>map</jv> = AMap.<jsm>of</jsm>( 3830 * <js>"foo"</js>, <js>"bar"</js>, 3831 * <js>"baz"</js>, <jk>new</jk> String[]{<js>"qux"</js>, <js>"true"</js>, <js>"123"</js>} 3832 * ); 3833 * 3834 * <jc>// Request body will be serialized as: foo=bar,baz=qux,true,123</jc> 3835 * <jv>client</jv> 3836 * .post(<js>"/uri"</js>, <jv>map</jv>) 3837 * .run(); 3838 * </p> 3839 * 3840 * <ul class='values javatree'> 3841 * <li class='jf'>{@link ParamFormat#UON} (default) - Use UON notation for parameters. 3842 * <li class='jf'>{@link ParamFormat#PLAINTEXT} - Use plain text for parameters. 3843 * </ul> 3844 * 3845 * <h4 class='section'>See Also:</h4><ul> 3846 * <li class='jm'>{@link org.apache.juneau.marshall.uon.UonSerializer.Builder#paramFormat(ParamFormat) UonSerializer.Builder#paramFormat(ParamFormat)} 3847 * </ul> 3848 * 3849 * @param value The new value for this property. 3850 * <br>Cannot be <jk>null</jk>. 3851 * @return This object. 3852 */ 3853 public SELF paramFormat(ParamFormat value) { 3854 serializers().forEach(UonSerializer.Builder.class, x -> x.paramFormat(value)); 3855 return self(); 3856 } 3857 3858 /** 3859 * <i><l>UonSerializer</l> configuration property: </i> Parameter format. 3860 * 3861 * <p> 3862 * Specifies the format of parameters when using the {@link UrlEncodingSerializer} to serialize Form Posts. 3863 * 3864 * <p> 3865 * Specifies plaintext as the format to use for GET parameter keys and values. 3866 * 3867 * <h4 class='section'>Example:</h4> 3868 * <p class='bjava'> 3869 * <jc>// Create a REST client with URL-Encoded serializer that serializes values in plain-text format.</jc> 3870 * RestClient <jv>client</jv> = RestClient 3871 * .<jsm>create</jsm>() 3872 * .urlEnc() 3873 * .build(); 3874 * 3875 * <jc>// An arbitrary data structure.</jc> 3876 * AMap <jv>map</jv> = AMap.<jsm>of</jsm>( 3877 * <js>"foo"</js>, <js>"bar"</js>, 3878 * <js>"baz"</js>, <jk>new</jk> String[]{<js>"qux"</js>, <js>"true"</js>, <js>"123"</js>} 3879 * ); 3880 * 3881 * <jc>// Request body will be serialized as: foo=bar,baz=qux,true,123</jc> 3882 * <jv>client</jv> 3883 * .post(<js>"/uri"</js>, <jv>map</jv>) 3884 * .run(); 3885 * </p> 3886 * 3887 * <h4 class='section'>See Also:</h4><ul> 3888 * <li class='jm'>{@link org.apache.juneau.marshall.uon.UonSerializer.Builder#paramFormatPlain() UonSerializer.Builder#paramFormatPlain()} 3889 * </ul> 3890 * 3891 * @return This object. 3892 */ 3893 public SELF paramFormatPlain() { 3894 serializers().forEach(UonSerializer.Builder.class, UonSerializer.Builder::paramFormatPlain); 3895 return self(); 3896 } 3897 3898 /** 3899 * Parser. 3900 * 3901 * <p> 3902 * Associates the specified {@link Parser Parser} with the HTTP client. 3903 * 3904 * <p> 3905 * The parser is used to parse the HTTP response body into a POJO. 3906 * 3907 * <h4 class='section'>Notes:</h4><ul> 3908 * <li class='note'>When using this method that takes in a class, the parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 3909 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3910 * </ul> 3911 * 3912 * <h4 class='section'>Example:</h4> 3913 * <p class='bjava'> 3914 * <jc>// Create a client that uses JSON transport for response bodies.</jc> 3915 * RestClient <jv>client</jv> = RestClient 3916 * .<jsm>create</jsm>() 3917 * .parser(JsonParser.<jk>class</jk>) 3918 * .build(); 3919 * </p> 3920 * 3921 * @param value 3922 * The new value for this setting. 3923 * <br>The default value is {@link JsonParser#DEFAULT}. 3924 * @return This object. 3925 */ 3926 public SELF parser(Class<? extends Parser> value) { 3927 return parsers(value); 3928 } 3929 3930 /** 3931 * Parser. 3932 * 3933 * <p> 3934 * Associates the specified {@link Parser Parser} with the HTTP client. 3935 * 3936 * <p> 3937 * The parser is used to parse the HTTP response body into a POJO. 3938 * 3939 * <h4 class='section'>Notes:</h4><ul> 3940 * <li class='note'>When using this method that takes in a pre-instantiated parser, the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 3941 * bean context property setters (e.g. {@link #swaps(Class...)}) defined 3942 * on this builder class have no effect. 3943 * </ul> 3944 * 3945 * <h4 class='section'>Example:</h4> 3946 * <p class='bjava'> 3947 * <jc>// Create a client that uses a predefined JSON parser for response bodies.</jc> 3948 * RestClient <jv>client</jv> = RestClient 3949 * .<jsm>create</jsm>() 3950 * .parser(JsonParser.<jsf>DEFAULT</jsf>) 3951 * .build(); 3952 * </p> 3953 * 3954 * @param value 3955 * The new value for this setting. 3956 * <br>The default value is {@link JsonParser#DEFAULT}. 3957 * <br>Cannot be <jk>null</jk>. 3958 * @return This object. 3959 */ 3960 public SELF parser(Parser value) { 3961 return parsers(value); 3962 } 3963 3964 /** 3965 * Returns the parser group sub-builder. 3966 * 3967 * @return The parser group sub-builder. 3968 */ 3969 public final ParserSet.Builder parsers() { 3970 if (parsers == null) 3971 parsers = createParsers(); 3972 return parsers; 3973 } 3974 3975 /** 3976 * Parsers. 3977 * 3978 * <p> 3979 * Associates the specified {@link Parser Parsers} with the HTTP client. 3980 * 3981 * <p> 3982 * The parsers are used to parse the HTTP response body into a POJO. 3983 * 3984 * <p> 3985 * The parser that best matches the <c>Accept</c> header will be used to parse the response body. 3986 * <br>If no <c>Accept</c> header is specified, the first parser in the list will be used. 3987 * 3988 * <h4 class='section'>Notes:</h4><ul> 3989 * <li class='note'>When using this method that takes in classes, the parsers can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 3990 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 3991 * </ul> 3992 * 3993 * <h4 class='section'>Example:</h4> 3994 * <p class='bjava'> 3995 * <jc>// Create a client that uses JSON and XML transport for response bodies.</jc> 3996 * RestClient <jv>client</jv> = RestClient 3997 * .<jsm>create</jsm>() 3998 * .parser(JsonParser.<jk>class</jk>, XmlParser.<jk>class</jk>) 3999 * .build(); 4000 * </p> 4001 * 4002 * @param value 4003 * The new value for this setting. 4004 * <br>The default value is {@link JsonParser#DEFAULT}. 4005 * @return This object. 4006 */ 4007 public SELF parsers(Class<? extends Parser>...value) { 4008 reqnns("value", value); 4009 parsers().add(value); 4010 return self(); 4011 } 4012 4013 /** 4014 * Parsers. 4015 * 4016 * <p> 4017 * Associates the specified {@link Parser Parsers} with the HTTP client. 4018 * 4019 * <p> 4020 * The parsers are used to parse the HTTP response body into a POJO. 4021 * 4022 * <p> 4023 * The parser that best matches the <c>Accept</c> header will be used to parse the response body. 4024 * <br>If no <c>Accept</c> header is specified, the first parser in the list will be used. 4025 * 4026 * <h4 class='section'>Notes:</h4><ul> 4027 * <li class='note'>When using this method that takes in pre-instantiated parsers, the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 4028 * bean context property setters (e.g. {@link #swaps(Class...)}) defined 4029 * on this builder class have no effect. 4030 * </ul> 4031 * 4032 * <h4 class='section'>Example:</h4> 4033 * <p class='bjava'> 4034 * <jc>// Create a client that uses JSON and XML transport for response bodies.</jc> 4035 * RestClient <jv>client</jv> = RestClient 4036 * .<jsm>create</jsm>() 4037 * .parser(JsonParser.<jsf>DEFAULT</jsf>, XmlParser.<jsf>DEFAULT</jsf>) 4038 * .build(); 4039 * </p> 4040 * 4041 * @param value 4042 * The new value for this setting. 4043 * <br>The default value is {@link JsonParser#DEFAULT}. 4044 * @return This object. 4045 */ 4046 public SELF parsers(Parser...value) { 4047 reqnns("value", value); 4048 parsers().add(value); 4049 return self(); 4050 } 4051 4052 /** 4053 * Returns the part parser sub-builder. 4054 * 4055 * @return The part parser sub-builder. 4056 */ 4057 public final HttpPartParser.Creator partParser() { 4058 if (partParser == null) 4059 partParser = createPartParser(); 4060 return partParser; 4061 } 4062 4063 /** 4064 * Part parser. 4065 * 4066 * <p> 4067 * The parser to use for parsing POJOs from form data, query parameters, headers, and path variables. 4068 * 4069 * <p> 4070 * The default part parser is {@link OpenApiParser} which allows for schema-driven marshalling. 4071 * 4072 * <h4 class='section'>Example:</h4> 4073 * <p class='bjava'> 4074 * <jc>// Create a client that uses UON format by default for incoming HTTP parts.</jc> 4075 * RestClient <jv>client</jv> = RestClient 4076 * .<jsm>create</jsm>() 4077 * .partParser(UonParser.<jk>class</jk>) 4078 * .build(); 4079 * </p> 4080 * 4081 * @param value 4082 * The new value for this setting. 4083 * <br>The default value is {@link OpenApiParser}. 4084 * <br>Cannot be <jk>null</jk>. 4085 * @return This object. 4086 */ 4087 public SELF partParser(Class<? extends HttpPartParser> value) { 4088 partParser().type(reqnn("value", value)); 4089 return self(); 4090 } 4091 4092 /** 4093 * Part parser. 4094 * 4095 * <p> 4096 * The parser to use for parsing POJOs from form data, query parameters, headers, and path variables. 4097 * 4098 * <p> 4099 * The default part parser is {@link OpenApiParser} which allows for schema-driven marshalling. 4100 * 4101 * <h4 class='section'>Example:</h4> 4102 * <p class='bjava'> 4103 * <jc>// Create a client that uses UON format by default for incoming HTTP parts.</jc> 4104 * RestClient <jv>client</jv> = RestClient 4105 * .<jsm>create</jsm>() 4106 * .partParser(UonParser.<jsf>DEFAULT</jsf>) 4107 * .build(); 4108 * </p> 4109 * 4110 * @param value 4111 * The new value for this setting. 4112 * <br>The default value is {@link OpenApiParser}. 4113 * <br>Cannot be <jk>null</jk>. 4114 * @return This object. 4115 */ 4116 public SELF partParser(HttpPartParser value) { 4117 partParser().impl(reqnn("value", value)); 4118 return self(); 4119 } 4120 4121 /** 4122 * Returns the part serializer sub-builder. 4123 * 4124 * @return The part serializer sub-builder. 4125 */ 4126 public final HttpPartSerializer.Creator partSerializer() { 4127 if (partSerializer == null) 4128 partSerializer = createPartSerializer(); 4129 return partSerializer; 4130 } 4131 4132 /** 4133 * Part serializer. 4134 * 4135 * <p> 4136 * The serializer to use for serializing POJOs in form data, query parameters, headers, and path variables. 4137 * 4138 * <p> 4139 * The default part serializer is {@link OpenApiSerializer} which allows for schema-driven marshalling. 4140 * 4141 * <h4 class='section'>Example:</h4> 4142 * <p class='bjava'> 4143 * <jc>// Create a client that uses UON format by default for outgoing HTTP parts.</jc> 4144 * RestClient <jv>client</jv> = RestClient 4145 * .<jsm>create</jsm>() 4146 * .partSerializer(UonSerializer.<jk>class</jk>) 4147 * .build(); 4148 * </p> 4149 * 4150 * @param value 4151 * The new value for this setting. 4152 * <br>The default value is {@link OpenApiSerializer}. 4153 * <br>Cannot be <jk>null</jk>. 4154 * @return This object. 4155 */ 4156 public SELF partSerializer(Class<? extends HttpPartSerializer> value) { 4157 partSerializer().type(reqnn("value", value)); 4158 return self(); 4159 } 4160 4161 /** 4162 * Part serializer. 4163 * 4164 * <p> 4165 * The serializer to use for serializing POJOs in form data, query parameters, headers, and path variables. 4166 * 4167 * <p> 4168 * The default part serializer is {@link OpenApiSerializer} which allows for schema-driven marshalling. 4169 * 4170 * <h4 class='section'>Example:</h4> 4171 * <p class='bjava'> 4172 * <jc>// Create a client that uses UON format by default for outgoing HTTP parts.</jc> 4173 * RestClient <jv>client</jv> = RestClient 4174 * .<jsm>create</jsm>() 4175 * .partSerializer(UonSerializer.<jsf>DEFAULT</jsf>) 4176 * .build(); 4177 * </p> 4178 * 4179 * @param value 4180 * The new value for this setting. 4181 * <br>The default value is {@link OpenApiSerializer}. 4182 * <br>Cannot be <jk>null</jk>. 4183 * @return This object. 4184 */ 4185 public SELF partSerializer(HttpPartSerializer value) { 4186 partSerializer().impl(reqnn("value", value)); 4187 return self(); 4188 } 4189 4190 /** 4191 * Returns the builder for the list of path data parameters that get applied to all requests created by this builder. 4192 * 4193 * <p> 4194 * This is the primary method for accessing the path data parameter list. 4195 * On first call, the builder is created via the method {@link #createFormData()}. 4196 * 4197 * <h4 class='section'>Example:</h4> 4198 * <p class='bjava'> 4199 * <jc>// Create a client that uses "bar" for the "{foo}" path variable on every request.</jc> 4200 * RestClient.Builder<?> <jv>builder</jv> = RestClient.<jsm>create</jsm>(); 4201 * <jv>builder</jv>.pathData().setDefault(<js>"foo"</js>, <js>"bar"</js>)); 4202 * RestClient <jv>client</jv> = <jv>builder</jv>.build(); 4203 * </p> 4204 * 4205 * <p> 4206 * The following convenience methods are also provided for updating the parameters: 4207 * <ul> 4208 * <li class='jm'>{@link #pathData(NameValuePair...)} 4209 * <li class='jm'>{@link #pathDataDefault(NameValuePair...)} 4210 * <li class='jm'>{@link #pathData(String,String)} 4211 * <li class='jm'>{@link #pathData(String,Supplier)} 4212 * </ul> 4213 * 4214 * @return The form data list builder. 4215 */ 4216 public final PartList pathData() { 4217 if (pathData == null) 4218 pathData = createPathData(); 4219 return pathData; 4220 } 4221 4222 /** 4223 * Sets multiple path parameters on all requests. 4224 * 4225 * <h4 class='section'>Example:</h4> 4226 * <p class='bjava'> 4227 * <jk>import static</jk> org.apache.juneau.http.HttpParts.*; 4228 * 4229 * RestClient <jv>client</jv> = RestClient 4230 * .<jsm>create</jsm>() 4231 * .pathData( 4232 * <jsm>stringPart</jsm>(<js>"foo"</js>, <js>"bar"</js>), 4233 * <jsm>booleanPart</jsm>(<js>"baz"</js>, <jk>true</jk>) 4234 * ) 4235 * .build(); 4236 * </p> 4237 * 4238 * <p> 4239 * This is a shortcut for calling <c>pathData().append(<jv>parts</jv>)</c>. 4240 * 4241 * @param parts 4242 * The path parameters. 4243 * <br>Can contain <jk>null</jk> values (ignored). 4244 * @return This object. 4245 * @see #pathData() 4246 */ 4247 public SELF pathData(NameValuePair...parts) { 4248 pathData().append(parts); 4249 return self(); 4250 } 4251 4252 /** 4253 * Appends a path parameter to all request bodies. 4254 * 4255 * <h4 class='section'>Example:</h4> 4256 * <p class='bjava'> 4257 * RestClient <jv>client</jv> = RestClient 4258 * .<jsm>create</jsm>() 4259 * .pathData(<js>"foo"</js>, <js>"bar"</js>) 4260 * .build(); 4261 * </p> 4262 * 4263 * <p> 4264 * This is a shortcut for calling <c>pathData().append(<jv>name</jv>,<jv>value</jv>)</c>. 4265 * 4266 * @param name The parameter name. 4267 * <br>Cannot be <jk>null</jk>. 4268 * @param value The parameter value. 4269 * <br>Can be <jk>null</jk> (null value will be serialized). 4270 * @return This object. 4271 * @see #pathData() 4272 */ 4273 public SELF pathData(String name, String value) { 4274 pathData().append(name, value); 4275 return self(); 4276 } 4277 4278 /** 4279 * Sets a path parameter with a dynamic value to all request bodies. 4280 * 4281 * <h4 class='section'>Example:</h4> 4282 * <p class='bjava'> 4283 * RestClient <jv>client</jv> = RestClient 4284 * .<jsm>create</jsm>() 4285 * .pathData(<js>"foo"</js>, ()-><js>"bar"</js>) 4286 * .build(); 4287 * </p> 4288 * 4289 * <p> 4290 * This is a shortcut for calling <c>pathData().append(<jv>name</jv>,<jv>value</jv>)</c>. 4291 * 4292 * @param name The parameter name. 4293 * <br>Cannot be <jk>null</jk>. 4294 * @param value The parameter value supplier. 4295 * <br>Can be <jk>null</jk> (null value will be serialized). 4296 * @return This object. 4297 * @see #pathData() 4298 */ 4299 public SELF pathData(String name, Supplier<String> value) { 4300 pathData().set(name, value); 4301 return self(); 4302 } 4303 4304 /** 4305 * Sets default path parameter values. 4306 * 4307 * <p> 4308 * Uses default values for specified parameters if not otherwise specified on the outgoing requests. 4309 * 4310 * <h4 class='section'>Example:</h4> 4311 * <p class='bjava'> 4312 * RestClient <jv>client</jv> = RestClient 4313 * .<jsm>create</jsm>() 4314 * .pathDataDefault(<jsm>stringPart</jsm>(<js>"foo"</js>, ()-><js>"bar"</js>)); 4315 * .build(); 4316 * </p> 4317 * 4318 * <p> 4319 * This is a shortcut for calling <c>pathData().setDefault(<jv>parts</jv>)</c>. 4320 * 4321 * @param parts The parts. 4322 * <br>Can contain <jk>null</jk> values (ignored). 4323 * @return This object. 4324 * @see #pathData() 4325 */ 4326 public SELF pathDataDefault(NameValuePair...parts) { 4327 pathData().setDefault(parts); 4328 return self(); 4329 } 4330 4331 /** 4332 * Convenience method for specifying Plain Text as the marshalling transmission media type. 4333 * 4334 * <p> 4335 * Plain text marshalling typically only works on simple POJOs that can be converted to and from strings using 4336 * swaps, swap methods, etc... 4337 * 4338 * <p> 4339 * {@link PlainTextSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 4340 * <ul> 4341 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 4342 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 4343 * </ul> 4344 * <p> 4345 * {@link PlainTextParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 4346 * <ul> 4347 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 4348 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 4349 * </ul> 4350 * <p> 4351 * <c>Accept</c> request header will be set to <js>"text/plain"</js> unless overridden 4352 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 4353 * <p> 4354 * <c>Content-Type</c> request header will be set to <js>"text/plain"</js> unless overridden 4355 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 4356 * <p> 4357 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 4358 * <ul> 4359 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 4360 * last-enabled language if the headers are not set. 4361 * </ul> 4362 * <p> 4363 * Identical to calling <c>serializer(PlainTextSerializer.<jk>class</jk>).parser(PlainTextParser.<jk>class</jk>)</c>. 4364 * 4365 * <h4 class='section'>Example:</h4> 4366 * <p class='bjava'> 4367 * <jc>// Construct a client that uses Plain Text marshalling.</jc> 4368 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().plainText().build(); 4369 * </p> 4370 * 4371 * @return This object. 4372 */ 4373 public SELF plainText() { 4374 return serializer(PlainTextSerializer.class).parser(PlainTextParser.class); 4375 } 4376 4377 /** 4378 * When called, the {@link #createConnectionManager()} method will return a {@link PoolingHttpClientConnectionManager} 4379 * instead of a {@link BasicHttpClientConnectionManager}. 4380 * 4381 * <h4 class='section'>Example:</h4> 4382 * <p class='bjava'> 4383 * <jc>// Construct a client that uses pooled connections.</jc> 4384 * RestClient <jv>client</jv> = RestClient 4385 * .<jsm>create</jsm>() 4386 * .pooled() 4387 * .build(); 4388 * </p> 4389 * 4390 * @return This object. 4391 */ 4392 public SELF pooled() { 4393 this.pooled = true; 4394 return self(); 4395 } 4396 4397 /** 4398 * Assigns default proxy value. 4399 * 4400 * <h4 class='section'>Notes:</h4><ul> 4401 * <li class='note'>This value can be overridden by the {@link #routePlanner(HttpRoutePlanner)} method. 4402 * <li class='warn'>Through a proxy, the SSRF guard's pin-on-connect would check the proxy's address rather than 4403 * the target's, so an SSRF-guard-active {@code @Remote} call (one without the 4404 * {@link #allowPrivateUrls(boolean) allowPrivateUrls} opt-in) on a proxy route is refused. This applies to any 4405 * proxy route, including one chosen by a {@link #routePlanner(HttpRoutePlanner) route planner} or the proxy 4406 * system properties ({@link #useSystemProperties()}). Ordinary requests are unaffected. 4407 * </ul> 4408 * 4409 * @param proxy New property value. 4410 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 4411 * @return This object. 4412 * @see HttpClientBuilder#setProxy(HttpHost) 4413 */ 4414 public SELF proxy(HttpHost proxy) { 4415 httpClientBuilder().setProxy(proxy); 4416 return self(); 4417 } 4418 4419 /** 4420 * Assigns {@link AuthenticationStrategy} instance for proxy authentication. 4421 * 4422 * @param proxyAuthStrategy New property value. 4423 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 4424 * @return This object. 4425 * @see HttpClientBuilder#setProxyAuthenticationStrategy(AuthenticationStrategy) 4426 */ 4427 public SELF proxyAuthenticationStrategy(AuthenticationStrategy proxyAuthStrategy) { 4428 httpClientBuilder().setProxyAuthenticationStrategy(proxyAuthStrategy); 4429 return self(); 4430 } 4431 4432 /** 4433 * Assigns file containing public suffix matcher. 4434 * 4435 * <h4 class='section'>Notes:</h4><ul> 4436 * <li class='note'>Instances of this class can be created with {@link PublicSuffixMatcherLoader}. 4437 * <li class='note'>It is used for cookies and, in both pools of the connection manager the default 4438 * {@link #createConnectionManager()} builds, by the default hostname verifier (one is used unless 4439 * {@link #sslHostnameVerifier(HostnameVerifier)} or {@link #sslSocketFactory(LayeredConnectionSocketFactory)} 4440 * is set). 4441 * </ul> 4442 * 4443 * @param publicSuffixMatcher New property value. 4444 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 4445 * @return This object. 4446 * @see HttpClientBuilder#setPublicSuffixMatcher(PublicSuffixMatcher) 4447 */ 4448 public SELF publicSuffixMatcher(PublicSuffixMatcher publicSuffixMatcher) { 4449 this.publicSuffixMatcher = publicSuffixMatcher; 4450 httpClientBuilder().setPublicSuffixMatcher(publicSuffixMatcher); 4451 return self(); 4452 } 4453 4454 /** 4455 * Returns the builder for the list of query parameters that get applied to all requests created by this builder. 4456 * 4457 * <p> 4458 * This is the primary method for accessing the query parameter list. 4459 * On first call, the builder is created via the method {@link #createQueryData()}. 4460 * 4461 * <h4 class='section'>Example:</h4> 4462 * <p class='bjava'> 4463 * <jc>// Create a client that adds a "foo=bar" query parameter on every request.</jc> 4464 * RestClient.Builder<?> <jv>builder</jv> = RestClient.<jsm>create</jsm>(); 4465 * <jv>builder</jv>.queryData().setDefault(<js>"foo"</js>, <js>"bar"</js>)); 4466 * RestClient <jv>client</jv> = <jv>builder</jv>.build(); 4467 * </p> 4468 * 4469 * <p> 4470 * The following convenience methods are also provided for updating the parameters: 4471 * <ul> 4472 * <li class='jm'>{@link #queryData(NameValuePair...)} 4473 * <li class='jm'>{@link #queryDataDefault(NameValuePair...)} 4474 * <li class='jm'>{@link #queryData(String,String)} 4475 * <li class='jm'>{@link #queryData(String,Supplier)} 4476 * </ul> 4477 * 4478 * @return The query data list builder. 4479 */ 4480 public final PartList queryData() { 4481 if (queryData == null) 4482 queryData = createQueryData(); 4483 return queryData; 4484 } 4485 4486 /** 4487 * Appends multiple query parameters to the URI of all requests. 4488 * 4489 * <h4 class='section'>Example:</h4> 4490 * <p class='bjava'> 4491 * <jk>import static</jk> org.apache.juneau.http.HttpParts.*; 4492 * 4493 * RestClient <jv>client</jv> = RestClient 4494 * .<jsm>create</jsm>() 4495 * .queryData( 4496 * <jsm>stringPart</jsm>(<js>"foo"</js>, <js>"bar"</js>), 4497 * <jsm>booleanPart</jsm>(<js>"baz"</js>, <jk>true</jk>) 4498 * ) 4499 * .build(); 4500 * </p> 4501 * 4502 * <p> 4503 * This is a shortcut for calling <c>queryData().append(<jv>parts</jv>)</c>. 4504 * 4505 * @param parts 4506 * The query parameters. 4507 * <br>Can contain <jk>null</jk> values (ignored). 4508 * @return This object. 4509 * @see #queryData() 4510 */ 4511 public SELF queryData(NameValuePair...parts) { 4512 queryData().append(parts); 4513 return self(); 4514 } 4515 4516 /** 4517 * Appends a query parameter to the URI. 4518 * 4519 * <h4 class='section'>Example:</h4> 4520 * <p class='bjava'> 4521 * RestClient <jv>client</jv> = RestClient 4522 * .<jsm>create</jsm>() 4523 * .queryData(<js>"foo"</js>, <js>"bar"</js>) 4524 * .build(); 4525 * </p> 4526 * 4527 * <p> 4528 * This is a shortcut for calling <c>queryData().append(<jv>name</jv>,<jv>value</jv>)</c>. 4529 * 4530 * @param name The parameter name. 4531 * <br>Cannot be <jk>null</jk>. 4532 * @param value The parameter value. 4533 * <br>Can be <jk>null</jk> (null value will be serialized). 4534 * @return This object. 4535 * @see #queryData() 4536 */ 4537 public SELF queryData(String name, String value) { 4538 queryData().append(name, value); 4539 return self(); 4540 } 4541 4542 /** 4543 * Appends a query parameter with a dynamic value to the URI. 4544 * 4545 * <h4 class='section'>Example:</h4> 4546 * <p class='bjava'> 4547 * RestClient <jv>client</jv> = RestClient 4548 * .<jsm>create</jsm>() 4549 * .queryData(<js>"foo"</js>, ()-><js>"bar"</js>) 4550 * .build(); 4551 * </p> 4552 * 4553 * <p> 4554 * This is a shortcut for calling <c>queryData().append(<jv>name</jv>,<jv>value</jv>)</c>. 4555 * 4556 * @param name The parameter name. 4557 * <br>Cannot be <jk>null</jk>. 4558 * @param value The parameter value supplier. 4559 * <br>Can be <jk>null</jk> (null value will be serialized). 4560 * @return This object. 4561 * @see #queryData() 4562 */ 4563 public SELF queryData(String name, Supplier<String> value) { 4564 queryData().append(name, value); 4565 return self(); 4566 } 4567 4568 /** 4569 * Sets default query parameter values. 4570 * 4571 * <p> 4572 * Uses default values for specified parameters if not otherwise specified on the outgoing requests. 4573 * 4574 * <h4 class='section'>Example:</h4> 4575 * <p class='bjava'> 4576 * RestClient <jv>client</jv> = RestClient 4577 * .<jsm>create</jsm>() 4578 * .queryDataDefault(<jsm>stringPart</jsm>(<js>"foo"</js>, ()-><js>"bar"</js>)); 4579 * .build(); 4580 * </p> 4581 * 4582 * <p> 4583 * This is a shortcut for calling <c>queryData().setDefault(<jv>parts</jv>)</c>. 4584 * 4585 * @param parts The parts. 4586 * <br>Can contain <jk>null</jk> values (ignored). 4587 * @return This object. 4588 * @see #queryData() 4589 */ 4590 public SELF queryDataDefault(NameValuePair...parts) { 4591 queryData().setDefault(parts); 4592 return self(); 4593 } 4594 4595 /** 4596 * Sets a default query parameter with serializer session options (UON map) for all requests. 4597 * 4598 * <p> 4599 * This is a shortcut for <c>queryDataDefault(stringPart({@link RestSharedConstants#QUERY_juneauSerializerOptions}, <jv>uon</jv>))</c>. 4600 * 4601 * @param uon 4602 * Serializer session options in UON form. 4603 * <br>Can be <jk>null</jk> (default is not set by this method). 4604 * @return This object. 4605 */ 4606 public SELF serializerSessionOptionsQueryDefault(String uon) { 4607 if (uon != null) 4608 queryDataDefault(stringPart(QUERY_juneauSerializerOptions, uon)); 4609 return self(); 4610 } 4611 4612 /** 4613 * Sets a default query parameter with parser session options (UON map) for all requests. 4614 * 4615 * <p> 4616 * This is a shortcut for <c>queryDataDefault(stringPart({@link RestSharedConstants#QUERY_juneauParserOptions}, <jv>uon</jv>))</c>. 4617 * 4618 * @param uon 4619 * Parser session options in UON form. 4620 * <br>Can be <jk>null</jk> (default is not set by this method). 4621 * @return This object. 4622 */ 4623 public SELF parserSessionOptionsQueryDefault(String uon) { 4624 if (uon != null) 4625 queryDataDefault(stringPart(QUERY_juneauParserOptions, uon)); 4626 return self(); 4627 } 4628 4629 /** 4630 * Convenience for {@link #serializerSessionOptionsQueryDefault(String)} using {@link Uon#of(Object)}. 4631 * 4632 * @param properties 4633 * Property names and values for serializer session options. 4634 * <br>Can be <jk>null</jk> (treated as an empty map). 4635 * @return This object. 4636 */ 4637 public SELF serializerSessionOptionsQueryDefault(Map<String,?> properties) { 4638 try { 4639 return serializerSessionOptionsQueryDefault(isEmpty(properties) ? null : Uon.of(properties)); 4640 } catch (SerializeException e) { 4641 throw rex(e, "Could not serialize serializer session options query default"); 4642 } 4643 } 4644 4645 /** 4646 * Convenience for {@link #parserSessionOptionsQueryDefault(String)} using {@link Uon#of(Object)}. 4647 * 4648 * @param properties 4649 * Property names and values for parser session options. 4650 * <br>Can be <jk>null</jk> (treated as an empty map). 4651 * @return This object. 4652 */ 4653 public SELF parserSessionOptionsQueryDefault(Map<String,?> properties) { 4654 try { 4655 return parserSessionOptionsQueryDefault(isEmpty(properties) ? null : Uon.of(properties)); 4656 } catch (SerializeException e) { 4657 throw rex(e, "Could not serialize parser session options query default"); 4658 } 4659 } 4660 4661 /** 4662 * <i><l>WriterSerializer</l> configuration property: </i> Quote character. 4663 * 4664 * <p> 4665 * Specifies the character to use for quoting attributes and values. 4666 * 4667 * <h4 class='section'>Notes:</h4><ul> 4668 * <li class='note'>This setting does not apply to the RDF serializers. 4669 * </ul> 4670 * 4671 * <h4 class='section'>Example:</h4> 4672 * <p class='bjava'> 4673 * <jc>// Create a REST client with JSON serializer that uses single quotes.</jc> 4674 * RestClient <jv>client</jv> = RestClient 4675 * .<jsm>create</jsm>() 4676 * .json() 4677 * .quoteChar(<js>'\''</js>) 4678 * .build(); 4679 * 4680 * <jc>// A bean with a single property</jc> 4681 * <jk>public class</jk> MyBean { 4682 * <jk>public</jk> String <jf>foo</jf> = <js>"bar"</js>; 4683 * } 4684 * 4685 * <jc>// Request body will contain: {'foo':'bar'}</jc> 4686 * <jv>client</jv> 4687 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 4688 * .run(); 4689 * </p> 4690 * 4691 * <h4 class='section'>See Also:</h4><ul> 4692 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.WriterSerializer.Builder#quoteChar(char) WriterSerializer.Builder#quoteChar(char)} 4693 * </ul> 4694 * 4695 * @param value 4696 * The new value for this property. 4697 * <br>The default is <js>'"'</js>. 4698 * @return This object. 4699 */ 4700 public SELF quoteChar(char value) { 4701 serializers().forEachWS(x -> x.quoteChar(value)); 4702 return self(); 4703 } 4704 4705 /** 4706 * Assigns {@link RedirectStrategy} instance. 4707 * 4708 * <h4 class='section'>Notes:</h4><ul> 4709 * <li class='note'>This value can be overridden by the {@link #disableRedirectHandling()} method. 4710 * </ul> 4711 * 4712 * @param redirectStrategy New property value. 4713 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 4714 * @return This object. 4715 * @see HttpClientBuilder#setRedirectStrategy(RedirectStrategy) 4716 */ 4717 public SELF redirectStrategy(RedirectStrategy redirectStrategy) { 4718 httpClientBuilder().setRedirectStrategy(redirectStrategy); 4719 return self(); 4720 } 4721 4722 /** 4723 * Assigns {@link HttpRequestExecutor} instance. 4724 * 4725 * @param requestExec New property value. 4726 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 4727 * @return This object. 4728 * @see HttpClientBuilder#setRequestExecutor(HttpRequestExecutor) 4729 */ 4730 public SELF requestExecutor(HttpRequestExecutor requestExec) { 4731 httpClientBuilder().setRequestExecutor(requestExec); 4732 return self(); 4733 } 4734 4735 /** 4736 * Assigns {@link HttpRequestRetryHandler} instance. 4737 * 4738 * <h4 class='section'>Notes:</h4><ul> 4739 * <li class='note'>This value can be overridden by the {@link #disableAutomaticRetries()} method. 4740 * </ul> 4741 * 4742 * @param retryHandler New property value. 4743 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 4744 * @return This object. 4745 * @see HttpClientBuilder#setRetryHandler(HttpRequestRetryHandler) 4746 */ 4747 public SELF retryHandler(HttpRequestRetryHandler retryHandler) { 4748 httpClientBuilder().setRetryHandler(retryHandler); 4749 return self(); 4750 } 4751 4752 /** 4753 * <i><l>RestClient</l> configuration property: </i> Root URI. 4754 * 4755 * <p> 4756 * When set, relative URI strings passed in through the various rest call methods (e.g. {@link RestClient#get(Object)} 4757 * will be prefixed with the specified root. 4758 * <br>This root URI is ignored on those methods if you pass in a {@link URL}, {@link URI}, or an absolute URI string. 4759 * 4760 * <h4 class='section'>Example:</h4> 4761 * <p class='bjava'> 4762 * <jc>// Create a client that uses UON format by default for HTTP parts.</jc> 4763 * RestClient <jv>client</jv> = RestClient 4764 * .<jsm>create</jsm>() 4765 * .rootUrl(<js>"http://localhost:10000/foo"</js>) 4766 * .build(); 4767 * 4768 * Bar <jv>bar</jv> = <jv>client</jv> 4769 * .get(<js>"/bar"</js>) <jc>// Relative to http://localhost:10000/foo</jc> 4770 * .run() 4771 * .getContent().as(Bar.<jk>class</jk>); 4772 * </p> 4773 * 4774 * @param value 4775 * The root URI to prefix to relative URI strings. 4776 * <br>Trailing slashes are trimmed. 4777 * <br>Usually a <c>String</c> but you can also pass in <c>URI</c> and <c>URL</c> objects as well. 4778 * <br>Can be <jk>null</jk> (no root URL will be set). 4779 * @return This object. 4780 */ 4781 public SELF rootUrl(Object value) { 4782 var s = s(value); 4783 if (ine(s)) 4784 s = s.replaceAll("\\/$", ""); 4785 if (isEmpty(s)) 4786 rootUrl = null; 4787 else if (s.indexOf("://") == -1) 4788 throw rex("Invalid rootUrl value: '%s'. Must be a valid absolute URL.", value); 4789 else { 4790 final var url = s; 4791 rootUrl = () -> url; 4792 } 4793 return self(); 4794 } 4795 4796 /** 4797 * Sets the root URL using a supplier, allowing the URL to be computed dynamically at request time. 4798 * 4799 * <p> 4800 * The supplier is called on every request, so the URL can change between requests. 4801 * No build-time validation is performed; invalid values will surface as errors when requests are made. 4802 * 4803 * <p> 4804 * Three common patterns are supported: 4805 * <ul> 4806 * <li> 4807 * <b>Swappable reference</b> — Use an {@link AtomicReference AtomicReference} 4808 * when you need to point the client at a different host at any time: 4809 * <p class='bjava'> 4810 * AtomicReference<String> <jv>urlRef</jv> = <jk>new</jk> AtomicReference<>(<js>"https://host1"</js>); 4811 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().rootUrl(<jv>urlRef</jv>::get).build(); 4812 * 4813 * <jc>// Switch to a different host at runtime.</jc> 4814 * <jv>urlRef</jv>.set(<js>"https://host2"</js>); 4815 * </p> 4816 * <li> 4817 * <b>Refreshable cached value</b> — Use {@link Memoizer Memoizer} 4818 * (via {@link Suppliers#memoizer(Supplier) Suppliers.memoizer()}) 4819 * when computing the URL is expensive (e.g. service discovery) and you want it cached until explicitly refreshed: 4820 * <p class='bjava'> 4821 * Memoizer<String> <jv>url</jv> = <jsm>memoizer</jsm>(() -> serviceDiscovery.<jsm>findUrl</jsm>(<js>"my-service"</js>)); 4822 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().rootUrl(<jv>url</jv>).build(); 4823 * 4824 * <jc>// Force re-evaluation on the next request (e.g. after a failover).</jc> 4825 * <jv>url</jv>.reset(); 4826 * </p> 4827 * <li> 4828 * <b>Purely dynamic</b> — Use a plain lambda when the URL must be re-evaluated on every request: 4829 * <p class='bjava'> 4830 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().rootUrl(() -> config.<jsm>getRootUrl</jsm>()).build(); 4831 * </p> 4832 * </ul> 4833 * 4834 * @param value 4835 * A supplier that returns the root URI to prefix to relative URI strings. 4836 * <br>Can be <jk>null</jk> (no root URL will be set). 4837 * @return This object. 4838 */ 4839 public SELF rootUrl(Supplier<String> value) { 4840 rootUrl = value; 4841 return self(); 4842 } 4843 4844 /** 4845 * Assigns {@link HttpRoutePlanner} instance. 4846 * 4847 * @param routePlanner New property value. 4848 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 4849 * @return This object. 4850 * @see HttpClientBuilder#setRoutePlanner(HttpRoutePlanner) 4851 */ 4852 public SELF routePlanner(HttpRoutePlanner routePlanner) { 4853 httpClientBuilder().setRoutePlanner(routePlanner); 4854 return self(); 4855 } 4856 4857 /** 4858 * Assigns {@link SchemePortResolver} instance. 4859 * 4860 * @param schemePortResolver New property value. 4861 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 4862 * @return This object. 4863 * @see HttpClientBuilder#setSchemePortResolver(SchemePortResolver) 4864 */ 4865 public SELF schemePortResolver(SchemePortResolver schemePortResolver) { 4866 httpClientBuilder().setSchemePortResolver(schemePortResolver); 4867 return self(); 4868 } 4869 4870 /** 4871 * Serializer. 4872 * 4873 * <p> 4874 * Associates the specified {@link Serializer Serializer} with the HTTP client. 4875 * 4876 * <p> 4877 * The serializer is used to serialize POJOs into the HTTP request body. 4878 * 4879 * <h4 class='section'>Notes:</h4><ul> 4880 * <li class='note'>When using this method that takes in a class, the serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 4881 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 4882 * </ul> 4883 * 4884 * <h4 class='section'>Example:</h4> 4885 * <p class='bjava'> 4886 * <jc>// Create a client that uses JSON transport for request bodies.</jc> 4887 * RestClient <jv>client</jv> = RestClient 4888 * .<jsm>create</jsm>() 4889 * .serializer(JsonSerializer.<jk>class</jk>) 4890 * .sortCollections() <jc>// Sort any collections being serialized.</jc> 4891 * .build(); 4892 * </p> 4893 * 4894 * @param value 4895 * The new value for this setting. 4896 * <br>The default is {@link JsonSerializer}. 4897 * @return This object. 4898 */ 4899 public SELF serializer(Class<? extends Serializer> value) { 4900 return serializers(value); 4901 } 4902 4903 /** 4904 * Serializer. 4905 * 4906 * <p> 4907 * Associates the specified {@link Serializer Serializer} with the HTTP client. 4908 * 4909 * <p> 4910 * The serializer is used to serialize POJOs into the HTTP request body. 4911 * 4912 * <h4 class='section'>Notes:</h4><ul> 4913 * <li class='note'>When using this method that takes in a pre-instantiated serializer, the serializer property setters (e.g. {@link #sortCollections()}) or 4914 * bean context property setters (e.g. {@link #swaps(Class...)}) defined 4915 * on this builder class have no effect. 4916 * </ul> 4917 * 4918 * <h4 class='section'>Example:</h4> 4919 * <p class='bjava'> 4920 * <jc>// Create a client that uses a predefined JSON serializer request bodies.</jc> 4921 * RestClient <jv>client</jv> = RestClient 4922 * .<jsm>create</jsm>() 4923 * .serializer(JsonSerializer.<jsf>DEFAULT_READABLE</jsf>) 4924 * .build(); 4925 * </p> 4926 * 4927 * @param value 4928 * The new value for this setting. 4929 * <br>The default is {@link JsonSerializer}. 4930 * <br>Cannot be <jk>null</jk>. 4931 * @return This object. 4932 */ 4933 public SELF serializer(Serializer value) { 4934 return serializers(value); 4935 } 4936 4937 /** 4938 * Returns the serializer group sub-builder. 4939 * 4940 * @return The serializer group sub-builder. 4941 */ 4942 public final SerializerSet.Builder serializers() { 4943 if (serializers == null) 4944 serializers = createSerializers(); 4945 return serializers; 4946 } 4947 4948 /** 4949 * Serializers. 4950 * 4951 * <p> 4952 * Associates the specified {@link Serializer Serializers} with the HTTP client. 4953 * 4954 * <p> 4955 * The serializer is used to serialize POJOs into the HTTP request body. 4956 * 4957 * <p> 4958 * The serializer that best matches the <c>Content-Type</c> header will be used to serialize the request body. 4959 * <br>If no <c>Content-Type</c> header is specified, the first serializer in the list will be used. 4960 * 4961 * <h4 class='section'>Notes:</h4><ul> 4962 * <li class='note'>When using this method that takes in classes, the serializers can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 4963 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 4964 * </ul> 4965 * 4966 * <h4 class='section'>Example:</h4> 4967 * <p class='bjava'> 4968 * <jc>// Create a client that uses JSON and XML transport for request bodies.</jc> 4969 * RestClient <jv>client</jv> = RestClient 4970 * .<jsm>create</jsm>() 4971 * .serializers(JsonSerializer.<jk>class</jk>, XmlSerializer.<jk>class</jk>) 4972 * .sortCollections() <jc>// Sort any collections being serialized.</jc> 4973 * .build(); 4974 * </p> 4975 * 4976 * @param value 4977 * The new value for this setting. 4978 * <br>The default is {@link JsonSerializer}. 4979 * @return This object. 4980 */ 4981 public SELF serializers(Class<? extends Serializer>...value) { 4982 reqnns("value", value); 4983 serializers().add(value); 4984 return self(); 4985 } 4986 4987 /** 4988 * Serializers. 4989 * 4990 * <p> 4991 * Associates the specified {@link Serializer Serializers} with the HTTP client. 4992 * 4993 * <p> 4994 * The serializer is used to serialize POJOs into the HTTP request body. 4995 * 4996 * <p> 4997 * The serializer that best matches the <c>Content-Type</c> header will be used to serialize the request body. 4998 * <br>If no <c>Content-Type</c> header is specified, the first serializer in the list will be used. 4999 * 5000 * <h4 class='section'>Notes:</h4><ul> 5001 * <li class='note'>When using this method that takes in a pre-instantiated serializers, the serializer property setters (e.g. {@link #sortCollections()}) or 5002 * bean context property setters (e.g. {@link #swaps(Class...)}) defined 5003 * on this builder class have no effect. 5004 * </ul> 5005 * 5006 * <h4 class='section'>Example:</h4> 5007 * <p class='bjava'> 5008 * <jc>// Create a client that uses predefined JSON and XML serializers for request bodies.</jc> 5009 * RestClient <jv>client</jv> = RestClient 5010 * .<jsm>create</jsm>() 5011 * .serializers(JsonSerializer.<jsf>DEFAULT_READABLE</jsf>, XmlSerializer.<jsf>DEFAULT_READABLE</jsf>) 5012 * .build(); 5013 * </p> 5014 * 5015 * @param value 5016 * The new value for this setting. 5017 * <br>The default is {@link JsonSerializer}. 5018 * @return This object. 5019 */ 5020 public SELF serializers(Serializer...value) { 5021 reqnns("value", value); 5022 serializers().add(value); 5023 return self(); 5024 } 5025 5026 /** 5027 * Assigns {@link ServiceUnavailableRetryStrategy} instance. 5028 * 5029 * @param serviceUnavailStrategy New property value. 5030 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 5031 * @return This object. 5032 * @see HttpClientBuilder#setServiceUnavailableRetryStrategy(ServiceUnavailableRetryStrategy) 5033 */ 5034 public SELF serviceUnavailableRetryStrategy(ServiceUnavailableRetryStrategy serviceUnavailStrategy) { 5035 httpClientBuilder().setServiceUnavailableRetryStrategy(serviceUnavailStrategy); 5036 return self(); 5037 } 5038 5039 /** 5040 * Skip empty form data. 5041 * 5042 * <p> 5043 * When enabled, form data consisting of empty strings will be skipped on requests. 5044 * Note that <jk>null</jk> values are already skipped. 5045 * 5046 * <p> 5047 * The {@link Schema#skipIfEmpty()} annotation overrides this setting. 5048 * 5049 * @return This object. 5050 */ 5051 public SELF skipEmptyFormData() { 5052 return skipEmptyFormData(true); 5053 } 5054 5055 /** 5056 * Skip empty form data. 5057 * 5058 * <p> 5059 * When enabled, form data consisting of empty strings will be skipped on requests. 5060 * Note that <jk>null</jk> values are already skipped. 5061 * 5062 * <p> 5063 * The {@link Schema#skipIfEmpty()} annotation overrides this setting. 5064 * 5065 * @param value 5066 * The new value for this setting. 5067 * <br>The default is <jk>false</jk>. 5068 * @return This object. 5069 */ 5070 public SELF skipEmptyFormData(boolean value) { 5071 skipEmptyFormData = value; 5072 return self(); 5073 } 5074 5075 /** 5076 * Skip empty header data. 5077 * 5078 * <p> 5079 * When enabled, headers consisting of empty strings will be skipped on requests. 5080 * Note that <jk>null</jk> values are already skipped. 5081 * 5082 * <p> 5083 * The {@link Schema#skipIfEmpty()} annotation overrides this setting. 5084 * 5085 * @return This object. 5086 */ 5087 public SELF skipEmptyHeaderData() { 5088 return skipEmptyHeaderData(true); 5089 } 5090 5091 /** 5092 * Skip empty header data. 5093 * 5094 * <p> 5095 * When enabled, headers consisting of empty strings will be skipped on requests. 5096 * Note that <jk>null</jk> values are already skipped. 5097 * 5098 * <p> 5099 * The {@link Schema#skipIfEmpty()} annotation overrides this setting. 5100 * 5101 * @param value 5102 * The new value for this setting. 5103 * <br>The default is <jk>false</jk>. 5104 * @return This object. 5105 */ 5106 public SELF skipEmptyHeaderData(boolean value) { 5107 skipEmptyHeaderData = value; 5108 return self(); 5109 } 5110 5111 /** 5112 * Skip empty query data. 5113 * 5114 * <p> 5115 * When enabled, query parameters consisting of empty strings will be skipped on requests. 5116 * Note that <jk>null</jk> values are already skipped. 5117 * 5118 * <p> 5119 * The {@link Schema#skipIfEmpty()} annotation overrides this setting. 5120 * 5121 * @return This object. 5122 */ 5123 public SELF skipEmptyQueryData() { 5124 return skipEmptyQueryData(true); 5125 } 5126 5127 /** 5128 * Skip empty query data. 5129 * 5130 * <p> 5131 * When enabled, query parameters consisting of empty strings will be skipped on requests. 5132 * Note that <jk>null</jk> values are already skipped. 5133 * 5134 * <p> 5135 * The {@link Schema#skipIfEmpty()} annotation overrides this setting. 5136 * 5137 * @param value 5138 * The new value for this setting. 5139 * <br>The default is <jk>false</jk>. 5140 * @return This object. 5141 */ 5142 public SELF skipEmptyQueryData(boolean value) { 5143 skipEmptyQueryData = value; 5144 return self(); 5145 } 5146 5147 /** 5148 * <i><l>Serializer</l> configuration property: </i> Sort arrays and collections alphabetically. 5149 * 5150 * <p> 5151 * When enabled, copies and sorts the contents of arrays and collections before serializing them. 5152 * 5153 * <p> 5154 * Note that this introduces a performance penalty since it requires copying the existing collection. 5155 * 5156 * <h4 class='section'>Example:</h4> 5157 * <p class='bjava'> 5158 * <jc>// Create a REST client with JSON serializer that sorts arrays and collections before serialization.</jc> 5159 * RestClient <jv>client</jv> = RestClient 5160 * .<jsm>create</jsm>() 5161 * .json() 5162 * .sortCollections() 5163 * .build(); 5164 * 5165 * <jc>// An unsorted array</jc> 5166 * String[] <jv>array</jv> = {<js>"foo"</js>,<js>"bar"</js>,<js>"baz"</js>} 5167 * 5168 * <jc>// Request body will contain: ["bar","baz","foo"]</jc> 5169 * <jv>client</jv> 5170 * .post(<js>"http://localhost:10000/foo"</js>, <jv>array</jv>) 5171 * .run(); 5172 * </p> 5173 * 5174 * <h4 class='section'>See Also:</h4><ul> 5175 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#sortCollections() Serializer.Builder#sortCollections()} 5176 * </ul> 5177 * 5178 * @return This object. 5179 */ 5180 public SELF sortCollections() { 5181 serializers().forEach(Serializer.Builder::sortCollections); 5182 return self(); 5183 } 5184 5185 /** 5186 * <i><l>Serializer</l> configuration property: </i> Sort maps alphabetically. 5187 * 5188 * <p> 5189 * When enabled, copies and sorts the contents of maps by their keys before serializing them. 5190 * 5191 * <p> 5192 * Note that this introduces a performance penalty. 5193 * 5194 * <h4 class='section'>Example:</h4> 5195 * <p class='bjava'> 5196 * <jc>// Create a REST client with JSON serializer that sorts maps before serialization.</jc> 5197 * RestClient <jv>client</jv> = RestClient 5198 * .<jsm>create</jsm>() 5199 * .json() 5200 * .sortMaps() 5201 * .build(); 5202 * 5203 * <jc>// An unsorted map.</jc> 5204 * AMap <jv>map</jv> = AMap.<jsm>of</jsm>(<js>"foo"</js>,1,<js>"bar"</js>,2,<js>"baz"</js>,3); 5205 * 5206 * <jc>// Request body will contain: {"bar":2,"baz":3,"foo":1}</jc> 5207 * <jv>client</jv> 5208 * .post(<js>"http://localhost:10000/foo"</js>, <jv>map</jv>) 5209 * .run(); 5210 * </p> 5211 * 5212 * <h4 class='section'>See Also:</h4><ul> 5213 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#sortMaps() Serializer.Builder#sortMaps()} 5214 * </ul> 5215 * 5216 * @return This object. 5217 */ 5218 public SELF sortMaps() { 5219 serializers().forEach(Serializer.Builder::sortMaps); 5220 return self(); 5221 } 5222 5223 /** 5224 * <i><l>WriterSerializer</l> configuration property: </i> Quote character. 5225 * 5226 * <p> 5227 * Specifies to use single quotes for quoting attributes and values. 5228 * 5229 * <h4 class='section'>Notes:</h4><ul> 5230 * <li class='note'>This setting does not apply to the RDF serializers. 5231 * </ul> 5232 * 5233 * <h4 class='section'>Example:</h4> 5234 * <p class='bjava'> 5235 * <jc>// Create a REST client with JSON serializer that uses single quotes.</jc> 5236 * RestClient <jv>client</jv> = RestClient 5237 * .<jsm>create</jsm>() 5238 * .json() 5239 * .sq() 5240 * .build(); 5241 * 5242 * <jc>// A bean with a single property</jc> 5243 * <jk>public class</jk> MyBean { 5244 * <jk>public</jk> String <jf>foo</jf> = <js>"bar"</js>; 5245 * } 5246 * 5247 * <jc>// Request body will contain: {'foo':'bar'}</jc> 5248 * <jv>client</jv> 5249 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 5250 * .run(); 5251 * </p> 5252 * 5253 * <h4 class='section'>See Also:</h4><ul> 5254 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.WriterSerializer.Builder#quoteChar(char) WriterSerializer.Builder#quoteChar(char)} 5255 * </ul> 5256 * 5257 * @return This object. 5258 */ 5259 public SELF sq() { 5260 serializers().forEachWS(WriterSerializer.Builder::sq); 5261 return self(); 5262 } 5263 5264 /** 5265 * Assigns {@link SSLContext} instance. 5266 * 5267 * <p> 5268 * The context (for example one initialized with a custom trust store) is used for {@code https} connections, with 5269 * the {@link #sslHostnameVerifier(HostnameVerifier) hostname verifier} if one is set, or the default one. 5270 * 5271 * <h4 class='section'>Notes:</h4><ul> 5272 * <li class='note'>It is applied to the connection manager the default {@link #createConnectionManager()} builds, for 5273 * both ordinary requests and the internal pool for SSRF-guard-active {@code @Remote} calls. It has no effect on 5274 * a connection manager supplied through {@link #connectionManager(HttpClientConnectionManager)} or an overridden 5275 * {@link #createConnectionManager()}, which carries its own socket factories. 5276 * <li class='note'>An {@link #sslSocketFactory(LayeredConnectionSocketFactory) SSL socket factory} takes precedence 5277 * over this value, including one set with 5278 * {@link HttpClientBuilder#setSSLSocketFactory(LayeredConnectionSocketFactory) setSSLSocketFactory} on a builder 5279 * passed to {@link #httpClientBuilder(HttpClientBuilder)} after this value was set (as in Apache 5280 * {@code HttpClientBuilder}). 5281 * </ul> 5282 * 5283 * @param sslContext New property value. 5284 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 5285 * @return This object. 5286 * @see HttpClientBuilder#setSSLContext(SSLContext) 5287 */ 5288 public SELF sslContext(SSLContext sslContext) { 5289 this.sslContext = sslContext; 5290 httpClientBuilder().setSSLContext(sslContext); 5291 return self(); 5292 } 5293 5294 /** 5295 * Assigns {@link HostnameVerifier} instance. 5296 * 5297 * <h4 class='section'>Notes:</h4><ul> 5298 * <li class='note'>It is applied to the connection manager the default {@link #createConnectionManager()} builds, for 5299 * both ordinary requests and the internal pool for SSRF-guard-active {@code @Remote} calls. It has no effect on 5300 * a connection manager supplied through {@link #connectionManager(HttpClientConnectionManager)} or an overridden 5301 * {@link #createConnectionManager()}, which carries its own socket factories. 5302 * <li class='note'>An {@link #sslSocketFactory(LayeredConnectionSocketFactory) SSL socket factory} takes precedence 5303 * over this value, including one set with 5304 * {@link HttpClientBuilder#setSSLSocketFactory(LayeredConnectionSocketFactory) setSSLSocketFactory} on a builder 5305 * passed to {@link #httpClientBuilder(HttpClientBuilder)} after this value was set (as in Apache 5306 * {@code HttpClientBuilder}). 5307 * </ul> 5308 * 5309 * @param hostnameVerifier New property value. 5310 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 5311 * @return This object. 5312 * @see HttpClientBuilder#setSSLHostnameVerifier(HostnameVerifier) 5313 */ 5314 public SELF sslHostnameVerifier(HostnameVerifier hostnameVerifier) { 5315 this.sslHostnameVerifier = hostnameVerifier; 5316 httpClientBuilder().setSSLHostnameVerifier(hostnameVerifier); 5317 return self(); 5318 } 5319 5320 /** 5321 * Assigns {@link LayeredConnectionSocketFactory} instance. 5322 * 5323 * <p> 5324 * The factory is used for {@code https} connections, in place of one built from the 5325 * {@link #sslContext(SSLContext) SSL context} and {@link #sslHostnameVerifier(HostnameVerifier) hostname verifier}. 5326 * 5327 * <h4 class='section'>Notes:</h4><ul> 5328 * <li class='note'>It is applied to the connection manager the default {@link #createConnectionManager()} builds, for 5329 * both ordinary requests and the internal pool for SSRF-guard-active {@code @Remote} calls. It has no effect on 5330 * a connection manager supplied through {@link #connectionManager(HttpClientConnectionManager)} or an overridden 5331 * {@link #createConnectionManager()}, which carries its own socket factories. 5332 * <li class='warn'>For SSRF-guard-active {@code @Remote} calls, the factory is given the address the SSRF pin has 5333 * already checked (the {@code remoteAddress} of 5334 * {@link ConnectionSocketFactory#connectSocket(int, Socket, HttpHost, InetSocketAddress, InetSocketAddress, HttpContext) connectSocket}). 5335 * It must connect to exactly that address: a factory that ignores it and connects by host name (resolving 5336 * the name again) bypasses the pin. The same holds for a factory set with 5337 * {@link HttpClientBuilder#setSSLSocketFactory(LayeredConnectionSocketFactory) setSSLSocketFactory} on a 5338 * builder passed to {@link #httpClientBuilder(HttpClientBuilder)}. 5339 * </ul> 5340 * 5341 * @param sslSocketFactory New property value. 5342 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 5343 * @return This object. 5344 * @see HttpClientBuilder#setSSLSocketFactory(LayeredConnectionSocketFactory) 5345 */ 5346 public SELF sslSocketFactory(LayeredConnectionSocketFactory sslSocketFactory) { 5347 this.sslSocketFactory = sslSocketFactory; 5348 httpClientBuilder().setSSLSocketFactory(sslSocketFactory); 5349 return self(); 5350 } 5351 5352 /** 5353 * Assigns {@link AuthenticationStrategy} instance for target host authentication. 5354 * 5355 * @param targetAuthStrategy New property value. 5356 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 5357 * @return This object. 5358 * @see HttpClientBuilder#setTargetAuthenticationStrategy(AuthenticationStrategy) 5359 */ 5360 public SELF targetAuthenticationStrategy(AuthenticationStrategy targetAuthStrategy) { 5361 httpClientBuilder().setTargetAuthenticationStrategy(targetAuthStrategy); 5362 return self(); 5363 } 5364 5365 /** 5366 * <i><l>Serializer</l> configuration property: </i> Trim empty lists and arrays. 5367 * 5368 * <p> 5369 * When enabled, empty lists and arrays will not be serialized. 5370 * 5371 * <p> 5372 * Note that enabling this setting has the following effects on parsing: 5373 * <ul class='spaced-list'> 5374 * <li> 5375 * Map entries with empty list values will be lost. 5376 * <li> 5377 * Bean properties with empty list values will not be set. 5378 * </ul> 5379 * 5380 * <h4 class='section'>Example:</h4> 5381 * <p class='bjava'> 5382 * <jc>// Create a serializer that skips empty arrays and collections.</jc> 5383 * WriterSerializer <jv>serializer</jv> = JsonSerializer 5384 * .<jsm>create</jsm>() 5385 * .trimEmptyCollections() 5386 * .build(); 5387 * 5388 * <jc>// A bean with a field with an empty array.</jc> 5389 * <jk>public class</jk> MyBean { 5390 * <jk>public</jk> String[] <jf>foo</jf> = {}; 5391 * } 5392 * 5393 * <jc>// Request body will contain: {}</jc> 5394 * <jv>client</jv> 5395 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 5396 * .run(); 5397 * </p> 5398 * 5399 * <h4 class='section'>See Also:</h4><ul> 5400 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#trimEmptyCollections() Serializer.Builder#trimEmptyCollections()} 5401 * </ul> 5402 * 5403 * @return This object. 5404 */ 5405 public SELF trimEmptyCollections() { 5406 serializers().forEach(Serializer.Builder::trimEmptyCollections); 5407 return self(); 5408 } 5409 5410 /** 5411 * <i><l>Serializer</l> configuration property: </i> Trim empty maps. 5412 * 5413 * <p> 5414 * When enabled, empty map values will not be serialized to the output. 5415 * 5416 * <p> 5417 * Note that enabling this setting has the following effects on parsing: 5418 * <ul class='spaced-list'> 5419 * <li> 5420 * Bean properties with empty map values will not be set. 5421 * </ul> 5422 * 5423 * <h4 class='section'>Example:</h4> 5424 * <p class='bjava'> 5425 * <jc>// Create a REST client with JSON serializer that skips empty maps.</jc> 5426 * RestClient <jv>client</jv> = RestClient 5427 * .<jsm>create</jsm>() 5428 * .json() 5429 * .trimEmptyMaps() 5430 * .build(); 5431 * 5432 * <jc>// A bean with a field with an empty map.</jc> 5433 * <jk>public class</jk> MyBean { 5434 * <jk>public</jk> AMap <jf>foo</jf> = AMap.<jsm>of</jsm>(); 5435 * } 5436 * 5437 * <jc>// Request body will contain: {}</jc> 5438 * <jv>client</jv> 5439 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 5440 * .run(); 5441 * </p> 5442 * 5443 * <h4 class='section'>See Also:</h4><ul> 5444 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#trimEmptyMaps() Serializer.Builder#trimEmptyMaps()} 5445 * </ul> 5446 * 5447 * @return This object. 5448 */ 5449 public SELF trimEmptyMaps() { 5450 serializers().forEach(Serializer.Builder::trimEmptyMaps); 5451 return self(); 5452 } 5453 5454 /** 5455 * <i><l>Parser</l> configuration property: </i> Trim parsed strings. 5456 * 5457 * <p> 5458 * When enabled, string values will be trimmed of whitespace using {@link String#trim()} before being added to 5459 * the POJO. 5460 * 5461 * <h4 class='section'>Example:</h4> 5462 * <p class='bjava'> 5463 * <jc>// Create a REST client with JSON parser with trim-strings enabled.</jc> 5464 * RestClient <jv>client</jv> = RestClient 5465 * .<jsm>create</jsm>() 5466 * .json() 5467 * .trimStringsOnRead() 5468 * .build(); 5469 * 5470 * <jc>// Try to parse JSON containing {" foo ":" bar "}.</jc> 5471 * Map<String,String> <jv>map</jv> = <jv>client</jv> 5472 * .get(<js>"/pathToJson"</js>) 5473 * .run() 5474 * .getContent().as(HashMap.<jk>class</jk>, String.<jk>class</jk>, String.<jk>class</jk>); 5475 * 5476 * <jc>// Make sure strings are trimmed.</jc> 5477 * <jsm>assertEquals</jsm>(<js>"bar"</js>, <jv>map</jv>.get(<js>"foo"</js>)); 5478 * </p> 5479 * 5480 * <h4 class='section'>See Also:</h4><ul> 5481 * <li class='jm'>{@link org.apache.juneau.marshall.parser.Parser.Builder#trimStrings() Parser.Builder#trimStrings()} 5482 * </ul> 5483 * 5484 * @return This object. 5485 */ 5486 public SELF trimStringsOnRead() { 5487 parsers().forEach(Parser.Builder::trimStrings); 5488 return self(); 5489 } 5490 5491 /** 5492 * <i><l>Serializer</l> configuration property: </i> Trim strings. 5493 * 5494 * <p> 5495 * When enabled, string values will be trimmed of whitespace using {@link String#trim()} before being serialized. 5496 * 5497 * <h4 class='section'>Example:</h4> 5498 * <p class='bjava'> 5499 * <jc>// Create a REST client with JSON serializer that trims strings before serialization.</jc> 5500 * RestClient <jv>client</jv> = RestClient 5501 * .<jsm>create</jsm>() 5502 * .json() 5503 * .trimStrings() 5504 * .build(); 5505 * 5506 * <jc>// A map with space-padded keys/values</jc> 5507 * AMap <jv>map</jv> = AMap.<jsm>of</jsm>(<js>" foo "</js>, <js>" bar "</js>); 5508 * 5509 * <jc>// Request body will contain: {"foo":"bar"}</jc> 5510 * <jv>client</jv> 5511 * .post(<js>"http://localhost:10000/foo"</js>, <jv>map</jv>) 5512 * .run(); 5513 * </p> 5514 * 5515 * <h4 class='section'>See Also:</h4><ul> 5516 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#trimStrings() Serializer.Builder#trimStrings()} 5517 * </ul> 5518 * 5519 * @return This object. 5520 */ 5521 public SELF trimStringsOnWrite() { 5522 serializers().forEach(Serializer.Builder::trimStrings); 5523 return self(); 5524 } 5525 5526 /** 5527 * Convenience method for specifying all available transmission types. 5528 * 5529 * <p> 5530 * All basic Juneau serializers will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 5531 * <ul> 5532 * <li>The serializers can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 5533 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 5534 * </ul> 5535 * <p> 5536 * All basic Juneau parsers will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 5537 * <ul> 5538 * <li>The parsers can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 5539 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 5540 * </ul> 5541 * <p> 5542 * <c>Accept</c> request header must be set via {@link #headers()}, or per-request 5543 * via {@link RestRequest#header(Header)} in order for the correct parser to be selected. 5544 * <p> 5545 * <c>Content-Type</c> request header must be set via {@link #headers()}, 5546 * or per-request via {@link RestRequest#header(Header)} in order for the correct serializer to be selected. 5547 * <p> 5548 * Similar to calling <c>json().json5().html().xml().uon().urlEnc().openApi().msgPack().plainText()</c>. 5549 * 5550 * <h4 class='section'>Example:</h4> 5551 * <p class='bjava'> 5552 * <jc>// Construct a client that uses universal marshalling.</jc> 5553 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().universal().build(); 5554 * </p> 5555 * 5556 * @return This object. 5557 */ 5558 public SELF universal() { 5559 // @formatter:off 5560 return 5561 serializers( 5562 JsonSerializer.class, 5563 JcsSerializer.class, 5564 Json5Serializer.class, 5565 Json5lSerializer.class, 5566 JsonlSerializer.class, 5567 HtmlSerializer.class, 5568 XmlSerializer.class, 5569 UonSerializer.class, 5570 UrlEncodingSerializer.class, 5571 OpenApiSerializer.class, 5572 BsonSerializer.class, 5573 CborSerializer.class, 5574 MsgPackSerializer.class, 5575 ParquetSerializer.class, 5576 PlainTextSerializer.class, 5577 TomlSerializer.class, 5578 HjsonSerializer.class, 5579 HoconSerializer.class, 5580 IniSerializer.class, 5581 PrototextSerializer.class, 5582 MarkdownSerializer.class 5583 ) 5584 .parsers( 5585 JsonParser.class, 5586 Json5Parser.class, 5587 Json5lParser.class, 5588 JsonlParser.class, 5589 XmlParser.class, 5590 HtmlParser.class, 5591 UonParser.class, 5592 UrlEncodingParser.class, 5593 OpenApiParser.class, 5594 BsonParser.class, 5595 CborParser.class, 5596 MsgPackParser.class, 5597 ParquetParser.class, 5598 PlainTextParser.class, 5599 TomlParser.class, 5600 HjsonParser.class, 5601 HoconParser.class, 5602 IniParser.class, 5603 PrototextParser.class, 5604 MarkdownParser.class 5605 ); 5606 // @formatter:on 5607 } 5608 5609 /** 5610 * Convenience method for specifying UON as the marshalling transmission media type. 5611 * 5612 * <p> 5613 * UON is Url-Encoding Object notation that is equivalent to JSON but suitable for transmission as URL-encoded 5614 * query and form post values. 5615 * 5616 * <p> 5617 * {@link UonSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 5618 * <ul> 5619 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 5620 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 5621 * </ul> 5622 * <p> 5623 * {@link UonParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 5624 * <ul> 5625 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 5626 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 5627 * </ul> 5628 * <p> 5629 * <c>Accept</c> request header will be set to <js>"text/uon"</js> unless overridden 5630 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 5631 * <p> 5632 * <c>Content-Type</c> request header will be set to <js>"text/uon"</js> unless overridden 5633 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 5634 * <p> 5635 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 5636 * <ul> 5637 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 5638 * last-enabled language if the headers are not set. 5639 * </ul> 5640 * <p> 5641 * Identical to calling <c>serializer(UonSerializer.<jk>class</jk>).parser(UonParser.<jk>class</jk>)</c>. 5642 * 5643 * <h4 class='section'>Example:</h4> 5644 * <p class='bjava'> 5645 * <jc>// Construct a client that uses UON marshalling.</jc> 5646 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().uon().build(); 5647 * </p> 5648 * 5649 * @return This object. 5650 */ 5651 public SELF uon() { 5652 return serializer(UonSerializer.class).parser(UonParser.class); 5653 } 5654 5655 /** 5656 * <i><l>Serializer</l> configuration property: </i> URI context bean. 5657 * 5658 * <p> 5659 * Bean used for resolution of URIs to absolute or root-relative form. 5660 * 5661 * <h4 class='section'>Example:</h4> 5662 * <p class='bjava'> 5663 * <jc>// Our URI contextual information.</jc> 5664 * String <jv>authority</jv> = <js>"http://localhost:10000"</js>; 5665 * String <jv>contextRoot</jv> = <js>"/myContext"</js>; 5666 * String <jv>servletPath</jv> = <js>"/myServlet"</js>; 5667 * String <jv>pathInfo</jv> = <js>"/foo"</js>; 5668 * 5669 * <jc>// Create a UriContext object.</jc> 5670 * UriContext <jv>uriContext</jv> = <jk>new</jk> UriContext(<jv>authority</jv>, <jv>contextRoot</jv>, <jv>servletPath</jv>, <jv>pathInfo</jv>); 5671 * 5672 * <jc>// Create a REST client with JSON serializer and associate our context.</jc> 5673 * RestClient <jv>client</jv> = RestClient 5674 * .<jsm>create</jsm>() 5675 * .json() 5676 * .uriContext(<jv>uriContext</jv>) 5677 * .uriRelativity(<jsf>RESOURCE</jsf>) <jc>// Assume relative paths are relative to servlet.</jc> 5678 * .uriResolution(<jsf>ABSOLUTE</jsf>) <jc>// Serialize URIs as absolute paths.</jc> 5679 * .build(); 5680 * 5681 * <jc>// A relative URI</jc> 5682 * URI <jv>uri</jv> = <jk>new</jk> URI(<js>"bar"</js>); 5683 * 5684 * <jc>// Request body will contain: "http://localhost:10000/myContext/myServlet/foo/bar"</jc> 5685 * <jv>client</jv> 5686 * .post(<js>"http://localhost:10000/foo"</js>, <jv>uri</jv>) 5687 * .run(); 5688 * </p> 5689 * 5690 * <h4 class='section'>See Also:</h4><ul> 5691 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#uriContext(UriContext) Serializer.Builder#uriContext(UriContext)} 5692 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/MarshallingUris">URIs</a> 5693 * </ul> 5694 * 5695 * @param value The new value for this property. 5696 * <br>Cannot be <jk>null</jk>. 5697 * @return This object. 5698 */ 5699 public SELF uriContext(UriContext value) { 5700 serializers().forEach(x -> x.uriContext(reqnn("value", value))); 5701 return self(); 5702 } 5703 5704 /** 5705 * <i><l>Serializer</l> configuration property: </i> URI relativity. 5706 * 5707 * <p> 5708 * Defines what relative URIs are relative to when serializing any of the following: 5709 * <ul> 5710 * <li>{@link URI} 5711 * <li>{@link URL} 5712 * <li>Properties and classes annotated with {@link Uri @Uri} 5713 * </ul> 5714 * 5715 * <p> 5716 * See {@link #uriContext(UriContext)} for examples. 5717 * 5718 * <ul class='values javatree'> 5719 * <li class='jf'>{@link UriRelativity#RESOURCE} 5720 * - Relative URIs should be considered relative to the servlet URI. 5721 * <li class='jf'>{@link UriRelativity#PATH_INFO} 5722 * - Relative URIs should be considered relative to the request URI. 5723 * </ul> 5724 * 5725 * <h4 class='section'>See Also:</h4><ul> 5726 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#uriRelativity(UriRelativity) Serializer.Builder#uriRelativity(UriRelativity)} 5727 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/MarshallingUris">URIs</a> 5728 * </ul> 5729 * 5730 * @param value 5731 * The new value for this property. 5732 * <br>The default is {@link UriRelativity#RESOURCE} 5733 * <br>Cannot be <jk>null</jk>. 5734 * @return This object. 5735 */ 5736 public SELF uriRelativity(UriRelativity value) { 5737 serializers().forEach(x -> x.uriRelativity(reqnn("value", value))); 5738 return self(); 5739 } 5740 5741 /** 5742 * <i><l>Serializer</l> configuration property: </i> URI resolution. 5743 * 5744 * <p> 5745 * Defines the resolution level for URIs when serializing any of the following: 5746 * <ul> 5747 * <li>{@link URI} 5748 * <li>{@link URL} 5749 * <li>Properties and classes annotated with {@link Uri @Uri} 5750 * </ul> 5751 * 5752 * <p> 5753 * See {@link #uriContext(UriContext)} for examples. 5754 * 5755 * <ul class='values'> 5756 * <li class='jf'>{@link UriResolution#ABSOLUTE} 5757 * - Resolve to an absolute URI (e.g. <js>"http://host:port/context-root/servlet-path/path-info"</js>). 5758 * <li class='jf'>{@link UriResolution#ROOT_RELATIVE} 5759 * - Resolve to a root-relative URI (e.g. <js>"/context-root/servlet-path/path-info"</js>). 5760 * <li class='jf'>{@link UriResolution#NONE} 5761 * - Don't do any URI resolution. 5762 * </ul> 5763 * 5764 * <h4 class='section'>See Also:</h4><ul> 5765 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.Serializer.Builder#uriResolution(UriResolution) Serializer.Builder#uriResolution(UriResolution)} 5766 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/MarshallingUris">URIs</a> 5767 * </ul> 5768 * 5769 * @param value 5770 * The new value for this property. 5771 * <br>The default is {@link UriResolution#NONE} 5772 * <br>Cannot be <jk>null</jk>. 5773 * @return This object. 5774 */ 5775 public SELF uriResolution(UriResolution value) { 5776 serializers().forEach(x -> x.uriResolution(reqnn("value", value))); 5777 return self(); 5778 } 5779 5780 /** 5781 * Convenience method for specifying URL-Encoding as the marshalling transmission media type. 5782 * 5783 * <p> 5784 * {@link UrlEncodingSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 5785 * <ul> 5786 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 5787 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 5788 * <li>This serializer is NOT used when using the {@link RestRequest#formData(String, Object)} (and related) methods for constructing 5789 * the request body. Instead, the part serializer specified via {@link #partSerializer(Class)} is used. 5790 * </ul> 5791 * <p> 5792 * {@link UrlEncodingParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 5793 * <ul> 5794 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 5795 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 5796 * </ul> 5797 * <p> 5798 * <c>Accept</c> request header will be set to <js>"application/x-www-form-urlencoded"</js> unless overridden 5799 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 5800 * <p> 5801 * <c>Content-Type</c> request header will be set to <js>"application/x-www-form-urlencoded"</js> unless overridden 5802 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 5803 * <p> 5804 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 5805 * <ul> 5806 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 5807 * last-enabled language if the headers are not set. 5808 * </ul> 5809 * <p> 5810 * Identical to calling <c>serializer(UrlEncodingSerializer.<jk>class</jk>).parser(UrlEncodingParser.<jk>class</jk>)</c>. 5811 * 5812 * <h4 class='section'>Example:</h4> 5813 * <p class='bjava'> 5814 * <jc>// Construct a client that uses URL-Encoded marshalling.</jc> 5815 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().urlEnc().build(); 5816 * </p> 5817 * 5818 * @return This object. 5819 */ 5820 public SELF urlEnc() { 5821 return serializer(UrlEncodingSerializer.class).parser(UrlEncodingParser.class); 5822 } 5823 5824 /** 5825 * Returns the URL-encoding serializer sub-builder. 5826 * 5827 * @return The URL-encoding serializer sub-builder. 5828 */ 5829 public final UrlEncodingSerializer.Builder urlEncodingSerializer() { 5830 if (urlEncodingSerializer == null) 5831 urlEncodingSerializer = createUrlEncodingSerializer(); 5832 return urlEncodingSerializer; 5833 } 5834 5835 5836 /** 5837 * Assigns {@link UserTokenHandler} instance. 5838 * 5839 * <h4 class='section'>Notes:</h4><ul> 5840 * <li class='note'>This value can be overridden by the {@link #disableConnectionState()} method. 5841 * </ul> 5842 * 5843 * @param userTokenHandler New property value. 5844 * <br>Can be <jk>null</jk> (value will not be set, default behavior will be used). 5845 * @return This object. 5846 * @see HttpClientBuilder#setUserTokenHandler(UserTokenHandler) 5847 */ 5848 public SELF userTokenHandler(UserTokenHandler userTokenHandler) { 5849 httpClientBuilder().setUserTokenHandler(userTokenHandler); 5850 return self(); 5851 } 5852 5853 /** 5854 * Use system properties when creating and configuring default implementations. 5855 * 5856 * <h4 class='section'>Notes:</h4><ul> 5857 * <li class='note'>The system properties Apache {@link HttpClientBuilder} reads for its own connection manager 5858 * apply to both pools of the connection manager the default {@link #createConnectionManager()} builds, as 5859 * Apache applies them: with no {@link #sslContext(SSLContext) sslContext} or 5860 * {@link #sslSocketFactory(LayeredConnectionSocketFactory) sslSocketFactory}, {@code https} uses the JVM's 5861 * default SSL socket factory (the {@code javax.net.ssl.*} trust and key stores); {@code https.protocols} and 5862 * {@code https.cipherSuites} restrict the TLS versions and cipher suites (unless an {@code sslSocketFactory} 5863 * is set); and unless {@code http.keepAlive} is {@code false}, {@code http.maxConnections} (default 5) limits 5864 * the connections per route, and twice that in total, which makes the connection manager a pooling one. 5865 * {@link #maxConnTotal(int)} and {@link #maxConnPerRoute(int)} win over that limit. 5866 * <li class='note'>The proxy system properties apply too (see {@link #proxy(HttpHost)}). 5867 * </ul> 5868 * 5869 * @return This object. 5870 * @see HttpClientBuilder#useSystemProperties() 5871 */ 5872 public SELF useSystemProperties() { 5873 this.systemProperties = true; 5874 httpClientBuilder().useSystemProperties(); 5875 return self(); 5876 } 5877 5878 /** 5879 * <i><l>WriterSerializer</l> configuration property: </i> Use whitespace. 5880 * 5881 * <p> 5882 * When enabled, whitespace is added to the output to improve readability. 5883 * 5884 * <h4 class='section'>Example:</h4> 5885 * <p class='bjava'> 5886 * <jc>// Create a REST client with JSON serializer with whitespace enabled.</jc> 5887 * RestClient <jv>client</jv> = RestClient 5888 * .<jsm>create</jsm>() 5889 * .json() 5890 * .useWhitespace() 5891 * .build(); 5892 * 5893 * <jc>// A bean with a single property</jc> 5894 * <jk>public class</jk> MyBean { 5895 * <jk>public</jk> String <jf>foo</jf> = <js>"bar"</js>; 5896 * } 5897 * 5898 * <jc>// Request body will contain: {\n\t"foo": "bar"\n\}\n</jc> 5899 * <jv>client</jv> 5900 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 5901 * .run(); 5902 * </p> 5903 * 5904 * <h4 class='section'>See Also:</h4><ul> 5905 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.WriterSerializer.Builder#useWhitespace() WriterSerializer.Builder#useWhitespace()} 5906 * </ul> 5907 * @return This object. 5908 */ 5909 public SELF useWhitespace() { 5910 serializers().forEachWS(WriterSerializer.Builder::useWhitespace); 5911 return self(); 5912 } 5913 5914 /** 5915 * <i><l>WriterSerializer</l> configuration property: </i> Use whitespace. 5916 * 5917 * <p> 5918 * When enabled, whitespace is added to the output to improve readability. 5919 * 5920 * <h4 class='section'>Example:</h4> 5921 * <p class='bjava'> 5922 * <jc>// Create a REST client with JSON serializer with whitespace enabled.</jc> 5923 * RestClient <jv>client</jv> = RestClient 5924 * .<jsm>create</jsm>() 5925 * .json() 5926 * .ws() 5927 * .build(); 5928 * 5929 * <jc>// A bean with a single property</jc> 5930 * <jk>public class</jk> MyBean { 5931 * <jk>public</jk> String <jf>foo</jf> = <js>"bar"</js>; 5932 * } 5933 * 5934 * <jc>// Request body will contain: {\n\t"foo": "bar"\n\}\n</jc> 5935 * <jv>client</jv> 5936 * .post(<js>"http://localhost:10000/foo"</js>, <jk>new</jk> MyBean()) 5937 * .run(); 5938 * </p> 5939 * 5940 * <h4 class='section'>See Also:</h4><ul> 5941 * <li class='jm'>{@link org.apache.juneau.marshall.serializer.WriterSerializer.Builder#useWhitespace() WriterSerializer.Builder#useWhitespace()} 5942 * </ul> 5943 * 5944 * @return This object. 5945 */ 5946 public SELF ws() { 5947 serializers().forEachWS(WriterSerializer.Builder::ws); 5948 return self(); 5949 } 5950 5951 /** 5952 * Convenience method for specifying XML as the marshalling transmission media type. 5953 * 5954 * <p> 5955 * {@link XmlSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 5956 * <ul> 5957 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link #sortCollections()}) or 5958 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 5959 * </ul> 5960 * <p> 5961 * {@link XmlParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 5962 * <ul> 5963 * <li>The parser can be configured using any of the parser property setters (e.g. {@link #ignoreUnknownBeanProperties()}) or 5964 * bean context property setters (e.g. {@link #swaps(Class...)}) defined on this builder class. 5965 * </ul> 5966 * <p> 5967 * <c>Accept</c> request header will be set to <js>"text/xml"</js> unless overridden 5968 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 5969 * <p> 5970 * <c>Content-Type</c> request header will be set to <js>"text/xml"</js> unless overridden 5971 * via {@link #headers()}, or per-request via {@link RestRequest#header(Header)}. 5972 * <p> 5973 * Can be combined with other marshaller setters such as {@link #json()} to provide support for multiple languages. 5974 * <ul> 5975 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 5976 * last-enabled language if the headers are not set. 5977 * </ul> 5978 * <p> 5979 * Identical to calling <c>serializer(XmlSerializer.<jk>class</jk>).parser(XmlParser.<jk>class</jk>)</c>. 5980 * 5981 * <h4 class='section'>Example:</h4> 5982 * <p class='bjava'> 5983 * <jc>// Construct a client that uses XML marshalling.</jc> 5984 * RestClient <jv>client</jv> = RestClient.<jsm>create</jsm>().xml().build(); 5985 * </p> 5986 * 5987 * @return This object. 5988 */ 5989 public SELF xml() { 5990 return serializer(XmlSerializer.class).parser(XmlParser.class); 5991 } 5992 5993 /** 5994 * Creates the creator for the rest call handler. 5995 * 5996 * <p> 5997 * Subclasses can override this method to provide their own implementation. 5998 * 5999 * <p> 6000 * The default behavior creates a bean instantiator initialized to return a {@link BasicRestCallHandler}. 6001 * 6002 * @return The creator for the rest call handler. 6003 * @see #callHandler() 6004 */ 6005 protected BeanInstantiator.Builder<RestCallHandler> createCallHandler() { 6006 return BeanInstantiator.of(RestCallHandler.class, beanStore).type(BasicRestCallHandler.class); 6007 } 6008 6009 /** 6010 * Creates the {@link HttpClientConnectionManager} returned by {@link #createConnectionManager()}. 6011 * 6012 * <p> 6013 * Subclasses can override this method to provide their own connection manager. 6014 * 6015 * <p> 6016 * The default implementation returns a new {@link PoolingHttpClientConnectionManager} if {@link #pooled()}, 6017 * {@link #maxConnTotal(int)}, {@link #maxConnPerRoute(int)} or a positive 6018 * {@link #connectionTimeToLive(long, TimeUnit) connectionTimeToLive} was set, or the {@code http.maxConnections} 6019 * limit of {@link #useSystemProperties()} applies (unless {@code http.keepAlive} is {@code false}), or a new 6020 * {@link BasicHttpClientConnectionManager} if not. It applies the {@link #sslContext(SSLContext) sslContext}, 6021 * {@link #sslSocketFactory(LayeredConnectionSocketFactory) sslSocketFactory}, 6022 * {@link #sslHostnameVerifier(HostnameVerifier) sslHostnameVerifier}, {@code maxConnTotal} and {@code maxConnPerRoute} 6023 * settings, which Apache {@link HttpClientBuilder} ignores once a connection manager is set. It also applies, to 6024 * both pools, the other settings Apache {@code HttpClientBuilder} applies only to a connection manager it builds 6025 * itself, whether made through this builder or directly on the {@link #httpClientBuilder() HttpClientBuilder}: 6026 * {@link #publicSuffixMatcher(PublicSuffixMatcher) publicSuffixMatcher} (for the default hostname verifier), 6027 * {@link #defaultSocketConfig(SocketConfig) defaultSocketConfig}, 6028 * {@link #defaultConnectionConfig(ConnectionConfig) defaultConnectionConfig}, 6029 * {@link #connectionTimeToLive(long, TimeUnit) connectionTimeToLive} (which, like {@code maxConnTotal} and 6030 * {@code maxConnPerRoute}, makes it a {@code PoolingHttpClientConnectionManager}) and the TLS and 6031 * {@code http.maxConnections} system properties of {@link #useSystemProperties()}. A 6032 * {@link HttpClientBuilder#setDnsResolver(DnsResolver) DNS resolver} set on the {@code HttpClientBuilder} is used 6033 * for ordinary requests only: SSRF-guard-active {@code @Remote} calls always resolve through the SSRF pin. 6034 * Each of these settings made through this builder also survives {@link #httpClientBuilder(HttpClientBuilder)} 6035 * replacing the {@code HttpClientBuilder}, and always wins over the same setting on the {@code HttpClientBuilder}, 6036 * whichever was set last (unlike Apache's own last-write-wins). An SSL socket factory wins over any SSL context, 6037 * wherever each was set. The {@code HttpClientBuilder}'s settings are read from its fields (it has no getters); 6038 * if they cannot be read, this method throws an {@link IllegalStateException} rather than ignore them. 6039 * 6040 * <p> 6041 * Each {@link #build()} calls this method again, so a builder reused after {@code build()} gives every client its 6042 * own connection manager (closing one client does not shut down another's). A connection manager supplied through 6043 * {@link #connectionManager(HttpClientConnectionManager)} is used as is by every client built. 6044 * 6045 * <p> 6046 * SSRF-guard-active {@code @Remote} calls do not use this connection manager: the default 6047 * {@link #createHttpClient()} pairs it with a second, dedicated one whose connections are all opened through the 6048 * SSRF pin, so that a guarded call never reuses a connection an ordinary request opened. It can only do that 6049 * for the instance this default implementation returns. If an override returns any other connection manager, 6050 * the client refuses every SSRF-guard-active {@code @Remote} call (one without the 6051 * {@link #allowPrivateUrls(boolean) allowPrivateUrls} opt-in). 6052 * 6053 * <p> 6054 * The dedicated connection manager copies this one's settings before each guarded call, but it is a separate pool: 6055 * limits such as {@link PoolingHttpClientConnectionManager#setMaxTotal(int) maxTotal} apply to each pool on its 6056 * own, so a client that mixes ordinary and guarded calls can hold up to twice as many open connections. 6057 * 6058 * <h4 class='section'>Example:</h4> 6059 * <p class='bjava'> 6060 * <jc>// A Builder that provides it's own customized HttpClientConnectionManager.</jc> 6061 * <jk>public class</jk> MyBuilder <jk>extends</jk> Builder { 6062 * <ja>@Override</ja> 6063 * <jk>protected</jk> HttpClientConnectionManager createConnectionManager() { 6064 * <jk>return new</jk> PoolingHttpClientConnectionManager(); 6065 * } 6066 * } 6067 * 6068 * <jc>// Instantiate.</jc> 6069 * RestClient <jv>client</jv> = <jk>new</jk> MyBuilder().build(); 6070 * </p> 6071 * 6072 * @return The connection manager to use. 6073 */ 6074 protected HttpClientConnectionManager createConnectionManager() { 6075 var s = HttpClientBuilderSettings.of(httpClientBuilder()); 6076 defaultRegistry = socketFactoryRegistry(s); 6077 defaultPoolSettings = poolSettings(s); 6078 defaultConnectionManager = newConnectionManager(defaultRegistry, or(s.dnsResolver(), SystemDefaultDnsResolver.INSTANCE), defaultPoolSettings); 6079 return defaultConnectionManager; 6080 } 6081 6082 // The socket factories for the TLS settings, chosen as Apache HttpClientBuilder chooses them when it builds its own 6083 // connection manager: the SSL socket factory, else one on the SSL context (else the JVM's default socket factory 6084 // under useSystemProperties(), else a default context) with the hostname verifier (else the default verifier on 6085 // the public suffix matcher) and, under useSystemProperties(), the https.protocols and https.cipherSuites. 6086 // A setting made through this builder always wins over the same setting read from the HttpClientBuilder, whichever 6087 // was set last. The two differ when httpClientBuilder(...) replaced the builder after the setting was made, or when 6088 // the setting was later made again directly on httpClientBuilder(). As in Apache, a socket factory wins over any 6089 // SSL context, wherever each was set. 6090 private Registry<ConnectionSocketFactory> socketFactoryRegistry(HttpClientBuilderSettings s) { 6091 var https = or(sslSocketFactory, s.sslSocketFactory()); 6092 if (https == null) { 6093 var sysProps = systemProperties || s.systemProperties(); 6094 var protocols = sysProps ? splitSystemProperty("https.protocols") : null; 6095 var cipherSuites = sysProps ? splitSystemProperty("https.cipherSuites") : null; 6096 var verifier = or(sslHostnameVerifier, s.hostnameVerifier()); 6097 if (verifier == null) 6098 verifier = new DefaultHostnameVerifier(or(publicSuffixMatcher, s.publicSuffixMatcher(), PublicSuffixMatcherLoader.getDefault())); 6099 var context = or(sslContext, s.sslContext()); 6100 if (nn(context)) 6101 https = new SSLConnectionSocketFactory(context, protocols, cipherSuites, verifier); 6102 else if (sysProps) 6103 https = new SSLConnectionSocketFactory((javax.net.ssl.SSLSocketFactory)javax.net.ssl.SSLSocketFactory.getDefault(), protocols, cipherSuites, verifier); 6104 else 6105 https = new SSLConnectionSocketFactory(SSLContexts.createDefault(), verifier); 6106 } 6107 return RegistryBuilder.<ConnectionSocketFactory>create() 6108 .register("http", PlainConnectionSocketFactory.getSocketFactory()) 6109 .register("https", https) 6110 .build(); 6111 } 6112 6113 private static String[] splitSystemProperty(String name) { 6114 var v = System.getProperty(name); 6115 return ib(v) ? null : splita(v); 6116 } 6117 6118 // The pool settings, applied as Apache HttpClientBuilder applies them to its own connection manager. The 6119 // http.maxConnections limit (default 5) of useSystemProperties() applies per route, and twice that in total, 6120 // unless http.keepAlive is off; maxConnTotal and maxConnPerRoute win over it. Any limit or a time-to-live 6121 // makes the manager a pooling one: BasicHttpClientConnectionManager has neither. 6122 private PoolSettings poolSettings(HttpClientBuilderSettings s) { 6123 var systemMax = (systemProperties || s.systemProperties()) && "true".equalsIgnoreCase(System.getProperty("http.keepAlive", "true")) 6124 ? Integer.parseInt(System.getProperty("http.maxConnections", "5")) : 0; 6125 var settingsTotal = s.maxConnTotal() > 0 ? s.maxConnTotal() : 2 * systemMax; 6126 var settingsPerRoute = s.maxConnPerRoute() > 0 ? s.maxConnPerRoute() : systemMax; 6127 var maxTotal = maxConnTotal > 0 ? maxConnTotal : settingsTotal; 6128 var maxPerRoute = maxConnPerRoute > 0 ? maxConnPerRoute : settingsPerRoute; 6129 var ownTtl = connTimeToLive > 0; 6130 var ttl = ownTtl ? connTimeToLive : s.connTimeToLive(); 6131 var ttlUnit = ownTtl ? connTimeToLiveTimeUnit : s.connTimeToLiveTimeUnit(); 6132 var pooling = pooled || maxTotal > 0 || maxPerRoute > 0 || ttl > 0; 6133 return new PoolSettings(pooling, maxTotal, maxPerRoute, ttl, or(ttlUnit, TimeUnit.MILLISECONDS), 6134 or(defaultSocketConfig, s.socketConfig()), or(defaultConnectionConfig, s.connectionConfig())); 6135 } 6136 6137 private static boolean overridesCreateConnectionManager(Class<?> c) { 6138 for (var x = c; x != Builder.class; x = x.getSuperclass()) { 6139 try { 6140 x.getDeclaredMethod("createConnectionManager"); 6141 return true; 6142 } catch (@SuppressWarnings("unused") NoSuchMethodException e) { /* Not declared here. */ } 6143 } 6144 return false; 6145 } 6146 6147 // Why guarded @Remote calls cannot be sent through a client built by b, or null if they can. The checks of the 6148 // client RestClient makes afterwards only see the connection manager the client stores, so they cannot tell: 6149 // - an HttpClientBuilder subclass whose build() or exec-chain factory may build the client around another 6150 // connection manager or request executor, or put a step in front of them that sends the request elsewhere; 6151 // - an HttpProcessor, which replaces the client's request interceptors (the SSRF guard's lease hand-over and the 6152 // redirect credential guard among them). 6153 private static String ssrfBuilderRefusal(HttpClientBuilder b) { 6154 var optOut = "or set allowPrivateUrls(true) if this is an intentional local-dev/intranet target."; 6155 if (! HttpClientBuilderSettings.isReadable()) 6156 // HTT: only an HttpClient release without the HttpClientBuilder fields, or a JVM that denies reflective access 6157 // to them, gets here (and then the default createConnectionManager() has already failed). 6158 return "Refusing to send a policy-covered @Remote request: the settings of " + HttpClientBuilder.class.getName() 6159 + " cannot be read, so whether the client it built honors the SSRF guardrail's connect-time contract " 6160 + "(pin-on-connect + redirect revalidation) cannot be confirmed. Use an HttpClient 4.5.x release, " + optOut; 6161 var override = overriddenBuilderMethod(b.getClass()); 6162 if (nn(override)) 6163 return "Refusing to send a policy-covered @Remote request through a client built by an HttpClientBuilder " 6164 + "subclass (" + override + "): the override may build the client around another connection manager or " 6165 + "request executor, so the SSRF guardrail's connect-time contract (pin-on-connect + redirect " 6166 + "revalidation) cannot be confirmed. Remove the override (configure the builder through its setters " 6167 + "instead), " + optOut; 6168 if (HttpClientBuilderSettings.hasHttpProcessor(b)) 6169 return "Refusing to send a policy-covered @Remote request through a client whose HttpProcessor was set: " 6170 + "httpProcessor(...) replaces the client's request interceptors, among them the SSRF guardrail's own and " 6171 + "the redirect credential guard, so its connect-time contract (pin-on-connect + redirect revalidation) " 6172 + "cannot be confirmed. Remove the httpProcessor(...) setting (add interceptors with " 6173 + "addInterceptorFirst(...) or addInterceptorLast(...) instead), " + optOut; 6174 var change = lateBuilderChange(b); 6175 if (nn(change)) 6176 return "Refusing to send a policy-covered @Remote request through a client whose HttpClientBuilder was changed " 6177 + "after the SSRF guard was wired into it (" + change + "), as an override of createHttpClient() does that " 6178 + "changes the builder after super.createHttpClient() and builds again. The change may add credentials to " 6179 + "a redirect hop on another origin, follow redirects without revalidation or send the request past the " 6180 + "guard's executor, so the SSRF guardrail's connect-time contract (pin-on-connect + redirect revalidation) " 6181 + "cannot be confirmed. Make the change before super.createHttpClient() (on httpClientBuilder() or through " 6182 + "this builder's setters), " + optOut; 6183 return null; 6184 } 6185 6186 // What was changed on b after the default createHttpClient() wired the SSRF guard into it, or null if nothing it 6187 // wired was: the guard's two request interceptors must still be the last ones (the redirect credential guard strips 6188 // what every interceptor before it added), and its redirect strategy and request executor must still be set. 6189 private static String lateBuilderChange(HttpClientBuilder b) { 6190 var last = HttpClientBuilderSettings.lastRequestInterceptors(b); 6191 var n = last.size(); 6192 if (n < 2 || ! (last.get(n - 2) instanceof ClassicRedirectCredentialGuard) || ! (last.get(n - 1) instanceof SsrfGuardConnectionManager.GuardInterceptor)) 6193 return "a request interceptor was added after the SSRF guard's own"; 6194 if (! (HttpClientBuilderSettings.redirectStrategy(b) instanceof PolicyAwareRedirectStrategy)) 6195 return "the redirect strategy was replaced"; 6196 if (! (HttpClientBuilderSettings.requestExecutor(b) instanceof SsrfGuardConnectionManager.GuardedRequestExecutor)) 6197 return "the request executor was replaced"; 6198 return null; 6199 } 6200 6201 // The HttpClientBuilder methods that decide which connection manager and request executor a built client uses. 6202 private static final List<Method> BUILDER_EXEC_METHODS = Arrays.stream(HttpClientBuilder.class.getDeclaredMethods()) 6203 .filter(m -> Set.of("build", "createMainExec", "decorateMainExec", "decorateProtocolExec").contains(m.getName())) 6204 .toList(); 6205 6206 // Returns "<class> overrides <method>(<params>)" for the first of BUILDER_EXEC_METHODS a class between c and 6207 // HttpClientBuilder declares, or null if there is none. 6208 private static String overriddenBuilderMethod(Class<?> c) { 6209 for (var x = c; nn(x) && x != HttpClientBuilder.class; x = x.getSuperclass()) { 6210 for (var m : BUILDER_EXEC_METHODS) { 6211 try { 6212 x.getDeclaredMethod(m.getName(), m.getParameterTypes()); 6213 return cn(x) + " overrides " + m.getName() + "(" + String.join(",", Arrays.stream(m.getParameterTypes()).map(Class::getSimpleName).toList()) + ")"; 6214 } catch (@SuppressWarnings("unused") NoSuchMethodException e) { /* Not declared here. */ } 6215 } 6216 } 6217 return null; 6218 } 6219 6220 private static HttpClientConnectionManager newConnectionManager(Registry<ConnectionSocketFactory> registry, DnsResolver dnsResolver, PoolSettings p) { 6221 if (! p.pooling()) { 6222 var cm = new BasicHttpClientConnectionManager(registry, null, null, dnsResolver); 6223 if (nn(p.socketConfig())) 6224 cm.setSocketConfig(p.socketConfig()); 6225 if (nn(p.connectionConfig())) 6226 cm.setConnectionConfig(p.connectionConfig()); 6227 return cm; 6228 } 6229 var cm = new PoolingHttpClientConnectionManager(registry, null, null, dnsResolver, p.timeToLive(), p.timeToLiveUnit()); 6230 if (nn(p.socketConfig())) 6231 cm.setDefaultSocketConfig(p.socketConfig()); 6232 if (nn(p.connectionConfig())) 6233 cm.setDefaultConnectionConfig(p.connectionConfig()); 6234 if (p.maxTotal() > 0) 6235 cm.setMaxTotal(p.maxTotal()); 6236 if (p.maxPerRoute() > 0) 6237 cm.setDefaultMaxPerRoute(p.maxPerRoute()); 6238 return cm; 6239 } 6240 6241 // The settings both pools of the default connection manager are built with. 6242 private record PoolSettings(boolean pooling, int maxTotal, int maxPerRoute, long timeToLive, TimeUnit timeToLiveUnit, 6243 SocketConfig socketConfig, ConnectionConfig connectionConfig) {} 6244 6245 /** 6246 * Creates the builder for the form data list. 6247 * 6248 * <p> 6249 * Subclasses can override this method to provide their own implementation. 6250 * 6251 * <p> 6252 * The default behavior creates an empty builder. 6253 * 6254 * @return The form data list builder. 6255 * @see #formData() 6256 */ 6257 protected PartList createFormData() { 6258 return PartList.create(); 6259 } 6260 6261 /** 6262 * Creates the builder for the header list. 6263 * 6264 * <p> 6265 * Subclasses can override this method to provide their own implementation. 6266 * 6267 * <p> 6268 * The default behavior creates an empty builder. 6269 * 6270 * @return The header list builder. 6271 * @see #headers() 6272 */ 6273 protected HeaderList createHeaderData() { 6274 return HeaderList.create(); 6275 } 6276 6277 /** 6278 * Creates an instance of an {@link HttpClient} to be used to handle all HTTP communications with the target server. 6279 * 6280 * <p> 6281 * This HTTP client is used when the HTTP client is not specified through one of the constructors or the 6282 * {@link #httpClient(CloseableHttpClient)} method. 6283 * 6284 * <p> 6285 * Subclasses can override this method to provide specially-configured HTTP clients to handle stuff such as 6286 * SSL/TLS certificate handling, authentication, etc. 6287 * 6288 * <p> 6289 * The default implementation returns an instance of {@link HttpClient} using the client builder returned by 6290 * {@link #createHttpClientBuilder()}. 6291 * 6292 * <h4 class='section'>Notes:</h4><ul> 6293 * <li class='warn'>SSRF-guard-active {@code @Remote} calls (ones without the 6294 * {@link #allowPrivateUrls(boolean) allowPrivateUrls} opt-in) are only sent through the client this default 6295 * implementation builds, which it wires to the connection manager that pins them. The client refuses every 6296 * such call if an override returns any other client (including a wrapper around the one it built), or after 6297 * {@code super.createHttpClient()} sets an {@link HttpProcessor} on the {@link HttpClientBuilder}, adds a request 6298 * interceptor with {@code addInterceptorLast(...)}, or replaces its redirect strategy or request executor (make 6299 * such changes before calling {@code super}), or if the builder is a 6300 * subclass that overrides {@link HttpClientBuilder#build()} or one of its exec-chain methods 6301 * ({@code createMainExec}, {@code decorateMainExec}, {@code decorateProtocolExec}), even an override that 6302 * returns or decorates nothing but what {@code super} built. Ordinary requests are unaffected. 6303 * </ul> 6304 * 6305 * <h4 class='section'>Example:</h4> 6306 * <p class='bjava'> 6307 * <jc>// A Builder that provides it's own customized HttpClient.</jc> 6308 * <jk>public class</jk> MyBuilder <jk>extends</jk> Builder { 6309 * <ja>@Override</ja> 6310 * <jk>protected</jk> HttpClientBuilder createHttpClient() { 6311 * <jk>return</jk> HttpClientBuilder.<jsm>create</jsm>().build(); 6312 * } 6313 * } 6314 * 6315 * <jc>// Instantiate.</jc> 6316 * RestClient <jv>client</jv> = <jk>new</jk> MyBuilder().build(); 6317 * </p> 6318 * 6319 * @return The HTTP client to use. 6320 */ 6321 protected CloseableHttpClient createHttpClient() { 6322 // A new connection manager for each client unless the caller supplied one: closing a client shuts its 6323 // connection manager down, so a reused builder must not hand an earlier client's to the next one. 6324 var cm = nn(connectionManager) ? connectionManager : createConnectionManager(); 6325 // Only a connection manager this builder created can be given a pinned twin; for any other one, the client 6326 // reports the SSRF guard as unsupported and refuses guarded remote calls. The twin is built from the same 6327 // socket factories and pool settings as the connection manager, so it is the same kind; settings an 6328 // override applied to that instance afterwards reach it before each guarded lease. 6329 ssrfGuard = nn(cm) && cm == defaultConnectionManager ? new SsrfGuardConnectionManager(cm, newConnectionManager(defaultRegistry, pinningResolver(), defaultPoolSettings)) : null; 6330 ownsConnectionManager = nn(ssrfGuard) && connectionManager == null && ! overridesCreateConnectionManager(getClass()); 6331 if (nn(ssrfGuard)) 6332 cm = ssrfGuard; 6333 httpClientBuilder().setConnectionManager(cm); 6334 // Once per HttpClientBuilder: a builder reused after build() keeps the interceptors earlier builds added. 6335 if (! HttpClientBuilderSettings.hasLastRequestInterceptor(httpClientBuilder(), ClassicRedirectCredentialGuard.class)) 6336 httpClientBuilder().addInterceptorLast(new ClassicRedirectCredentialGuard()); 6337 if (nn(ssrfGuard) && HttpClientBuilderSettings.isReadable()) { 6338 // The guard of a request travels on its context (see SsrfGuardMarker): the interceptor reads it before the 6339 // connection lease, and the executor refuses a guarded request on a connection of the ordinary pool. 6340 if (! HttpClientBuilderSettings.hasLastRequestInterceptor(httpClientBuilder(), SsrfGuardConnectionManager.GuardInterceptor.class)) 6341 httpClientBuilder().addInterceptorLast(new SsrfGuardConnectionManager.GuardInterceptor()); 6342 httpClientBuilder().setRequestExecutor(new SsrfGuardConnectionManager.GuardedRequestExecutor(HttpClientBuilderSettings.requestExecutor(httpClientBuilder()), ssrfGuard)); 6343 } 6344 httpClientBuilder().setRedirectStrategy(new PolicyAwareRedirectStrategy()); 6345 return httpClientBuilder().build(); 6346 } 6347 6348 // The shared pinning resolver unless this builder set per-client allowed address ranges, which need a resolver of their own. 6349 private PolicyPinningDnsResolver pinningResolver() { 6350 var ranges = RemoteUrlPolicy.AllowedRanges.of(allowedAddressRanges.toArray(new String[0])); 6351 return ranges.isEmpty() ? PolicyPinningDnsResolver.INSTANCE : new PolicyPinningDnsResolver(ranges); 6352 } 6353 6354 /** 6355 * Creates an instance of an {@link HttpClientBuilder} to be used to create the {@link HttpClient}. 6356 * 6357 * <p> 6358 * Subclasses can override this method to provide their own client builder. 6359 * The builder can also be specified using the {@link #httpClientBuilder(HttpClientBuilder)} method. 6360 * 6361 * <h4 class='section'>Example:</h4> 6362 * <p class='bjava'> 6363 * <jc>// A Builder that provides it's own customized HttpClientBuilder.</jc> 6364 * <jk>public class</jk> MyBuilder <jk>extends</jk> Builder { 6365 * <ja>@Override</ja> 6366 * <jk>protected</jk> HttpClientBuilder createHttpClientBuilder() { 6367 * <jk>return</jk> HttpClientBuilder.<jsm>create</jsm>(); 6368 * } 6369 * } 6370 * 6371 * <jc>// Instantiate.</jc> 6372 * RestClient <jv>client</jv> = <jk>new</jk> MyBuilder().build(); 6373 * </p> 6374 * 6375 * @return The HTTP client builder to use to create the HTTP client. 6376 */ 6377 protected HttpClientBuilder createHttpClientBuilder() { 6378 return HttpClientBuilder.create(); 6379 } 6380 6381 /** 6382 * Instantiates the parser group sub-builder. 6383 * 6384 * @return A new parser group sub-builder. 6385 */ 6386 protected ParserSet.Builder createParsers() { 6387 return ParserSet.create().marshallingContext(marshallingContext()); 6388 } 6389 6390 /** 6391 * Instantiates the part parser sub-builder. 6392 * 6393 * @return A new part parser sub-builder. 6394 */ 6395 protected HttpPartParser.Creator createPartParser() { 6396 return HttpPartParser.creator().type(OpenApiParser.class).marshallingContext(marshallingContext()); 6397 } 6398 6399 /** 6400 * Instantiates the part serializer sub-builder. 6401 * 6402 * @return A new part serializer sub-builder. 6403 */ 6404 protected HttpPartSerializer.Creator createPartSerializer() { 6405 return HttpPartSerializer.creator().type(OpenApiSerializer.class).marshallingContext(marshallingContext()); 6406 } 6407 6408 /** 6409 * Creates the builder for the path data list. 6410 * 6411 * <p> 6412 * Subclasses can override this method to provide their own implementation. 6413 * 6414 * <p> 6415 * The default behavior creates an empty builder. 6416 * 6417 * @return The path data list builder. 6418 * @see #pathData() 6419 */ 6420 protected PartList createPathData() { 6421 return PartList.create(); 6422 } 6423 6424 /** 6425 * Creates the builder for the query data list. 6426 * 6427 * <p> 6428 * Subclasses can override this method to provide their own implementation. 6429 * 6430 * <p> 6431 * The default behavior creates an empty builder. 6432 * 6433 * @return The query data list builder. 6434 * @see #queryData() 6435 */ 6436 protected PartList createQueryData() { 6437 return PartList.create(); 6438 } 6439 6440 /** 6441 * Instantiates the serializer group sub-builder. 6442 * 6443 * @return A new serializer group sub-builder. 6444 */ 6445 protected SerializerSet.Builder createSerializers() { 6446 return SerializerSet.create().marshallingContext(marshallingContext()); 6447 } 6448 6449 /** 6450 * Instantiates the URL-encoding serializer sub-builder. 6451 * 6452 * @return A new URL-encoding serializer sub-builder. 6453 */ 6454 protected UrlEncodingSerializer.Builder createUrlEncodingSerializer() { 6455 return UrlEncodingSerializer.create().marshallingContext(marshallingContext()); 6456 } 6457 6458 final CloseableHttpClient getHttpClient() { return nn(httpClient) ? httpClient : createHttpClient(); } 6459 } 6460 6461 /** 6462 * Concrete default builder leaf for the non-subclassed {@link RestClient#create()} / {@link RestClient#copy()} path. 6463 */ 6464 public static final class DefaultBuilder extends Builder<DefaultBuilder> { 6465 6466 DefaultBuilder() {} 6467 } 6468 6469 private static final RestCallInterceptor[] EMPTY_REST_CALL_INTERCEPTORS = {}; 6470 private static final ConcurrentHashMap<Class<?>,Context> requestContexts = new ConcurrentHashMap<>(); 6471 private static final BiPredicate<RestRequest,RestResponse> LOG_REQUESTS_PREDICATE_DEFAULT = (req, res) -> true; 6472 6473 /** 6474 * Instantiates a new clean-slate {@link Builder} object. 6475 * 6476 * @return A new {@link Builder} object. 6477 */ 6478 public static <T extends Builder<T>> Builder<T> create() { 6479 return (Builder<T>) new DefaultBuilder(); 6480 } 6481 6482 protected final boolean detectLeaks; 6483 protected final boolean allowPrivateUrls; 6484 private final RemoteUrlPolicy.AllowedRanges allowedAddressRanges; 6485 protected final boolean ignoreErrors; 6486 protected final boolean keepHttpClientOpen; 6487 protected final boolean skipEmptyFormData; 6488 protected final boolean skipEmptyHeaderData; 6489 protected final boolean skipEmptyQueryData; 6490 protected final BiPredicate<RestRequest,RestResponse> logRequestsPredicate; 6491 protected final CloseableHttpClient httpClient; 6492 protected final DetailLevel logRequests; 6493 protected final HeaderList headerData; 6494 protected final HttpPartParser partParser; 6495 protected final HttpPartSerializer partSerializer; 6496 protected final Level logRequestsLevel; 6497 protected final PartList formData; 6498 protected final PartList pathData; 6499 protected final PartList queryData; 6500 protected final ParserSet parsers; 6501 protected final RestCallInterceptor[] interceptors; 6502 protected final SerializerSet serializers; 6503 protected final UrlEncodingSerializer urlEncodingSerializer; // Used for form posts only. 6504 Predicate<Integer> errorCodes; 6505 private final WritableBeanStore beanStore; 6506 private final HttpClientConnectionManager connectionManager; 6507 private final Logger logger; 6508 private final Map<Class<?>,HttpPartParser> partParsers = new ConcurrentHashMap<>(); 6509 private final Map<Class<?>,HttpPartSerializer> partSerializers = new ConcurrentHashMap<>(); 6510 private final Pattern absUrlPattern = Pattern.compile("^\\w++://.*"); 6511 private final PrintStream console; 6512 private final RestCallHandler callHandler; 6513 private StackTraceElement[] closedStack; 6514 private final StackTraceElement[] creationStack; 6515 private final Supplier<String> rootUrl; 6516 private final boolean executorServiceShutdownOnClose; 6517 private final boolean logToConsole; 6518 private final boolean ssrfPolicySupported; 6519 6520 // Why SSRF-guard-active @Remote calls are refused, or null if they are supported. 6521 private final String ssrfRefusal; 6522 // The two-pool router this client's HttpClient uses, or null when the SSRF guard is unsupported. 6523 private final SsrfGuardConnectionManager ssrfGuard; 6524 6525 private final boolean ownsConnectionManager; 6526 private final AtomicBoolean isClosed = new AtomicBoolean(false); 6527 private final AtomicReference<ExecutorService> executorService = new AtomicReference<>(); 6528 6529 /** 6530 * Constructor. 6531 * 6532 * @param builder The builder for this client. 6533 */ 6534 public RestClient(Builder<?> builder) { 6535 super(builder); 6536 6537 beanStore = builder.beanStore.addBean(RestClient.class, this); 6538 6539 callHandler = builder.callHandler().run(); 6540 connectionManager = builder.connectionManager; 6541 console = nn(builder.console) ? builder.console : System.err; 6542 creationStack = isDebug() ? Thread.currentThread().getStackTrace() : null; 6543 detectLeaks = builder.detectLeaks; 6544 allowPrivateUrls = builder.allowPrivateUrls || Boolean.getBoolean(RemoteUrlPolicy.ALLOW_PRIVATE_URLS_PROPERTY); 6545 allowedAddressRanges = RemoteUrlPolicy.AllowedRanges.of(builder.allowedAddressRanges.toArray(new String[0])); 6546 errorCodes = builder.errorCodes; 6547 formData = builder.formData().copy(); 6548 headerData = builder.headers().copy(); 6549 httpClient = builder.getHttpClient(); 6550 // Read after getHttpClient(): the default createHttpClient() sets ssrfGuard. It wires it into the client it 6551 // builds, but an override of createHttpClient() or of HttpClientBuilder.build() may return another client. 6552 var builtGuard = builder.httpClient == null ? builder.ssrfGuard : null; 6553 ssrfGuard = nn(builtGuard) && builtGuard.isConnectionManagerOf(httpClient) ? builtGuard : null; 6554 ownsConnectionManager = nn(ssrfGuard) && builder.ownsConnectionManager; 6555 // The HttpClientBuilder is checked as it is now, not when the default createHttpClient() built from it: an override 6556 // may call super, change the builder and build again. What is checked: a builder subclass override, an 6557 // HttpProcessor, and whether what createHttpClient() wired (the guard's interceptors last, its redirect strategy and 6558 // request executor) is still in place. One of these changes made after the client was built is refused too (fail 6559 // closed): which client it went into cannot be told. A change undone before the override returns is not seen. 6560 ssrfRefusal = ssrfRefusal(builtGuard, nn(builtGuard) ? Builder.ssrfBuilderRefusal(builder.httpClientBuilder()) : null); 6561 ssrfPolicySupported = ssrfRefusal == null; 6562 ignoreErrors = builder.ignoreErrors; 6563 interceptors = nn(builder.interceptors) ? builder.interceptors.toArray(EMPTY_REST_CALL_INTERCEPTORS) : EMPTY_REST_CALL_INTERCEPTORS; 6564 keepHttpClientOpen = builder.keepHttpClientOpen; 6565 logger = nn(builder.logger) ? builder.logger : Logger.getLogger(cn(RestClient.class)); 6566 if (nn(builder.logRequests)) { 6567 logRequests = builder.logRequests; 6568 } else { 6569 logRequests = isDebug() ? DetailLevel.FULL : DetailLevel.NONE; 6570 } 6571 if (nn(builder.logRequestsLevel)) { 6572 logRequestsLevel = builder.logRequestsLevel; 6573 } else { 6574 logRequestsLevel = isDebug() ? Level.WARNING : Level.OFF; 6575 } 6576 logRequestsPredicate = nn(builder.logRequestsPredicate) ? builder.logRequestsPredicate : LOG_REQUESTS_PREDICATE_DEFAULT; 6577 logToConsole = builder.logToConsole || isDebug(); 6578 parsers = builder.parsers().build(); 6579 partParser = builder.partParser().create(); 6580 partSerializer = builder.partSerializer().create(); 6581 pathData = builder.pathData().copy(); 6582 queryData = builder.queryData().copy(); 6583 rootUrl = builder.rootUrl; 6584 serializers = builder.serializers().build(); 6585 skipEmptyFormData = builder.skipEmptyFormData; 6586 skipEmptyHeaderData = builder.skipEmptyHeaderData; 6587 skipEmptyQueryData = builder.skipEmptyQueryData; 6588 urlEncodingSerializer = builder.urlEncodingSerializer().build(); 6589 if (builder.executorService != null) 6590 executorService.set(builder.executorService); 6591 executorServiceShutdownOnClose = builder.executorServiceShutdownOnClose; 6592 6593 init(); 6594 } 6595 6596 /** 6597 * Returns the root URL set on this client. 6598 * 6599 * @return The root URL, or <jk>null</jk> if not set. 6600 */ 6601 public String getRootUrl() { 6602 return rootUrl != null ? rootUrl.get() : null; 6603 } 6604 6605 /** 6606 * Returns the effective builder/settings-level {@code allowPrivateUrls} opt-in for this client (the logical OR 6607 * of {@code Builder#allowPrivateUrls(boolean)} and the {@value RemoteUrlPolicy#ALLOW_PRIVATE_URLS_PROPERTY} 6608 * system property). 6609 * 6610 * <p> 6611 * The fully effective per-call value additionally ORs in the {@code @Remote}/{@code @RemoteOp} 6612 * {@code allowPrivateUrls} annotation attribute (see {@link Remote#allowPrivateUrls()}). 6613 * 6614 * @return {@code true} if this client opts into allowing private/loopback/link-local/metadata {@code @Remote} targets. 6615 */ 6616 public boolean isAllowPrivateUrls() { 6617 return allowPrivateUrls; 6618 } 6619 6620 /** 6621 * Returns the per-client allowed address ranges set through {@link Builder#allowAddressRanges(String...)}. 6622 * 6623 * @return The ranges; never <jk>null</jk>, empty when none were set. 6624 */ 6625 public RemoteUrlPolicy.AllowedRanges getAllowedAddressRanges() { 6626 return allowedAddressRanges; 6627 } 6628 6629 /** 6630 * Performs a REST call where the entire call is specified in a simple string. 6631 * 6632 * <p> 6633 * This method is useful for performing callbacks when the target of a callback is passed in 6634 * on an initial request, for example to signal when a long-running process has completed. 6635 * 6636 * <p> 6637 * The call string can be any of the following formats: 6638 * <ul class='spaced-list'> 6639 * <li> 6640 * <js>"[method] [uri]"</js> - e.g. <js>"GET http://localhost/callback"</js> 6641 * <li> 6642 * <js>"[method] [uri] [payload]"</js> - e.g. <js>"POST http://localhost/callback some text payload"</js> 6643 * <li> 6644 * <js>"[method] [headers] [uri] [payload]"</js> - e.g. <js>"POST {'Content-Type':'text/json'} http://localhost/callback {'some':'json'}"</js> 6645 * </ul> 6646 * <p> 6647 * The payload will always be sent using a simple {@link StringEntity}. 6648 * 6649 * @param callString The call string. 6650 * <br>Can be <jk>null</jk> or empty (treated as empty string, will result in an invalid request). 6651 * @return 6652 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 6653 * as a parsed object. 6654 * @throws RestCallException REST call failed. 6655 */ 6656 @SuppressWarnings({ 6657 "java:S1854", // state = S5 is a necessary state machine transition; SonarLint false positive 6658 "java:S4165" // state already holds S5 in some paths, but the assignment is a deliberate state machine transition 6659 }) 6660 public RestRequest callback(String callString) throws RestCallException { 6661 callString = emptyIfNull(callString); 6662 6663 // S1 - Looking for end of method. 6664 // S2 - Found end of method, looking for beginning of URI or headers. 6665 // S3 - Found beginning of headers, looking for end of headers. 6666 // S4 - Found end of headers, looking for beginning of URI. 6667 // S5 - Found beginning of URI, looking for end of URI. 6668 6669 var state = S1; 6670 6671 var mark = 0; 6672 String method = null; 6673 String headers = null; 6674 String uri = null; 6675 String content = null; 6676 for (var i = 0; i < callString.length(); i++) { 6677 var c = callString.charAt(i); 6678 if (state == S1) { 6679 if (isWhitespace(c)) { 6680 method = callString.substring(mark, i); 6681 state = S2; 6682 } 6683 } else if (state == S2) { 6684 if (! isWhitespace(c)) { 6685 mark = i; 6686 state = (c == '{') ? S3 : S5; 6687 } 6688 } else if (state == S3) { 6689 if (c == '}') { 6690 headers = callString.substring(mark, i + 1); 6691 state = S4; 6692 } 6693 } else if (state == S4) { 6694 if (! isWhitespace(c)) { 6695 mark = i; 6696 state = S5; 6697 } 6698 } else /* (state == S5) */ { 6699 if (isWhitespace(c)) { 6700 uri = callString.substring(mark, i); 6701 content = callString.substring(i).trim(); 6702 break; 6703 } 6704 } 6705 } 6706 6707 if (state != S5) 6708 throw new RestCallException(null, null, "Invalid format for call string. State=%s", state); 6709 6710 try { 6711 var req = request(method, uri, ine(content)); 6712 if (nn(headers)) 6713 Json5Map.ofString(headers).forEach((k, v) -> req.header(stringHeader(k, s(v)))); 6714 if (ine(content)) 6715 req.contentString(content); 6716 return req; 6717 } catch (ParseException e) { 6718 throw new RestCallException(null, e, "Invalid format for call string."); 6719 } 6720 } 6721 6722 /** 6723 * Calls {@link CloseableHttpClient#close()} on the underlying {@link CloseableHttpClient}. 6724 * 6725 * <p> 6726 * It's good practice to call this method after the client is no longer used. 6727 * 6728 * @throws IOException Thrown by underlying stream. 6729 */ 6730 @Override 6731 public void close() throws IOException { 6732 isClosed.set(true); 6733 ExecutorService es = executorService.get(); 6734 if (! keepHttpClientOpen) { 6735 try { 6736 httpClient.close(); 6737 } finally { 6738 shutdownPinnedPool(); 6739 } 6740 } 6741 if (nn(es) && executorServiceShutdownOnClose) 6742 es.shutdown(); 6743 // If executorServiceShutdownOnClose is false, executor service remains open for reuse 6744 if (nn(creationStack)) 6745 closedStack = Thread.currentThread().getStackTrace(); 6746 } 6747 6748 // The pinned pool is always this client's own (nothing else can reach it), and so is the ordinary pool when this 6749 // client's build() created it, so they are shut down with the client even when the connection manager is shared 6750 // and the HttpClient therefore leaves it open. 6751 private void shutdownPinnedPool() { 6752 if (ownsConnectionManager) 6753 ssrfGuard.shutdown(); 6754 else if (nn(ssrfGuard)) 6755 ssrfGuard.shutdownPinned(); 6756 } 6757 6758 /** 6759 * Same as {@link #close()}, but ignores any exceptions. 6760 */ 6761 public void closeQuietly() { 6762 isClosed.set(true); 6763 try { 6764 if (! keepHttpClientOpen) { 6765 try { 6766 httpClient.close(); 6767 } finally { 6768 shutdownPinnedPool(); 6769 } 6770 } 6771 ExecutorService es = executorService.get(); 6772 if (nn(es) && executorServiceShutdownOnClose) 6773 es.shutdown(); 6774 } catch (@SuppressWarnings("unused") Exception t) { /* Suppress close/shutdown exceptions during cleanup */ } 6775 if (nn(creationStack)) 6776 closedStack = Thread.currentThread().getStackTrace(); 6777 } 6778 6779 @Override /* Overridden from Context */ 6780 public Builder copy() { 6781 throw new NoSuchMethodError("Not implemented."); 6782 } 6783 6784 /** 6785 * Creates a mutable copy of the form data defined on this client. 6786 * 6787 * <p> 6788 * Used during the construction of {@link RestRequest} objects. 6789 * 6790 * <p> 6791 * Subclasses can override this method to provide their own builder. 6792 * 6793 * @return A new builder. 6794 */ 6795 public PartList createFormData() { 6796 return formData.copy(); 6797 } 6798 6799 /** 6800 * Creates a mutable copy of the header data defined on this client. 6801 * 6802 * <p> 6803 * Used during the construction of {@link RestRequest} objects. 6804 * 6805 * <p> 6806 * Subclasses can override this method to provide their own builder. 6807 * 6808 * @return A new builder. 6809 */ 6810 public HeaderList createHeaderData() { 6811 return headerData.copy(); 6812 } 6813 6814 /** 6815 * Creates a mutable copy of the path data defined on this client. 6816 * 6817 * <p> 6818 * Used during the construction of {@link RestRequest} objects. 6819 * 6820 * <p> 6821 * Subclasses can override this method to provide their own builder. 6822 * 6823 * @return A new builder. 6824 */ 6825 public PartList createPathData() { 6826 return pathData.copy(); 6827 } 6828 6829 /** 6830 * Creates a mutable copy of the query data defined on this client. 6831 * 6832 * <p> 6833 * Used during the construction of {@link RestRequest} objects. 6834 * 6835 * <p> 6836 * Subclasses can override this method to provide their own builder. 6837 * 6838 * @return A new builder. 6839 */ 6840 public PartList createQueryData() { 6841 return queryData.copy(); 6842 } 6843 6844 /** 6845 * Perform a <c>DELETE</c> request against the specified URI. 6846 * 6847 * @param uri 6848 * The URI of the remote REST resource. 6849 * <br>Can be any of the following types: 6850 * <ul> 6851 * <li>{@link URIBuilder} 6852 * <li>{@link URI} 6853 * <li>{@link URL} 6854 * <li>{@link String} 6855 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 6856 * </ul> 6857 * @return 6858 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 6859 * as a parsed object. 6860 * @throws RestCallException If any authentication errors occurred. 6861 */ 6862 public RestRequest delete(Object uri) throws RestCallException { 6863 return request(op("DELETE", uri, NO_BODY)); 6864 } 6865 6866 /** 6867 * Executes HTTP request using the default context. 6868 * 6869 * <h4 class='section'>Notes:</h4><ul> 6870 * <li class='note'>This method gets passed on directly to the underlying {@link HttpClient} class. 6871 * </ul> 6872 * 6873 * @param target The target host for the request. 6874 * <br>Implementations may accept <jk>null</jk> if they can still determine a route, for example to a default 6875 * target or by inspecting the request. 6876 * @param request The request to execute. 6877 * @return The response to the request. 6878 * <br>This is always a final response, never an intermediate response with an 1xx status code. 6879 * <br>Whether redirects or authentication challenges will be returned or handled automatically depends on the 6880 * implementation and configuration of this client. 6881 * @throws IOException In case of a problem or the connection was aborted. 6882 * @throws ClientProtocolException In case of an http protocol error. 6883 */ 6884 @Override /* Overridden from HttpClient */ 6885 public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException { 6886 return httpClient.execute(target, request); 6887 } 6888 6889 /** 6890 * Executes HTTP request using the given context. 6891 * 6892 * <h4 class='section'>Notes:</h4><ul> 6893 * <li class='note'>This method gets passed on directly to the underlying {@link HttpClient} class. 6894 * <li class='note'>The {@link #run(HttpHost,HttpRequest,HttpContext)} method has been provided as a wrapper around this method. 6895 * Subclasses can override these methods for handling requests with and without bodies separately. 6896 * <li class='note'>The {@link RestCallHandler} interface can also be implemented to intercept this method. 6897 * </ul> 6898 * 6899 * @param target The target host for the request. 6900 * <br>Implementations may accept <jk>null</jk> if they can still determine a route, for example to a default 6901 * target or by inspecting the request. 6902 * @param request The request to execute. 6903 * @param context The context to use for the execution, or <jk>null</jk> to use the default context. 6904 * @return 6905 * The response to the request. 6906 * <br>This is always a final response, never an intermediate response with an 1xx status code. 6907 * <br>Whether redirects or authentication challenges will be returned or handled automatically depends on the 6908 * implementation and configuration of this client. 6909 * @throws IOException In case of a problem or the connection was aborted. 6910 * @throws ClientProtocolException In case of an http protocol error. 6911 */ 6912 @Override /* Overridden from HttpClient */ 6913 public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { 6914 return httpClient.execute(target, request, context); 6915 } 6916 6917 /** 6918 * Executes HTTP request to the target using the default context and processes the response using the given response handler. 6919 * 6920 * <p> 6921 * The content entity associated with the response is fully consumed and the underlying connection is released back 6922 * to the connection manager automatically in all cases relieving individual {@link ResponseHandler ResponseHandlers} 6923 * from having to manage resource deallocation internally. 6924 * 6925 * <h4 class='section'>Notes:</h4><ul> 6926 * <li class='note'>This method gets passed on directly to the underlying {@link HttpClient} class. 6927 * </ul> 6928 * 6929 * @param target 6930 * The target host for the request. 6931 * <br>Implementations may accept <jk>null</jk> if they can still determine a route, for example to a default target or by inspecting the request. 6932 * @param request The request to execute. 6933 * @param responseHandler The response handler. 6934 * @return The response object as generated by the response handler. 6935 * @throws IOException In case of a problem or the connection was aborted. 6936 * @throws ClientProtocolException In case of an http protocol error. 6937 */ 6938 @Override /* Overridden from HttpClient */ 6939 public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler) throws IOException { 6940 return httpClient.execute(target, request, responseHandler); 6941 } 6942 6943 /** 6944 * Executes a request using the default context and processes the response using the given response handler. 6945 * 6946 * <p> 6947 * The content entity associated with the response is fully consumed and the underlying connection is released back 6948 * to the connection manager automatically in all cases relieving individual {@link ResponseHandler ResponseHandlers} 6949 * from having to manage resource deallocation internally. 6950 * 6951 * <h4 class='section'>Notes:</h4><ul> 6952 * <li class='note'>This method gets passed on directly to the underlying {@link HttpClient} class. 6953 * </ul> 6954 * 6955 * @param target 6956 * The target host for the request. 6957 * <br>Implementations may accept <jk>null</jk> if they can still determine a route, for example to a default target or by inspecting the request. 6958 * @param request The request to execute. 6959 * @param responseHandler The response handler. 6960 * @param context The context to use for the execution, or <jk>null</jk> to use the default context. 6961 * @return The response object as generated by the response handler. 6962 * @throws IOException In case of a problem or the connection was aborted. 6963 * @throws ClientProtocolException In case of an http protocol error. 6964 */ 6965 @Override /* Overridden from HttpClient */ 6966 public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException { 6967 return httpClient.execute(target, request, responseHandler, context); 6968 } 6969 6970 /** 6971 * Executes HTTP request using the default context. 6972 * 6973 * <h4 class='section'>Notes:</h4><ul> 6974 * <li class='note'>This method gets passed on directly to the underlying {@link HttpClient} class. 6975 * </ul> 6976 * 6977 * @param request The request to execute. 6978 * @return 6979 * The response to the request. 6980 * <br>This is always a final response, never an intermediate response with an 1xx status code. 6981 * <br>Whether redirects or authentication challenges will be returned or handled automatically depends on the 6982 * implementation and configuration of this client. 6983 * @throws IOException In case of a problem or the connection was aborted. 6984 * @throws ClientProtocolException In case of an http protocol error. 6985 */ 6986 @Override /* Overridden from HttpClient */ 6987 public HttpResponse execute(HttpUriRequest request) throws IOException { 6988 return httpClient.execute(request); 6989 } 6990 6991 /** 6992 * Executes HTTP request using the given context. 6993 * 6994 * <h4 class='section'>Notes:</h4><ul> 6995 * <li class='note'>This method gets passed on directly to the underlying {@link HttpClient} class. 6996 * </ul> 6997 * 6998 * @param request The request to execute. 6999 * @param context The context to use for the execution, or <jk>null</jk> to use the default context. 7000 * @return 7001 * The response to the request. 7002 * <br>This is always a final response, never an intermediate response with an 1xx status code. 7003 * <br>Whether redirects or authentication challenges will be returned or handled automatically depends on the 7004 * implementation and configuration of this client. 7005 * @throws IOException In case of a problem or the connection was aborted. 7006 * @throws ClientProtocolException In case of an http protocol error. 7007 */ 7008 @Override /* Overridden from HttpClient */ 7009 public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException { 7010 return httpClient.execute(request, context); 7011 } 7012 7013 /** 7014 * Executes HTTP request using the default context and processes the response using the given response handler. 7015 * 7016 * <p> 7017 * The content entity associated with the response is fully consumed and the underlying connection is released back 7018 * to the connection manager automatically in all cases relieving individual {@link ResponseHandler ResponseHandlers} 7019 * from having to manage resource deallocation internally. 7020 * 7021 * <h4 class='section'>Notes:</h4><ul> 7022 * <li class='note'>This method gets passed on directly to the underlying {@link HttpClient} class. 7023 * </ul> 7024 * 7025 * @param request The request to execute. 7026 * @param responseHandler The response handler. 7027 * @return Object returned by response handler. 7028 * @throws IOException In case of a problem or the connection was aborted. 7029 * @throws ClientProtocolException In case of an http protocol error. 7030 */ 7031 @Override /* Overridden from HttpClient */ 7032 public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException { 7033 return httpClient.execute(request, responseHandler); 7034 } 7035 7036 /** 7037 * Executes HTTP request using the given context and processes the response using the given response handler. 7038 * 7039 * <p> 7040 * The content entity associated with the response is fully consumed and the underlying connection is released back 7041 * to the connection manager automatically in all cases relieving individual {@link ResponseHandler ResponseHandlers} 7042 * from having to manage resource deallocation internally. 7043 * 7044 * <h4 class='section'>Notes:</h4><ul> 7045 * <li class='note'>This method gets passed on directly to the underlying {@link HttpClient} class. 7046 * </ul> 7047 * 7048 * @param request The request to execute. 7049 * @param responseHandler The response handler. 7050 * @param context The context to use for the execution, or <jk>null</jk> to use the default context. 7051 * @return The response object as generated by the response handler. 7052 * @throws IOException In case of a problem or the connection was aborted. 7053 * @throws ClientProtocolException In case of an http protocol error. 7054 */ 7055 @Override /* Overridden from HttpClient */ 7056 public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException { 7057 return httpClient.execute(request, responseHandler, context); 7058 } 7059 7060 /** 7061 * Same as {@link #formPost(Object, Object)} but doesn't specify the input yet. 7062 * 7063 * @param uri 7064 * The URI of the remote REST resource. 7065 * <br>Can be any of the following types: 7066 * <ul> 7067 * <li>{@link URIBuilder} 7068 * <li>{@link URI} 7069 * <li>{@link URL} 7070 * <li>{@link String} 7071 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7072 * </ul> 7073 * @return 7074 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7075 * as a parsed object. 7076 * @throws RestCallException If any authentication errors occurred. 7077 */ 7078 public RestRequest formPost(Object uri) throws RestCallException { 7079 return request(op("POST", uri, NO_BODY)); 7080 } 7081 7082 /** 7083 * Perform a <c>POST</c> request with a content type of <c>application/x-www-form-urlencoded</c> 7084 * against the specified URI. 7085 * 7086 * @param uri 7087 * The URI of the remote REST resource. 7088 * <br>Can be any of the following types: 7089 * <ul> 7090 * <li>{@link URIBuilder} 7091 * <li>{@link URI} 7092 * <li>{@link URL} 7093 * <li>{@link String} 7094 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7095 * </ul> 7096 * @param body 7097 * The object to serialize and transmit to the URI as the body of the request. 7098 * <ul class='spaced-list'> 7099 * <li>{@link NameValuePair} - URL-encoded as a single name-value pair. 7100 * <li>{@link NameValuePair} array - URL-encoded as name value pairs. 7101 * <li>{@link PartList} - URL-encoded as name value pairs. 7102 * <li>{@link Reader}/{@link InputStream}- Streamed directly and <l>Content-Type</l> set to <js>"application/x-www-form-urlencoded"</js> 7103 * <li>{@link HttpResource} - Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. 7104 * <li>{@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 7105 * <li>{@link Object} - Converted to a {@link SerializedEntity} using {@link UrlEncodingSerializer} to serialize. 7106 * <li>{@link Supplier} - A supplier of anything on this list. 7107 * </ul> 7108 * @return 7109 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7110 * as a parsed object. 7111 * @throws RestCallException If any authentication errors occurred. 7112 */ 7113 public RestRequest formPost(Object uri, Object body) throws RestCallException { 7114 var req = request(op("POST", uri, NO_BODY)); 7115 try { 7116 if (body instanceof Supplier<?> body2) 7117 body = body2.get(); 7118 if (body instanceof NameValuePair body2) 7119 return req.content(new UrlEncodedFormEntity(l(body2))); 7120 if (body instanceof NameValuePair[] namevaluepairArray) 7121 return req.content(new UrlEncodedFormEntity(l(namevaluepairArray))); 7122 if (body instanceof PartList body2) 7123 return req.content(new UrlEncodedFormEntity(body2)); 7124 if (body instanceof HttpResource body2) 7125 body2.getHeaders().forEach(req::header); 7126 if (body instanceof HttpEntity body2) { 7127 if (body2.getContentType() == null) 7128 req.header(ContentType.APPLICATION_FORM_URLENCODED); 7129 return req.content(body2); 7130 } 7131 if (body instanceof Reader || body instanceof InputStream) 7132 return req.header(ContentType.APPLICATION_FORM_URLENCODED).content(body); 7133 return req.content(serializedEntity(body, urlEncodingSerializer, null)); 7134 } catch (IOException e) { 7135 throw new RestCallException(null, e, "Could not read form post body."); 7136 } 7137 } 7138 7139 /** 7140 * Perform a <c>POST</c> request with a content type of <c>application/x-www-form-urlencoded</c> 7141 * against the specified URI. 7142 * 7143 * @param uri 7144 * The URI of the remote REST resource. 7145 * <br>Can be any of the following types: 7146 * <ul> 7147 * <li>{@link URIBuilder} 7148 * <li>{@link URI} 7149 * <li>{@link URL} 7150 * <li>{@link String} 7151 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7152 * </ul> 7153 * @param parameters 7154 * The parameters of the form post. 7155 * <br>The parameters represent name/value pairs and must be an even number of arguments. 7156 * <br>Parameters are converted to {@link BasicPart} objects. 7157 * @return 7158 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7159 * as a parsed object. 7160 * @throws RestCallException If any authentication errors occurred. 7161 */ 7162 public RestRequest formPostPairs(Object uri, String...parameters) throws RestCallException { 7163 return formPost(uri, partList(parameters)); 7164 } 7165 7166 /** 7167 * Perform a <c>GET</c> request against the root URI. 7168 * 7169 * @return 7170 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7171 * as a parsed object. 7172 * @throws RestCallException If any authentication errors occurred. 7173 */ 7174 public RestRequest get() throws RestCallException { 7175 return request(op("GET", null, NO_BODY)); 7176 } 7177 7178 /** 7179 * Perform a <c>GET</c> request against the specified URI. 7180 * 7181 * @param uri 7182 * The URI of the remote REST resource. 7183 * <br>Can be any of the following types: 7184 * <ul> 7185 * <li>{@link URIBuilder} 7186 * <li>{@link URI} 7187 * <li>{@link URL} 7188 * <li>{@link String} 7189 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7190 * </ul> 7191 * @return 7192 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7193 * as a parsed object. 7194 * @throws RestCallException If any authentication errors occurred. 7195 */ 7196 public RestRequest get(Object uri) throws RestCallException { 7197 return request(op("GET", uri, NO_BODY)); 7198 } 7199 7200 /** 7201 * Obtains the connection manager used by this client. 7202 * 7203 * @return The connection manager. 7204 * @deprecated Use {@link HttpClientBuilder}. 7205 */ 7206 @Deprecated(since = "10.0", forRemoval = true) 7207 @Override /* Overridden from HttpClient */ 7208 public ClientConnectionManager getConnectionManager() { return httpClient.getConnectionManager(); } 7209 7210 /** 7211 * Returns the connection manager if one was specified in the client builder. 7212 * 7213 * @return The connection manager. May be <jk>null</jk>. 7214 */ 7215 public HttpClientConnectionManager getHttpClientConnectionManager() { return connectionManager; } 7216 7217 /** 7218 * Obtains the parameters for this client. 7219 * 7220 * These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client. 7221 * 7222 * @return The default parameters. 7223 * @deprecated Use {@link RequestConfig}. 7224 */ 7225 @Deprecated(since = "10.0", forRemoval = true) 7226 @Override /* Overridden from HttpClient */ 7227 public HttpParams getParams() { return httpClient.getParams(); } 7228 7229 /** 7230 * Create a new proxy interface against a 3rd-party REST interface. 7231 * 7232 * <p> 7233 * The URI to the REST interface is based on the following values: 7234 * <ul> 7235 * <li>The {@link Remote#path() @Remote(path)} annotation on the interface (<c>remote-path</c>). 7236 * <li>The {@link Builder#rootUrl(Object) rootUrl} on the client (<c>root-url</c>). 7237 * <li>The fully-qualified class name of the interface (<c>class-name</c>). 7238 * </ul> 7239 * 7240 * <p> 7241 * The URI calculation is as follows: 7242 * <ul> 7243 * <li><c>remote-path</c> - If remote path is absolute. 7244 * <li><c>root-uri/remote-path</c> - If remote path is relative and root-uri has been specified. 7245 * <li><c>root-uri/class-name</c> - If remote path is not specified. 7246 * </ul> 7247 * 7248 * <p> 7249 * If the information is not available to resolve to an absolute URI, a {@link RemoteMetadataException} is thrown. 7250 * 7251 * <h4 class='section'>Examples:</h4> 7252 * <p class='bjava'> 7253 * <jk>package</jk> org.apache.foo; 7254 * 7255 * <ja>@RemoteResource</ja>(path=<js>"http://hostname/resturi/myinterface1"</js>) 7256 * <jk>public interface</jk> MyInterface1 { ... } 7257 * 7258 * <ja>@RemoteResource</ja>(path=<js>"/myinterface2"</js>) 7259 * <jk>public interface</jk> MyInterface2 { ... } 7260 * 7261 * <jk>public interface</jk> MyInterface3 { ... } 7262 * 7263 * <jc>// Resolves to "http://localhost/resturi/myinterface1"</jc> 7264 * MyInterface1 <jv>interface1</jv> = RestClient 7265 * .<jsm>create</jsm>() 7266 * .build() 7267 * .getRemote(MyInterface1.<jk>class</jk>); 7268 * 7269 * <jc>// Resolves to "http://hostname/resturi/myinterface2"</jc> 7270 * MyInterface2 <jv>interface2</jv> = RestClient 7271 * .<jsm>create</jsm>() 7272 * .rootUrl(<js>"http://hostname/resturi"</js>) 7273 * .build() 7274 * .getRemote(MyInterface2.<jk>class</jk>); 7275 * 7276 * <jc>// Resolves to "http://hostname/resturi/org.apache.foo.MyInterface3"</jc> 7277 * MyInterface3 <jv>interface3</jv> = RestClient 7278 * .<jsm>create</jsm>() 7279 * .rootUrl(<js>"http://hostname/resturi"</js>) 7280 * .build() 7281 * .getRemote(MyInterface3.<jk>class</jk>); 7282 * </p> 7283 * 7284 * <h4 class='section'>Notes:</h4><ul> 7285 * <li class='note'> 7286 * If you plan on using your proxy in a multi-threaded environment, you'll want to use an underlying 7287 * pooling client connection manager. 7288 * </ul> 7289 * 7290 * <h4 class='section'>See Also:</h4><ul> 7291 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestProxies">REST Proxies</a> 7292 * </ul> 7293 * 7294 * @param <T> The interface to create a proxy for. 7295 * @param interfaceClass The interface to create a proxy for. 7296 * <br>Cannot be <jk>null</jk>. 7297 * @return The new proxy interface. 7298 * @throws RemoteMetadataException If the REST URI cannot be determined based on the information given. 7299 */ 7300 public <T> T getRemote(Class<T> interfaceClass) { 7301 return getRemote(interfaceClass, null); 7302 } 7303 7304 /** 7305 * Same as {@link #getRemote(Class)} except explicitly specifies the URI of the REST interface. 7306 * 7307 * <h4 class='section'>See Also:</h4><ul> 7308 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestProxies">REST Proxies</a> 7309 * </ul> 7310 * 7311 * @param <T> The interface to create a proxy for. 7312 * @param interfaceClass The interface to create a proxy for. 7313 * <br>Cannot be <jk>null</jk>. 7314 * @param rootUrl The URI of the REST interface. 7315 * <br>Can be <jk>null</jk> (will use the root URL from the client builder if set). 7316 * @return The new proxy interface. 7317 */ 7318 public <T> T getRemote(Class<T> interfaceClass, Object rootUrl) { 7319 return getRemote(interfaceClass, rootUrl, null, null); 7320 } 7321 7322 /** 7323 * Same as {@link #getRemote(Class, Object)} but allows you to override the serializer and parser used. 7324 * 7325 * <h4 class='section'>See Also:</h4><ul> 7326 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestProxies">REST Proxies</a> 7327 * </ul> 7328 7329 * @param <T> The interface to create a proxy for. 7330 * @param interfaceClass The interface to create a proxy for. 7331 * <br>Cannot be <jk>null</jk>. 7332 * @param rootUrl The URI of the REST interface. 7333 * <br>Can be <jk>null</jk> (will use the root URL from the client builder if set). 7334 * @param serializer The serializer used to serialize POJOs to the body of the HTTP request. 7335 * <br>Can be <jk>null</jk> (will use the default serializer from the client). 7336 * @param parser The parser used to parse POJOs from the body of the HTTP response. 7337 * <br>Can be <jk>null</jk> (will use the default parser from the client). 7338 * @return The new proxy interface. 7339 */ 7340 @SuppressWarnings({ 7341 "java:S6541" // Brain method acceptable - remote proxy creation requires complex initialization logic 7342 }) 7343 public <T> T getRemote(Class<T> interfaceClass, Object rootUrl, Serializer serializer, Parser parser) { 7344 7345 reqnn("interfaceClass", interfaceClass); 7346 7347 if (rootUrl == null) 7348 rootUrl = this.rootUrl != null ? this.rootUrl.get() : null; 7349 7350 final String restUrl2 = trimSlashes(emptyIfNull(rootUrl)); 7351 7352 return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), a(interfaceClass), new InvocationHandler() { 7353 7354 final RemoteMeta rm = new RemoteMeta(interfaceClass); 7355 7356 @Override /* Overridden from InvocationHandler */ 7357 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 7358 var rom = rm.getOperationMeta(method); 7359 7360 // Resolve the effective request URL (interface/method baseUrl + @Url overrides, with the SSRF guard). 7361 var uri = resolveRemoteUri(interfaceClass, restUrl2, method, rom, rm, args); 7362 7363 var ror = rom.getReturns(); 7364 if (ror.isFuture()) { 7365 return getExecutorService().submit(() -> { 7366 try { 7367 return executeRemoteWithRetry(uri, serializer, parser, method, rom, rm, args); 7368 } catch (Exception e) { 7369 throw toRex(e); 7370 } 7371 }); 7372 } else if (ror.isCompletableFuture()) { 7373 var cf = new CompletableFuture<>(); 7374 getExecutorService().submit(() -> { 7375 try { 7376 cf.complete(executeRemoteWithRetry(uri, serializer, parser, method, rom, rm, args)); 7377 } catch (Exception e) { 7378 cf.completeExceptionally(e); 7379 } 7380 return null; 7381 }); 7382 return cf; 7383 } 7384 7385 try { 7386 return executeRemoteWithRetry(uri, serializer, parser, method, rom, rm, args); 7387 } catch (Exception e) { 7388 // Check if this is a RuntimeException wrapping a RestCallException with an Error cause 7389 if (e instanceof RuntimeException e2 && e2.getCause() instanceof RestCallException rce) { 7390 var t = rce.getCause(); 7391 if (nn(t)) { 7392 // Check if the cause matches the method's declared exception types 7393 for (var t2 : method.getExceptionTypes()) 7394 if (t2.isInstance(t)) 7395 throw t; // Rethrow the original Throwable (can be Error) 7396 } 7397 } 7398 throw e; 7399 } 7400 } 7401 }); 7402 } 7403 7404 /** 7405 * Create a new proxy interface against an RRPC-style service. 7406 * 7407 * <p> 7408 * Remote interfaces are interfaces exposed on the server side using either the <c>RrpcServlet</c> 7409 * or <c>RRPC</c> REST methods. 7410 * 7411 * <p> 7412 * The URI to the REST interface is based on the following values: 7413 * <ul> 7414 * <li>The {@link Remote#path() @Remote(path)} annotation on the interface (<c>remote-path</c>). 7415 * <li>The {@link Builder#rootUrl(Object) rootUrl} on the client (<c>root-url</c>). 7416 * <li>The fully-qualified class name of the interface (<c>class-name</c>). 7417 * </ul> 7418 * 7419 * <p> 7420 * The URI calculation is as follows: 7421 * <ul> 7422 * <li><c>remote-path</c> - If remote path is absolute. 7423 * <li><c>root-url/remote-path</c> - If remote path is relative and root-url has been specified. 7424 * <li><c>root-url/class-name</c> - If remote path is not specified. 7425 * </ul> 7426 * 7427 * <p> 7428 * If the information is not available to resolve to an absolute URI, a {@link RemoteMetadataException} is thrown. 7429 * 7430 * <h4 class='section'>Notes:</h4><ul> 7431 * <li class='note'> 7432 * If you plan on using your proxy in a multi-threaded environment, you'll want to use an underlying 7433 * pooling client connection manager. 7434 * </ul> 7435 * 7436 * <h4 class='section'>See Also:</h4><ul> 7437 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestRpc">REST/RPC</a> 7438 * </ul> 7439 * 7440 * @param <T> The interface to create a proxy for. 7441 * @param interfaceClass The interface to create a proxy for. 7442 * <br>Cannot be <jk>null</jk>. 7443 * @return The new proxy interface. 7444 * @throws RemoteMetadataException If the REST URI cannot be determined based on the information given. 7445 */ 7446 public <T> T getRrpcInterface(Class<T> interfaceClass) { 7447 return getRrpcInterface(interfaceClass, null); 7448 } 7449 7450 /** 7451 * Same as {@link #getRrpcInterface(Class)} except explicitly specifies the URI of the REST interface. 7452 * 7453 * <h4 class='section'>See Also:</h4><ul> 7454 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestRpc">REST/RPC</a> 7455 * </ul> 7456 * 7457 * @param <T> The interface to create a proxy for. 7458 * @param interfaceClass The interface to create a proxy for. 7459 * <br>Cannot be <jk>null</jk>. 7460 * @param uri The URI of the REST interface. 7461 * <br>Can be <jk>null</jk> (will use the root URL from the client builder if set). 7462 * @return The new proxy interface. 7463 */ 7464 public <T> T getRrpcInterface(Class<T> interfaceClass, Object uri) { 7465 return getRrpcInterface(interfaceClass, uri, null, null); 7466 } 7467 7468 /** 7469 * Same as {@link #getRrpcInterface(Class, Object)} but allows you to override the serializer and parser used. 7470 * 7471 * <h4 class='section'>See Also:</h4><ul> 7472 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestRpc">REST/RPC</a> 7473 * </ul> 7474 * 7475 * @param <T> The interface to create a proxy for. 7476 * @param interfaceClass The interface to create a proxy for. 7477 * <br>Cannot be <jk>null</jk>. 7478 * @param uri The URI of the REST interface. 7479 * <br>Can be <jk>null</jk> (will use the root URL from the client builder if set). 7480 * @param serializer The serializer used to serialize POJOs to the body of the HTTP request. 7481 * <br>Can be <jk>null</jk> (will use the default serializer from the client). 7482 * @param parser The parser used to parse POJOs from the body of the HTTP response. 7483 * <br>Can be <jk>null</jk> (will use the default parser from the client). 7484 * @return The new proxy interface. 7485 */ 7486 public <T> T getRrpcInterface(Class<T> interfaceClass, Object uri, Serializer serializer, Parser parser) { 7487 7488 if (uri == null) { 7489 var rm = new RrpcInterfaceMeta(interfaceClass, ""); 7490 var path = rm.getPath(); 7491 if (path.indexOf("://") == -1) { 7492 var rootUrlValue = rootUrl != null ? rootUrl.get() : null; 7493 if (isEmpty(rootUrlValue)) 7494 throw new RemoteMetadataException(interfaceClass, "Root URI has not been specified. Cannot construct absolute path to remote interface."); 7495 path = trimSlashes(rootUrlValue) + '/' + path; 7496 } 7497 uri = path; 7498 } 7499 7500 final String restUrl2 = s(uri); 7501 7502 return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), a(interfaceClass), new InvocationHandler() { 7503 7504 final RrpcInterfaceMeta rm = new RrpcInterfaceMeta(interfaceClass, restUrl2); 7505 7506 @Override /* Overridden from InvocationHandler */ 7507 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 7508 var rim = rm.getMethodMeta(method); 7509 7510 var uri = rim.getUri(); 7511 RestResponse res; 7512 7513 try { 7514 // @formatter:off 7515 RestRequest rc = request("POST", uri, true) 7516 .serializer(serializer) 7517 .content(args) 7518 .rethrow(RuntimeException.class) 7519 .rethrow(method.getExceptionTypes()); 7520 // @formatter:on 7521 7522 res = rc.run(); 7523 7524 var v = res.getContent().as(method.getGenericReturnType()); 7525 if (v == null && method.getReturnType().isPrimitive()) 7526 v = ClassInfo.of(method.getReturnType()).getPrimitiveDefault(); 7527 return v; 7528 7529 } catch (Exception e) { 7530 // Check if this is a RuntimeException wrapping a RestCallException with an Error cause 7531 if (e instanceof RuntimeException e2 && e2.getCause() instanceof RestCallException rce) { 7532 var t = rce.getCause(); 7533 if (nn(t)) { 7534 // Check if the cause matches the method's declared exception types 7535 for (var t2 : method.getExceptionTypes()) 7536 if (t2.isInstance(t)) 7537 throw t; // Rethrow the original Throwable (can be Error) 7538 } 7539 } 7540 if (e instanceof RestCallException e2) { 7541 var t = e2.getCause(); 7542 if (nn(t)) { 7543 // Check if the cause matches the method's declared exception types 7544 for (var t2 : method.getExceptionTypes()) 7545 if (t2.isInstance(t)) 7546 throw t; // Rethrow the original Throwable (can be Error) 7547 if (t instanceof Exception t2) 7548 e = t2; 7549 } 7550 } 7551 if (e instanceof RuntimeException e2) 7552 throw e2; 7553 for (var t2 : method.getExceptionTypes()) 7554 if (t2.isInstance(e)) 7555 throw e; 7556 throw toRex(e); 7557 } 7558 } 7559 }); 7560 } 7561 7562 /** 7563 * Perform a <c>HEAD</c> request against the specified URI. 7564 * 7565 * @param uri 7566 * The URI of the remote REST resource. 7567 * <br>Can be any of the following types: 7568 * <ul> 7569 * <li>{@link URIBuilder} 7570 * <li>{@link URI} 7571 * <li>{@link URL} 7572 * <li>{@link String} 7573 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7574 * </ul> 7575 * @return 7576 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7577 * as a parsed object. 7578 * @throws RestCallException If any authentication errors occurred. 7579 */ 7580 public RestRequest head(Object uri) throws RestCallException { 7581 return request(op("HEAD", uri, NO_BODY)); 7582 } 7583 7584 /** 7585 * Perform an <c>OPTIONS</c> request against the specified URI. 7586 * 7587 * @param uri 7588 * The URI of the remote REST resource. 7589 * <br>Can be any of the following types: 7590 * <ul> 7591 * <li>{@link URIBuilder} 7592 * <li>{@link URI} 7593 * <li>{@link URL} 7594 * <li>{@link String} 7595 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7596 * </ul> 7597 * @return 7598 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7599 * as a parsed object. 7600 * @throws RestCallException If any authentication errors occurred. 7601 */ 7602 public RestRequest options(Object uri) throws RestCallException { 7603 return request(op("OPTIONS", uri, NO_BODY)); 7604 } 7605 7606 /** 7607 * Same as {@link #patch(Object, Object)} but don't specify the input yet. 7608 * 7609 * <p> 7610 * You must call {@link RestRequest#content(Object)} to set the contents on the result object. 7611 * 7612 * @param uri 7613 * The URI of the remote REST resource. 7614 * <br>Can be any of the following types: 7615 * <ul> 7616 * <li>{@link URIBuilder} 7617 * <li>{@link URI} 7618 * <li>{@link URL} 7619 * <li>{@link String} 7620 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7621 * </ul> 7622 * @return 7623 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7624 * as a parsed object. 7625 * @throws RestCallException REST call failed. 7626 */ 7627 public RestRequest patch(Object uri) throws RestCallException { 7628 return request(op(PATCH, uri, NO_BODY)); 7629 } 7630 7631 /** 7632 * Perform a <c>PATCH</c> request against the specified URI. 7633 * 7634 * @param uri 7635 * The URI of the remote REST resource. 7636 * <br>Can be any of the following types: 7637 * <ul> 7638 * <li>{@link URIBuilder} 7639 * <li>{@link URI} 7640 * <li>{@link URL} 7641 * <li>{@link String} 7642 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7643 * </ul> 7644 * @param body 7645 * The object to serialize and transmit to the URI as the body of the request. 7646 * Can be of the following types: 7647 * <ul class='spaced-list'> 7648 * <li> 7649 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 7650 * <li> 7651 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 7652 * <li> 7653 * {@link HttpResource} - Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. 7654 * <li> 7655 * {@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 7656 * <li> 7657 * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the 7658 * {@link RestClient}. 7659 * <li> 7660 * {@link PartList} - Converted to a URL-encoded FORM post. 7661 * <li> 7662 * {@link Supplier} - A supplier of anything on this list. 7663 * </ul> 7664 * @return 7665 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7666 * as a parsed object. 7667 * @throws RestCallException If any authentication errors occurred. 7668 */ 7669 public RestRequest patch(Object uri, Object body) throws RestCallException { 7670 return request(op(PATCH, uri, body)); 7671 } 7672 7673 /** 7674 * Perform a <c>PATCH</c> request against the specified URI as a plain text body bypassing the serializer. 7675 * 7676 * @param uri 7677 * The URI of the remote REST resource. 7678 * <br>Can be any of the following types: 7679 * <ul> 7680 * <li>{@link URIBuilder} 7681 * <li>{@link URI} 7682 * <li>{@link URL} 7683 * <li>{@link String} 7684 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7685 * </ul> 7686 * @param body 7687 * The object to serialize and transmit to the URI as the body of the request bypassing the serializer. 7688 * @param contentType 7689 * The content type of the request. 7690 * @return 7691 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7692 * as a parsed object. 7693 * @throws RestCallException If any authentication errors occurred. 7694 */ 7695 public RestRequest patch(Object uri, String body, ContentType contentType) throws RestCallException { 7696 return request(op(PATCH, uri, stringBody(body))).header(contentType); 7697 } 7698 7699 /** 7700 * Same as {@link #post(Object, Object)} but don't specify the input yet. 7701 * 7702 * <p> 7703 * You must call either {@link RestRequest#content(Object)} or {@link RestRequest#formData(String, Object)} to set the 7704 * contents on the result object. 7705 * 7706 * <h4 class='section'>Notes:</h4><ul> 7707 * <li class='note'>Use {@link #formPost(Object, Object)} for <c>application/x-www-form-urlencoded</c> form posts. 7708 * </ul> 7709 * 7710 * @param uri 7711 * The URI of the remote REST resource. 7712 * <br>Can be any of the following types: 7713 * <ul> 7714 * <li>{@link URIBuilder} 7715 * <li>{@link URI} 7716 * <li>{@link URL} 7717 * <li>{@link String} 7718 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7719 * </ul> 7720 * @return 7721 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7722 * as a parsed object. 7723 * @throws RestCallException REST call failed. 7724 */ 7725 public RestRequest post(Object uri) throws RestCallException { 7726 return request(op("POST", uri, NO_BODY)); 7727 } 7728 7729 /** 7730 * Perform a <c>POST</c> request against the specified URI. 7731 * 7732 * <h4 class='section'>Notes:</h4><ul> 7733 * <li class='note'>Use {@link #formPost(Object, Object)} for <c>application/x-www-form-urlencoded</c> form posts. 7734 * </ul> 7735 * 7736 * @param uri 7737 * The URI of the remote REST resource. 7738 * <br>Can be any of the following types: 7739 * <ul> 7740 * <li>{@link URIBuilder} 7741 * <li>{@link URI} 7742 * <li>{@link URL} 7743 * <li>{@link String} 7744 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7745 * </ul> 7746 * @param body 7747 * The object to serialize and transmit to the URI as the body of the request. 7748 * Can be of the following types: 7749 * <ul class='spaced-list'> 7750 * <li> 7751 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 7752 * <li> 7753 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 7754 * <li> 7755 * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the 7756 * {@link RestClient}. 7757 * <li> 7758 * {@link HttpEntity} / {@link HttpResource} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 7759 * <li> 7760 * {@link PartList} - Converted to a URL-encoded FORM post. 7761 * <li> 7762 * {@link Supplier} - A supplier of anything on this list. 7763 * </ul> 7764 * @return 7765 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7766 * as a parsed object. 7767 * @throws RestCallException If any authentication errors occurred. 7768 */ 7769 public RestRequest post(Object uri, Object body) throws RestCallException { 7770 return request(op("POST", uri, body)); 7771 } 7772 7773 /** 7774 * Perform a <c>POST</c> request against the specified URI as a plain text body bypassing the serializer. 7775 * 7776 * @param uri 7777 * The URI of the remote REST resource. 7778 * <br>Can be any of the following types: 7779 * <ul> 7780 * <li>{@link URIBuilder} 7781 * <li>{@link URI} 7782 * <li>{@link URL} 7783 * <li>{@link String} 7784 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7785 * </ul> 7786 * @param body 7787 * The object to serialize and transmit to the URI as the body of the request bypassing the serializer. 7788 * @param contentType 7789 * The content type of the request. 7790 * @return 7791 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7792 * as a parsed object. 7793 * @throws RestCallException If any authentication errors occurred. 7794 */ 7795 public RestRequest post(Object uri, String body, ContentType contentType) throws RestCallException { 7796 return request(op("POST", uri, stringBody(body))).header(contentType); 7797 } 7798 7799 /** 7800 * Same as {@link #put(Object, Object)} but don't specify the input yet. 7801 * 7802 * <p> 7803 * You must call either {@link RestRequest#content(Object)} or {@link RestRequest#formData(String, Object)} 7804 * to set the contents on the result object. 7805 * 7806 * @param uri 7807 * The URI of the remote REST resource. 7808 * <br>Can be any of the following types: 7809 * <ul> 7810 * <li>{@link URIBuilder} 7811 * <li>{@link URI} 7812 * <li>{@link URL} 7813 * <li>{@link String} 7814 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7815 * </ul> 7816 * @return 7817 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7818 * as a parsed object. 7819 * @throws RestCallException REST call failed. 7820 */ 7821 public RestRequest put(Object uri) throws RestCallException { 7822 return request(op("PUT", uri, NO_BODY)); 7823 } 7824 7825 /** 7826 * Perform a <c>PUT</c> request against the specified URI. 7827 * 7828 * @param uri 7829 * The URI of the remote REST resource. 7830 * <br>Can be any of the following types: 7831 * <ul> 7832 * <li>{@link URIBuilder} 7833 * <li>{@link URI} 7834 * <li>{@link URL} 7835 * <li>{@link String} 7836 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7837 * </ul> 7838 * @param body 7839 * The object to serialize and transmit to the URI as the body of the request. 7840 * Can be of the following types: 7841 * <ul class='spaced-list'> 7842 * <li> 7843 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 7844 * <li> 7845 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 7846 * <li> 7847 * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the 7848 * {@link RestClient}. 7849 * <li> 7850 * {@link HttpEntity} / {@link HttpResource} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 7851 * <li> 7852 * {@link PartList} - Converted to a URL-encoded FORM post. 7853 * <li> 7854 * {@link Supplier} - A supplier of anything on this list. 7855 * </ul> 7856 * @return 7857 * A {@link RestRequest} object that can be further tailored before executing the request 7858 * and getting the response as a parsed object. 7859 * @throws RestCallException If any authentication errors occurred. 7860 */ 7861 public RestRequest put(Object uri, Object body) throws RestCallException { 7862 return request(op("PUT", uri, body)); 7863 } 7864 7865 /** 7866 * Perform a <c>PUT</c> request against the specified URI using a plain text body bypassing the serializer. 7867 * 7868 * @param uri 7869 * The URI of the remote REST resource. 7870 * <br>Can be any of the following types: 7871 * <ul> 7872 * <li>{@link URIBuilder} 7873 * <li>{@link URI} 7874 * <li>{@link URL} 7875 * <li>{@link String} 7876 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7877 * </ul> 7878 * @param body 7879 * The object to serialize and transmit to the URI as the body of the request bypassing the serializer. 7880 * @param contentType The content type of the request. 7881 * @return 7882 * A {@link RestRequest} object that can be further tailored before executing the request 7883 * and getting the response as a parsed object. 7884 * @throws RestCallException If any authentication errors occurred. 7885 */ 7886 public RestRequest put(Object uri, String body, ContentType contentType) throws RestCallException { 7887 return request(op("PUT", uri, stringBody(body))).header(contentType); 7888 } 7889 7890 /** 7891 * Perform a generic REST call. 7892 * 7893 * @param method The HTTP method. 7894 * <br>Cannot be <jk>null</jk>. 7895 * @param uri 7896 * The URI of the remote REST resource. 7897 * <br>Can be any of the following types: 7898 * <ul> 7899 * <li>{@link URIBuilder} 7900 * <li>{@link URI} 7901 * <li>{@link URL} 7902 * <li>{@link String} 7903 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7904 * </ul> 7905 * <br>Can be <jk>null</jk> (will result in an invalid request). 7906 * @return 7907 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7908 * as a parsed object. 7909 * @throws RestCallException If any authentication errors occurred. 7910 */ 7911 public RestRequest request(String method, Object uri) throws RestCallException { 7912 return request(op(method, uri, NO_BODY)); 7913 } 7914 7915 /** 7916 * Perform a generic REST call. 7917 * 7918 * <p> 7919 * Typically you're going to use {@link #request(String, Object)} or {@link #request(String, Object, Object)}, 7920 * but this method is provided to allow you to perform non-standard HTTP methods (e.g. HTTP FOO). 7921 * 7922 * @param method The method name (e.g. <js>"GET"</js>, <js>"OPTIONS"</js>). 7923 * <br>Cannot be <jk>null</jk>. 7924 * @param uri 7925 * The URI of the remote REST resource. 7926 * <br>Can be any of the following types: 7927 * <ul> 7928 * <li>{@link URIBuilder} 7929 * <li>{@link URI} 7930 * <li>{@link URL} 7931 * <li>{@link String} 7932 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7933 * </ul> 7934 * <br>Can be <jk>null</jk> (will result in an invalid request). 7935 * @param hasBody Boolean flag indicating if the specified request has content associated with it. 7936 * @return 7937 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7938 * as a parsed object. 7939 * @throws RestCallException If any authentication errors occurred. 7940 */ 7941 public RestRequest request(String method, Object uri, boolean hasBody) throws RestCallException { 7942 return request(op(method, uri, NO_BODY).hasContent(hasBody)); 7943 } 7944 7945 /** 7946 * Perform a generic REST call. 7947 * 7948 * @param method The HTTP method. 7949 * <br>Cannot be <jk>null</jk>. 7950 * @param uri 7951 * The URI of the remote REST resource. 7952 * <br>Can be any of the following types: 7953 * <ul> 7954 * <li>{@link URIBuilder} 7955 * <li>{@link URI} 7956 * <li>{@link URL} 7957 * <li>{@link String} 7958 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 7959 * </ul> 7960 * <br>Can be <jk>null</jk> (will result in an invalid request). 7961 * @param body 7962 * The HTTP body content. 7963 * Can be of the following types: 7964 * <ul class='spaced-list'> 7965 * <li> 7966 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 7967 * <li> 7968 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 7969 * <li> 7970 * {@link HttpResource} - Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. 7971 * <li> 7972 * {@link HttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 7973 * <li> 7974 * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the 7975 * {@link RestClient}. 7976 * <li> 7977 * {@link PartList} - Converted to a URL-encoded FORM post. 7978 * <li> 7979 * {@link Supplier} - A supplier of anything on this list. 7980 * </ul> 7981 * This parameter is IGNORED if the method type normally does not have content. 7982 * @return 7983 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 7984 * as a parsed object. 7985 * @throws RestCallException If any authentication errors occurred. 7986 */ 7987 public RestRequest request(String method, Object uri, Object body) throws RestCallException { 7988 return request(op(method, uri, body)); 7989 } 7990 7991 private static RestOperation op(String method, Object url, Object body) { 7992 return RestOperation.of(method, url, body); 7993 } 7994 7995 private static Reader stringBody(String body) { 7996 return body == null ? null : new StringReader(s(body)); 7997 } 7998 7999 /** 8000 * Creates a {@link RestRequest} object from the specified {@link HttpRequest} object. 8001 * 8002 * <p> 8003 * Subclasses can override this method to provide their own specialized {@link RestRequest} objects. 8004 * 8005 * <h4 class='section'>Notes:</h4><ul> 8006 * <li class='warn'>The SSRF guard of {@code @Remote} calls travels on the request's {@link HttpContext}, which an 8007 * override of {@link RestRequest#run()} in the returned request's class may drop (by copying the request, or 8008 * sending it with another context), and depends on this client's connection manager, which a request bound to a different client does not use. So an SSRF-guard-active 8009 * {@code @Remote} call (one without the {@link Builder#allowPrivateUrls(boolean) allowPrivateUrls} opt-in) is 8010 * refused through such a request, whether this method or {@link #request(String, Object, boolean)} returns it. 8011 * Ordinary requests are unaffected. 8012 * </ul> 8013 * 8014 * @param uri The target. 8015 * @param method The HTTP method (uppercase). 8016 * @param hasBody Whether this method has a request entity. 8017 * @return A new {@link RestRequest} object. 8018 * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt. 8019 */ 8020 protected RestRequest createRequest(URI uri, String method, boolean hasBody) throws RestCallException { 8021 return new RestRequest(this, uri, method, hasBody); 8022 } 8023 8024 /** 8025 * Creates a {@link RestResponse} object from the specified {@link HttpResponse} object. 8026 * 8027 * <p> 8028 * Subclasses can override this method to provide their own specialized {@link RestResponse} objects. 8029 * 8030 * @param request The request creating this response. 8031 * @param httpResponse The response object to wrap. 8032 * @param parser The parser to use to parse the response. 8033 * 8034 * @return A new {@link RestResponse} object. 8035 * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt. 8036 */ 8037 protected RestResponse createResponse(RestRequest request, HttpResponse httpResponse, Parser parser) throws RestCallException { 8038 return new RestResponse(this, request, httpResponse, parser); 8039 } 8040 8041 /** 8042 * @deprecated Object.finalize() is deprecated. Use try-with-resources or explicit close() calls instead. 8043 */ 8044 @Override 8045 @Deprecated(since = "9", forRemoval = true) // Object.finalize() is deprecated 8046 @SuppressWarnings({ 8047 "java:S1113" // Kept for detectLeaks; logs warning when RestClient is GC'd without close 8048 }) 8049 protected void finalize() throws Throwable { 8050 if (detectLeaks && ! isClosed.get() && ! keepHttpClientOpen) { 8051 var sb = new StringBuilder("WARNING: RestClient garbage collected before it was finalized."); // NOT DEBUG 8052 if (nn(creationStack)) { 8053 sb.append("\nCreation Stack:"); // NOT DEBUG 8054 for (var e : creationStack) { 8055 sb.append("\n\t").append(e); // NOT DEBUG 8056 } 8057 } 8058 log(WARNING, sb.toString()); 8059 } 8060 } 8061 8062 /** 8063 * Returns the part parser associated with this client. 8064 * 8065 * @return The part parser associated with this client. 8066 */ 8067 protected HttpPartParser getPartParser() { return partParser; } 8068 8069 /** 8070 * Returns the part parser instance of the specified type. 8071 * 8072 * @param c The part parser class. 8073 * @return The part parser. 8074 */ 8075 protected HttpPartParser getPartParser(Class<? extends HttpPartParser> c) { 8076 var x = partParsers.get(c); 8077 if (x == null) { 8078 try { 8079 x = BeanInstantiator.of(c, beanStore).run(); 8080 } catch (ExecutableException e) { 8081 throw toRex(e); 8082 } 8083 partParsers.put(c, x); 8084 } 8085 return x; 8086 } 8087 8088 /** 8089 * Returns the part serializer associated with this client. 8090 * 8091 * @return The part serializer associated with this client. 8092 */ 8093 protected HttpPartSerializer getPartSerializer() { return partSerializer; } 8094 8095 /** 8096 * Returns the part serializer instance of the specified type. 8097 * 8098 * @param c The part serializer class. 8099 * @return The part serializer. 8100 */ 8101 protected HttpPartSerializer getPartSerializer(Class<? extends HttpPartSerializer> c) { 8102 var x = partSerializers.get(c); 8103 if (x == null) { 8104 try { 8105 x = BeanInstantiator.of(c, beanStore).run(); 8106 } catch (ExecutableException e) { 8107 throw toRex(e); 8108 } 8109 partSerializers.put(c, x); 8110 } 8111 return x; 8112 } 8113 8114 /** 8115 * Gets called add the end of the constructor call to perform any post-initialization. 8116 */ 8117 protected void init() { 8118 // No-op: Intentional empty implementation for optional override method 8119 } 8120 8121 /** 8122 * Returns <jk>true</jk> if empty request form-data parameter values should be ignored. 8123 * 8124 * @return <jk>true</jk> if empty request form-data parameter values should be ignored. 8125 */ 8126 protected boolean isSkipEmptyFormData() { return skipEmptyFormData; } 8127 8128 /** 8129 * Returns <jk>true</jk> if empty request header values should be ignored. 8130 * 8131 * @return <jk>true</jk> if empty request header values should be ignored. 8132 */ 8133 protected boolean isSkipEmptyHeaderData() { return skipEmptyHeaderData; } 8134 8135 /** 8136 * Returns <jk>true</jk> if empty request query parameter values should be ignored. 8137 * 8138 * @return <jk>true</jk> if empty request query parameter values should be ignored. 8139 */ 8140 protected boolean isSkipEmptyQueryData() { return skipEmptyQueryData; } 8141 8142 /** 8143 * Logs a message. 8144 * 8145 * @param level The log level. 8146 * @param msg The message with {@link String#format(String, Object...) String.format}-style (<c>%s</c>) arguments. 8147 * @param args The arguments. 8148 */ 8149 protected void log(Level level, String msg, Object...args) { 8150 if (logger.isLoggable(level)) { 8151 String formattedMsg = f(msg, args); 8152 logger.log(level, formattedMsg); 8153 if (logToConsole) 8154 console.println(formattedMsg); 8155 } else if (logToConsole) { 8156 console.println(f(msg, args)); 8157 } 8158 } 8159 8160 /** 8161 * Logs a message. 8162 * 8163 * @param level The log level. 8164 * @param t Thrown exception. 8165 * <br>Can be <jk>null</jk> (no exception stack trace will be logged). 8166 * @param msg The message. 8167 * @param args Optional message arguments. 8168 */ 8169 protected void log(Level level, Throwable t, String msg, Object...args) { 8170 if (logger.isLoggable(level)) { 8171 String formattedMsg = f(msg, args); 8172 logger.log(level, formattedMsg, t); 8173 if (logToConsole) { 8174 console.println(f(msg, args)); 8175 if (nn(t)) 8176 t.printStackTrace(console); 8177 } 8178 } else if (logToConsole) { 8179 console.println(f(msg, args)); 8180 if (nn(t)) 8181 t.printStackTrace(console); 8182 } 8183 } 8184 8185 /** 8186 * Interceptor method called immediately after the RestRequest object is created and all headers/query/form-data has been set on the request from the client. 8187 * 8188 * <p> 8189 * Subclasses can override this method to handle any cleanup operations. 8190 * 8191 * <h4 class='section'>See Also:</h4><ul> 8192 * <li class='jm'>{@link Builder#interceptors(Object...)} 8193 * </ul> 8194 * 8195 * @param req The HTTP request. 8196 * @param res The HTTP response. 8197 * @throws RestCallException If any of the interceptors threw an exception. 8198 */ 8199 protected void onCallClose(RestRequest req, RestResponse res) throws RestCallException { 8200 try { 8201 for (var rci : interceptors) 8202 rci.onClose(req, res); 8203 } catch (RuntimeException | RestCallException e) { 8204 throw e; 8205 } catch (Exception e) { 8206 throw new RestCallException(res, e, "Interceptor threw an exception on close."); 8207 } 8208 } 8209 8210 /** 8211 * Interceptor method called immediately after an HTTP response has been received. 8212 * 8213 * <p> 8214 * Subclasses can override this method to intercept the response and perform special modifications. 8215 * 8216 * <h4 class='section'>See Also:</h4><ul> 8217 * <li class='jm'>{@link Builder#interceptors(Object...)} 8218 * </ul> 8219 * 8220 * @param req The HTTP request. 8221 * @param res The HTTP response. 8222 * @throws RestCallException If any of the interceptors threw an exception. 8223 */ 8224 protected void onCallConnect(RestRequest req, RestResponse res) throws RestCallException { 8225 try { 8226 for (var rci : interceptors) 8227 rci.onConnect(req, res); 8228 } catch (RuntimeException | RestCallException e) { 8229 throw e; 8230 } catch (Exception e) { 8231 throw new RestCallException(res, e, "Interceptor threw an exception on connect."); 8232 } 8233 } 8234 8235 /** 8236 * Interceptor method called immediately after the RestRequest object is created and all headers/query/form-data has been copied from the client. 8237 * 8238 * <p> 8239 * Subclasses can override this method to intercept the request and perform special modifications. 8240 * 8241 * <h4 class='section'>See Also:</h4><ul> 8242 * <li class='jm'>{@link Builder#interceptors(Object...)} 8243 * </ul> 8244 * 8245 * @param req The HTTP request. 8246 * @throws RestCallException If any of the interceptors threw an exception. 8247 */ 8248 protected void onCallInit(RestRequest req) throws RestCallException { 8249 try { 8250 for (var rci : interceptors) 8251 rci.onInit(req); 8252 } catch (RuntimeException | RestCallException e) { 8253 throw e; 8254 } catch (Exception e) { 8255 throw new RestCallException(null, e, "Interceptor threw an exception on init."); 8256 } 8257 } 8258 8259 @Override /* Overridden from MarshallingContextable */ 8260 protected FluentMap<String,Object> properties() { 8261 return super.properties() 8262 .a("errorCodes", errorCodes) 8263 .a("executorService", executorService.get()) 8264 .a("executorServiceShutdownOnClose", executorServiceShutdownOnClose) 8265 .a("headerData", headerData) 8266 .a("interceptors", interceptors) 8267 .a("keepHttpClientOpen", keepHttpClientOpen) 8268 .a("partParser", partParser) 8269 .a("partSerializer", partSerializer) 8270 .a("queryData", queryData) 8271 .a("rootUrl", rootUrl != null ? rootUrl.get() : null); 8272 } 8273 8274 /** 8275 * Perform an arbitrary request against the specified URI. 8276 * 8277 * <p> 8278 * All requests feed through this method so it can be used to intercept request creations and make modifications 8279 * (such as add headers). 8280 * 8281 * @param op The operation that identifies the HTTP method, URL, and optional payload. 8282 * @return 8283 * A {@link RestRequest} object that can be further tailored before executing the request and getting the response 8284 * as a parsed object. 8285 * @throws RestCallException If any authentication errors occurred. 8286 */ 8287 protected RestRequest request(RestOperation op) throws RestCallException { 8288 if (isClosed.get()) { 8289 Exception e2 = null; 8290 if (nn(closedStack)) { 8291 e2 = new Exception("Creation stack:"); 8292 e2.setStackTrace(closedStack); 8293 throw new RestCallException(null, e2, "RestClient.close() has already been called. This client cannot be reused."); 8294 } 8295 throw new RestCallException(null, null, 8296 "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.client2.RestClient.trackCreation' to true."); 8297 } 8298 8299 var req = createRequest(toUri(op.getUri(), rootUrl != null ? rootUrl.get() : null), op.getMethod(), op.hasContent()); 8300 8301 onCallInit(req); 8302 8303 req.content(op.getContent()); 8304 8305 return req; 8306 } 8307 8308 /** 8309 * Entrypoint for executing all requests and returning a response. 8310 * 8311 * <p> 8312 * Subclasses can override this method to provide specialized handling. 8313 * 8314 * <p> 8315 * The behavior of this method can also be modified by specifying a different {@link RestCallHandler}. 8316 * 8317 * <h4 class='section'>Notes:</h4><ul> 8318 * <li class='warn'>The SSRF guard of {@code @Remote} calls travels on the request's {@code HttpContext}, which this 8319 * client cannot guarantee an override passes on unchanged. So a client whose class overrides this method, 8320 * {@link #execute(HttpHost, HttpRequest, HttpContext)} or {@link #execute(HttpUriRequest, HttpContext)} refuses every 8321 * SSRF-guard-active {@code @Remote} call (one without the {@link Builder#allowPrivateUrls(boolean) allowPrivateUrls} 8322 * opt-in). Ordinary requests are unaffected. 8323 * </ul> 8324 * 8325 * <h4 class='section'>See Also:</h4><ul> 8326 * <li class='jm'>{@link Builder#callHandler()} 8327 * </ul> 8328 * 8329 * @param target The target host for the request. 8330 * <br>Implementations may accept <jk>null</jk> if they can still determine a route, for example to a default 8331 * target or by inspecting the request. 8332 * @param request The request to execute. 8333 * @param context The context to use for the execution, or <jk>null</jk> to use the default context. 8334 * @return 8335 * The response to the request. 8336 * <br>This is always a final response, never an intermediate response with an 1xx status code. 8337 * <br>Whether redirects or authentication challenges will be returned or handled automatically depends on the 8338 * implementation and configuration of this client. 8339 * @throws IOException In case of a problem or the connection was aborted. 8340 * @throws ClientProtocolException In case of an http protocol error. 8341 */ 8342 protected HttpResponse run(HttpHost target, HttpRequest request, HttpContext context) throws IOException { 8343 return callHandler.run(target, request, context); 8344 } 8345 8346 // The methods a request is dispatched through on its way from RestRequest to the HttpClient (run(...), then the two 8347 // execute(...) overloads BasicRestCallHandler calls). 8348 private static final List<Method> DISPATCH_METHODS = dispatchMethods(); 8349 8350 private static List<Method> dispatchMethods() { 8351 try { 8352 return List.of( 8353 RestClient.class.getDeclaredMethod("run", HttpHost.class, HttpRequest.class, HttpContext.class), 8354 RestClient.class.getDeclaredMethod("execute", HttpHost.class, HttpRequest.class, HttpContext.class), 8355 RestClient.class.getDeclaredMethod("execute", HttpUriRequest.class, HttpContext.class)); 8356 } catch (NoSuchMethodException e) { 8357 throw new ExceptionInInitializerError(e); 8358 } 8359 } 8360 8361 // Why this client cannot guarantee the SSRF guard of @Remote calls, or null if it can. A connection manager this 8362 // client did not build has no pinned pool, an HttpClient other than the one the default createHttpClient() wired to 8363 // it (builtGuard) does not use it, and builderRefusal says why the HttpClientBuilder may have built the client around 8364 // something else. The guard travels on each request's context, so it holds on another thread as long as the request 8365 // that carries it is the one sent; but anything that may send a different request (a custom call handler, a handler 8366 // bound to another client, a subclass that overrides the request dispatch: each may copy the request, or send it with 8367 // another context) is refused, and these refusals are what keep such paths from going out unpinned. 8368 private String ssrfRefusal(SsrfGuardConnectionManager builtGuard, String builderRefusal) { 8369 var tail = "the SSRF guardrail's connect-time contract (pin-on-connect + redirect revalidation) is not in force. "; 8370 var optOut = "or set allowPrivateUrls(true) if this is an intentional local-dev/intranet target."; 8371 if (ssrfGuard == null && nn(builtGuard) && ! SsrfGuardConnectionManager.canCheckWiring()) 8372 // HTT: only an HttpClient release whose InternalHttpClient has no connManager field, or a JVM that denies 8373 // reflective access to it, gets here. 8374 return "Refusing to send a policy-covered @Remote request: this RestClient cannot read the connection manager of " 8375 + "the HttpClient it built (org.apache.http.impl.client.InternalHttpClient.connManager), so it cannot confirm " 8376 + "that the client uses its SSRF-guard connection manager, and " + tail + "Use an HttpClient 4.5.x release, " 8377 + optOut; 8378 if (ssrfGuard == null && nn(builtGuard)) 8379 return "Refusing to send a policy-covered @Remote request through an HttpClient that is not the one this RestClient " 8380 + "wired to its SSRF-guard connection manager: an overridden createHttpClient() or HttpClientBuilder.build() " 8381 + "returned another client, or a wrapper around one, which may send the request without the pinned pool, so " 8382 + tail + "Return the client super.createHttpClient() or HttpClientBuilder.build() built, unwrapped (customize it " 8383 + "through httpClientBuilder(...) instead), " + optOut; 8384 if (nn(builderRefusal)) 8385 return builderRefusal; 8386 if (ssrfGuard == null) 8387 return "Refusing to send a policy-covered @Remote request through a caller-supplied HttpClient or connection " 8388 + "manager that cannot be guaranteed to honor the SSRF guardrail's connect-time contract (pin-on-connect + " 8389 + "redirect revalidation): the client was supplied via httpClient(...) or an overridden createHttpClient(), " 8390 + "or the connection manager via connectionManager(...) or an overridden createConnectionManager(), instead " 8391 + "of being built by this RestClient. Let this RestClient build its own HttpClient and connection manager, " 8392 + optOut; 8393 if (callHandler.getClass() != BasicRestCallHandler.class) 8394 return "Refusing to send a policy-covered @Remote request through a custom RestCallHandler (" + cn(callHandler) 8395 + "): it may copy the request, or send it with another context, without the SSRF guard the request carries, so " 8396 + tail + "Remove the callHandler(...) setting, " + optOut; 8397 if (((BasicRestCallHandler)callHandler).client() != this) 8398 return "Refusing to send a policy-covered @Remote request through a BasicRestCallHandler bound to a different " 8399 + "RestClient: it sends the request through that client's connection manager, where " + tail 8400 + "Remove the callHandler(...) setting, " + optOut; 8401 var dispatch = overriddenDispatch(getClass()); 8402 if (nn(dispatch)) 8403 return "Refusing to send a policy-covered @Remote request through a RestClient subclass (" + dispatch 8404 + "): the override may copy the request, or send it with another context, without the SSRF guard the request " 8405 + "carries, so " + tail + "Remove the override, " + optOut; 8406 return null; 8407 } 8408 8409 // Why a guarded call cannot be sent through rc (the request createRequest(...) returned), or null if it can: a request 8410 // bound to another client goes out through that client's HttpClient, and an override of RestRequest.run() may copy 8411 // the request, or send it with another context, without the guard it carries. 8412 private String requestRefusal(RestRequest rc) { 8413 if (rc.client != this) 8414 return "Refusing to send a policy-covered @Remote request through a RestRequest bound to a different " 8415 + "RestClient: it sends the request through that client's HttpClient, where the SSRF guardrail's " 8416 + "connect-time contract (pin-on-connect + redirect revalidation) is not in force. Remove the " 8417 + "createRequest(...) or request(...) override that returns it, or set allowPrivateUrls(true) if this is " 8418 + "an intentional local-dev/intranet target."; 8419 for (Class<?> x = rc.getClass(); x != RestRequest.class; x = x.getSuperclass()) { 8420 try { 8421 x.getDeclaredMethod("run"); 8422 return "Refusing to send a policy-covered @Remote request through a RestRequest subclass (" + cn(x) 8423 + " overrides run()): the override may copy the request, or send it with another context, without the " 8424 + "SSRF guard the request carries, so the SSRF guardrail's connect-time contract (pin-on-connect + redirect revalidation) is not in force. Remove the override " 8425 + "(or the createRequest(...) override that returns it), or set allowPrivateUrls(true) if this is an " 8426 + "intentional local-dev/intranet target."; 8427 } catch (@SuppressWarnings("unused") NoSuchMethodException e) { /* Not declared here. */ } 8428 } 8429 return null; 8430 } 8431 8432 // Returns "<class>.<method>(<params>)" for the first dispatch method a subclass between c and RestClient declares, 8433 // or null if there is none. 8434 private static String overriddenDispatch(Class<?> c) { 8435 for (var x = c; x != RestClient.class; x = x.getSuperclass()) { 8436 for (var m : DISPATCH_METHODS) { 8437 try { 8438 x.getDeclaredMethod(m.getName(), m.getParameterTypes()); 8439 return cn(x) + " overrides " + m.getName() + "(" + String.join(",", Arrays.stream(m.getParameterTypes()).map(Class::getSimpleName).toList()) + ")"; 8440 } catch (@SuppressWarnings("unused") NoSuchMethodException e) { /* Not declared here. */ } 8441 } 8442 } 8443 return null; 8444 } 8445 8446 /** 8447 * Resolves the effective request URL for a remote-proxy call, applying the dynamic-URL overrides 8448 * ({@code @Url} parameter, then method-level {@code baseUrl}, then interface-level {@code baseUrl}) over the 8449 * statically-computed interface-base + method path, with the http/https SSRF guardrail. 8450 * 8451 * <p> 8452 * Ported from the next-generation engine's {@code RemoteInvocationHandler.resolveEffectiveUrl(...)}. 8453 */ 8454 String resolveRemoteUri(Class<?> interfaceClass, String restUrl2, Method method, RemoteOperationMeta rom, RemoteMeta rm, Object[] args) { 8455 var fullPath = rom.getFullPath(); 8456 var allowPrivate = isAllowPrivateUrls() || rm.isAllowPrivateUrls(); 8457 String uri; 8458 8459 // Option A: a call-time @Url parameter wins over everything (endpoint replacement). 8460 var urlIdx = rom.getUrlParamIndex(); 8461 if (urlIdx >= 0) { 8462 var arg = (args == null || urlIdx >= args.length) ? null : args[urlIdx]; 8463 var v = arg == null ? null : arg.toString(); 8464 if (ib(v)) 8465 throw new RemoteMetadataException(interfaceClass, "@Url parameter on " + method.getDeclaringClass().getName() + "." + method.getName() + " must not be null or blank."); 8466 uri = RemoteProxyUtils.requireHttpScheme(v.trim(), allowPrivate, allowedAddressRanges); 8467 // A scheme-less @Url value is relative and resolved against the client root URL only. 8468 if (uri.indexOf("://") == -1) 8469 uri = restUrl2 + '/' + trimSlashes(uri); 8470 } else { 8471 // Option B: a declarative base/host override (method-level wins over interface-level). 8472 var baseUrl = firstNonEmpty(rom.getBaseUrl(), rm.getBaseUrl()); 8473 if (ine(baseUrl)) { 8474 uri = RemoteProxyUtils.requireHttpScheme(RemoteProxyUtils.combinePaths(baseUrl, fullPath), allowPrivate, allowedAddressRanges); 8475 } else { 8476 uri = fullPath; 8477 if (uri.indexOf("://") == -1) 8478 uri = restUrl2 + '/' + uri; 8479 } 8480 } 8481 8482 if (uri.indexOf("://") == -1) 8483 throw new RemoteMetadataException(interfaceClass, "Root URI has not been specified. Cannot construct absolute path to remote resource."); 8484 8485 // SSRF guardrail (parity with juneau-rest-client RemoteClient.resolveEffectiveUrl): the fully-resolved 8486 // absolute URI -- including a scheme-less @Url/default-path combined with the client root above -- must pass 8487 // the full deny-private policy, not just the http/https scheme check (Review R4: the default (no-override) 8488 // path is policy-covered too once it is absolute). 8489 try { 8490 RemoteUrlPolicy.requireAllowedUrl(uri, allowPrivate, allowedAddressRanges); 8491 } catch (IllegalArgumentException e) { 8492 throw new RemoteMetadataException(interfaceClass, e.getMessage()); 8493 } 8494 8495 return uri; 8496 } 8497 8498 /** 8499 * Builds a fresh {@link RestRequest} for a remote-proxy call, binding constant parts (interface + method level), 8500 * content-negotiation overrides ({@code accept}/{@code contentType}), the method-argument parts, and the per-call 8501 * timeout. Re-invoked per retry attempt so a (gated) retry resends a freshly-bound request. 8502 * 8503 * <p> 8504 * Ported from the next-generation engine's {@code RemoteInvocationHandler.buildRequest(...)}. Unlike the NG 8505 * version, argument binding here is driven entirely by the pre-resolved {@link RemoteOperationMeta} (<c>rom</c>) 8506 * rather than live reflection over the interface {@link Method}, and any misconfiguration that needs to identify 8507 * the offending interface/method is already reported earlier by {@link #resolveRemoteUri}; neither the interface 8508 * class nor the {@link Method} is needed here. 8509 */ 8510 RestRequest buildRemoteRequest(String uri, Serializer serializer, Parser parser, RemoteOperationMeta rom, RemoteMeta rm, Object[] args) throws RestCallException { 8511 var httpMethod = rom.getHttpMethod(); 8512 var rc = request(httpMethod, uri, hasContent(httpMethod)); 8513 8514 if (serializer != null) rc.serializer(serializer); 8515 if (parser != null) rc.parser(parser); 8516 8517 // contentType override: select the matching registered serializer (else the client default) and send the 8518 // overridden media type as the Content-Type label (mirrors NG resolveBodyFormat()). 8519 var effContentType = firstNonEmpty(rom.getContentType(), rm.getContentType()); 8520 if (ine(effContentType)) { 8521 var s = getMatchingSerializer(effContentType); 8522 if (s == null) { 8523 var all = serializers.getSerializers(); 8524 if (! all.isEmpty()) 8525 s = all.get(0); 8526 } 8527 if (nn(s)) 8528 rc.serializer(s); 8529 rc.contentType(effContentType); 8530 } 8531 8532 var effAccept = firstNonEmpty(rom.getAccept(), rm.getAccept()); 8533 8534 // Constant headers (interface-level then method-level, method-level wins on name collisions). A constant 8535 // Content-Type/Accept is dropped when the dedicated contentType/accept attribute is in effect. 8536 var methodHeaderNames = new HashSet<String>(); 8537 rom.getConstantHeaders().forEach(e -> methodHeaderNames.add(e.getKey())); 8538 var skipContentType = ine(effContentType); 8539 var skipAccept = ine(effAccept); 8540 rm.getHeaders().forEach(h -> { 8541 var n = h.getName(); 8542 if (methodHeaderNames.contains(n)) 8543 return; 8544 if (skipContentType && eqic(HEADER_CONTENT_TYPE, n)) 8545 return; 8546 if (skipAccept && eqic(HEADER_ACCEPT, n)) 8547 return; 8548 rc.header(h); 8549 }); 8550 rom.getConstantHeaders().forEach(e -> { 8551 if (skipContentType && eqic(HEADER_CONTENT_TYPE, e.getKey())) 8552 return; 8553 if (skipAccept && eqic(HEADER_ACCEPT, e.getKey())) 8554 return; 8555 rc.header(e.getKey(), e.getValue()); 8556 }); 8557 8558 // Constant query/form-data (interface-level then method-level, method-level wins on name collisions). 8559 RemoteProxyUtils.mergeConstants(rm.getQueryData(), rom.getConstantQueryData()).forEach(rc::queryData); 8560 RemoteProxyUtils.mergeConstants(rm.getFormData(), rom.getConstantFormData()).forEach(rc::formData); 8561 8562 // Apply method-level defaults if parameter values are not provided (9.2.0) 8563 rom.forEachPathArg(a -> { 8564 var val = args[a.getIndex()]; 8565 if (val == null) { 8566 var def = a.getSchema().getDefault(); 8567 if (def == null) 8568 def = rom.getPathDefault(a.getName()); 8569 if (nn(def)) 8570 val = def; 8571 } 8572 rc.pathArg(a.getName(), val, a.getSchema(), a.getSerializer().orElse(partSerializer)); 8573 }); 8574 rom.forEachQueryArg(a -> { 8575 var val = args[a.getIndex()]; 8576 if (val == null) { 8577 var def = a.getSchema().getDefault(); 8578 if (def == null) 8579 def = rom.getQueryDefault(a.getName()); 8580 if (nn(def)) 8581 val = def; 8582 } 8583 rc.queryArg(a.getName(), val, a.getSchema(), a.getSerializer().orElse(partSerializer), a.isSkipIfEmpty()); 8584 }); 8585 rom.forEachFormDataArg(a -> { 8586 var val = args[a.getIndex()]; 8587 if (val == null) { 8588 var def = a.getSchema().getDefault(); 8589 if (def == null) 8590 def = rom.getFormDataDefault(a.getName()); 8591 if (nn(def)) 8592 val = def; 8593 } 8594 rc.formDataArg(a.getName(), val, a.getSchema(), a.getSerializer().orElse(partSerializer), a.isSkipIfEmpty()); 8595 }); 8596 rom.forEachHeaderArg(a -> { 8597 var val = args[a.getIndex()]; 8598 if (val == null) { 8599 var def = a.getSchema().getDefault(); 8600 if (def == null) 8601 def = rom.getHeaderDefault(a.getName()); 8602 if (nn(def)) 8603 val = def; 8604 } 8605 rc.headerArg(a.getName(), val, a.getSchema(), a.getSerializer().orElse(partSerializer), a.isSkipIfEmpty()); 8606 }); 8607 8608 var ba = rom.getContentArg(); 8609 if (nn(ba)) { 8610 var val = args[ba.getIndex()]; 8611 if (val == null) { 8612 var def = ba.getSchema().getDefault(); 8613 if (def == null) 8614 def = rom.getContentDefault(); 8615 if (nn(def)) 8616 val = def; 8617 } 8618 rc.content(val, ba.getSchema()); 8619 } else { 8620 var contentDef = rom.getContentDefault(); 8621 if (nn(contentDef)) 8622 rc.content(contentDef); 8623 } 8624 8625 rom.forEachRequestArg(rmba -> { 8626 var rbm = rmba.getMeta(); 8627 var bean = args[rmba.getIndex()]; 8628 if (nn(bean)) { 8629 for (var p : rbm.getProperties()) { 8630 var val = safeSupplier(() -> p.getGetter().invoke(bean)); 8631 if (val instanceof Optional<?> val2) 8632 val = val2.orElse(null); 8633 var pt = p.getPartType(); 8634 var pn = p.getPartName(); 8635 var schema = p.getSchema(); 8636 if (pt == PATH) 8637 rc.pathArg(pn, val, schema, p.getSerializer().orElse(partSerializer)); 8638 else if (nn(val)) { 8639 if (pt == QUERY) 8640 rc.queryArg(pn, val, schema, p.getSerializer().orElse(partSerializer), schema.isSkipIfEmpty()); 8641 else if (pt == FORMDATA) 8642 rc.formDataArg(pn, val, schema, p.getSerializer().orElse(partSerializer), schema.isSkipIfEmpty()); 8643 else if (pt == HEADER) 8644 rc.headerArg(pn, val, schema, p.getSerializer().orElse(partSerializer), schema.isSkipIfEmpty()); 8645 else /* (pt == HttpPartType.BODY) */ 8646 rc.content(val, schema); 8647 } 8648 } 8649 } 8650 }); 8651 8652 // Set the Accept header from the dedicated attribute unless a caller-supplied @Header param already provided one. 8653 if (ine(effAccept) && ! rc.containsHeader(HEADER_ACCEPT)) 8654 rc.accept(effAccept); 8655 8656 // Per-call response/read timeout (method-level overrides interface-level) via a per-call RequestConfig. 8657 var effTimeout = firstNonEmpty(rom.getTimeout(), rm.getTimeout()); 8658 if (ine(effTimeout)) { 8659 var ms = getDuration(effTimeout); 8660 if (ms > 0) { 8661 var base = rc.getConfig(); 8662 var cb = base != null ? RequestConfig.copy(base) : RequestConfig.custom(); 8663 rc.config(cb.setSocketTimeout((int)ms).build()); 8664 } 8665 } 8666 8667 return rc; 8668 } 8669 8670 /** 8671 * Executes a remote-proxy call and processes the return value, applying safe automatic retries when the method 8672 * opts in and all safety gates pass (idempotent verb or {@code retryNonIdempotent}, buffered return mode, and a 8673 * repeatable body). Mirrors the next-generation engine's {@code RemoteInvocationHandler.processReturn(...)}. 8674 */ 8675 @SuppressWarnings({ 8676 "java:S135" // Two continue statements are the two retry triggers (transport failure, retryable status); merging them would obscure the loop 8677 }) 8678 Object executeRemoteWithRetry(String uri, Serializer serializer, Parser parser, Method method, RemoteOperationMeta rom, RemoteMeta rm, Object[] args) throws Exception { 8679 var throwOnError = rm.isThrowOnError() || rom.isThrowOnError(); 8680 var ror = rom.getReturns(); 8681 var maxRetries = (isRetryableMode(ror, method.getReturnType()) && isRetryableVerb(rom, rm)) ? effectiveRetries(rom, rm) : 0; 8682 8683 // Every getRemote() call is policy-covered; the SSRF guard is active unless allowPrivateUrls opts out. 8684 var allowPrivate = isAllowPrivateUrls() || rm.isAllowPrivateUrls(); 8685 var guardActive = ! allowPrivate; 8686 if (guardActive && ! ssrfPolicySupported) 8687 throw new RestCallException(null, null, "%s", ssrfRefusal); 8688 8689 var attempt = 0; 8690 while (true) { 8691 var rc = buildRemoteRequest(uri, serializer, parser, rom, rm, args); 8692 rc.rethrow(RuntimeException.class); 8693 rom.forEachException(rc::rethrow); 8694 // The classic run() throws by default on >=400; the proxy replicates NG's throwIfError() instead, so it 8695 // always suppresses that generic throw and applies the typed/conditional mapping itself. 8696 rc.ignoreErrors(); 8697 if (guardActive) { 8698 var refusal = requestRefusal(rc); 8699 if (nn(refusal)) 8700 throw new RestCallException(null, null, "%s", refusal); 8701 // Carried on the request's context, so the guard holds on whichever thread the request is sent. 8702 rc.ssrfGuard(); 8703 } 8704 8705 // Non-repeatable body: never retry (resending a consumed stream would corrupt the call). 8706 var canRetry = maxRetries > 0 && (attempt > 0 || rc.isBodyRepeatable()); 8707 8708 RestResponse res; 8709 if (guardActive) 8710 RemoteUrlPolicyState.activate(); 8711 try { 8712 res = rc.run(); 8713 } catch (SsrfGuardConnectionManager.GuardRefusedException e) { 8714 // Reported like the other guard refusals (and other transport failures), not as a raw runtime exception. 8715 throw new RestCallException(null, e, "%s", e.getMessage()); 8716 } catch (RestCallException e) { 8717 // A transport failure (IOException cause) is retryable; a reconstructed server exception is not 8718 // caught here (it is not a RestCallException). 8719 if (canRetry && attempt < maxRetries && e.getCause() instanceof IOException) { 8720 attempt++; 8721 backoff(attempt); 8722 continue; 8723 } 8724 Throwable t = e.getCause(); 8725 if (t instanceof RuntimeException t2) 8726 throw t2; 8727 if (t instanceof Exception t2) { 8728 for (var t3 : method.getExceptionTypes()) 8729 if (t3.isInstance(t2)) 8730 throw t2; 8731 } 8732 throw toRex(e); 8733 } finally { 8734 if (guardActive) 8735 RemoteUrlPolicyState.deactivate(); 8736 } 8737 8738 if (canRetry && attempt < maxRetries && isRetryableStatus(res.getStatusCode())) { 8739 res.close(); 8740 attempt++; 8741 backoff(attempt); 8742 continue; 8743 } 8744 8745 return materializeRemote(res, method, rom, throwOnError); 8746 } 8747 } 8748 8749 /** 8750 * Materializes the terminal return value from an already-run response, applying the typed-exception / 8751 * conditional-throw error mapping (mirrors the next-generation engine's {@code throwIfError} + 8752 * {@code materializeResponse}). 8753 */ 8754 Object materializeRemote(RestResponse res, Method method, RemoteOperationMeta rom, boolean throwOnError) throws Exception { 8755 var ror = rom.getReturns(); 8756 var rv = ror.getReturnValue(); 8757 8758 if (rv == RemoteReturn.NONE) { 8759 res.close(); 8760 return null; 8761 } 8762 if (rv == RemoteReturn.STATUS) { 8763 var sc = res.getStatusCode(); 8764 var rt = method.getReturnType(); 8765 res.close(); 8766 if (rt == Integer.class || rt == int.class) 8767 return sc; 8768 if (rt == Boolean.class || rt == boolean.class) 8769 return sc < 400; 8770 throw new RestCallException(res, null, "Invalid return type on method annotated with @RemoteOp(returns=RemoteReturn.STATUS). Only integer and booleans types are valid."); 8771 } 8772 if (rv == RemoteReturn.RESPONSE) 8773 return res; 8774 if (rv == RemoteReturn.BEAN) { 8775 throwRemoteError(res, method, throwOnError); 8776 return res.as(ror.getResponseBeanMeta()); 8777 } 8778 // BODY (default) 8779 throwRemoteError(res, method, throwOnError); 8780 var rt = method.getReturnType(); 8781 Object v = res.getContent().as(ror.getReturnType()); 8782 if (v == null && rt.isPrimitive()) 8783 v = ClassInfo.of(rt).getPrimitiveDefault(); 8784 return v; 8785 } 8786 8787 /** 8788 * Maps an error HTTP status (≥400) to a typed exception declared in the method's {@code throws} clause (a 8789 * {@link org.apache.juneau.http.response.BasicHttpException} subtype whose {@code STATUS_CODE} matches), else 8790 * conditionally throws a generic exception when {@code throwOnError} is set, else lets the error body flow through 8791 * as the return value. Mirrors the next-generation engine's {@code throwIfError(...)}. 8792 */ 8793 void throwRemoteError(RestResponse res, Method method, boolean throwOnError) throws Exception { 8794 var sc = res.getStatusCode(); 8795 if (sc < 400) 8796 return; 8797 for (var et : method.getExceptionTypes()) { 8798 if (org.apache.juneau.http.response.BasicHttpException.class.isAssignableFrom(et) && httpStatusCode(et) == sc) { 8799 var body = res.getContent().asString(); 8800 res.close(); 8801 throw (org.apache.juneau.http.response.BasicHttpException) instantiateHttpType(et, body); 8802 } 8803 } 8804 if (throwOnError) { 8805 var body = res.getContent().asString(); 8806 res.close(); 8807 throw new org.apache.juneau.http.response.BasicHttpException(sc, body); 8808 } 8809 // else: let the error body flow through as the return value (parity with NG throwOnError=false). 8810 } 8811 8812 /** Returns the static {@code STATUS_CODE} field of an HTTP response/exception type, or {@code -1} if absent. */ 8813 private static int httpStatusCode(Class<?> c) { 8814 try { 8815 return c.getField("STATUS_CODE").getInt(null); 8816 } catch (ReflectiveOperationException e) { 8817 return -1; 8818 } 8819 } 8820 8821 /** Instantiates an HTTP response/exception bean, preferring a {@code (String body)} constructor. */ 8822 private static Object instantiateHttpType(Class<?> c, String body) { 8823 try { 8824 return newHttpTypeInstance(c, body); 8825 } catch (ReflectiveOperationException e) { 8826 throw rex(e, "Could not instantiate HTTP response/exception type %s", c.getName()); 8827 } 8828 } 8829 8830 private static Object newHttpTypeInstance(Class<?> c, String body) throws ReflectiveOperationException { 8831 try { 8832 return c.getConstructor(String.class).newInstance(body); 8833 } catch (NoSuchMethodException e) { 8834 return c.getConstructor().newInstance(); 8835 } 8836 } 8837 8838 /** Returns <jk>true</jk> if the return mode/type is a buffered (retryable) shape, not a streaming/wrapper one. */ 8839 private static boolean isRetryableMode(RemoteOperationReturn ror, Class<?> returnType) { 8840 if (ror.getReturnValue() == RemoteReturn.RESPONSE) 8841 return false; 8842 if (ror.isFuture() || ror.isCompletableFuture()) 8843 return false; 8844 return ! (returnType == InputStream.class || returnType == Reader.class || returnType == Optional.class); 8845 } 8846 8847 /** Returns <jk>true</jk> if the verb may auto-retry: idempotent verbs always, POST/PATCH only when opted in. */ 8848 private static boolean isRetryableVerb(RemoteOperationMeta rom, RemoteMeta rm) { 8849 if (isOneOf(rom.getHttpMethod(), "GET", "PUT", "DELETE", "HEAD")) 8850 return true; 8851 return rom.isRetryNonIdempotent() || rm.isRetryNonIdempotent(); 8852 } 8853 8854 /** Returns the effective retry count: a positive method-level value overrides the interface-level default. */ 8855 private static int effectiveRetries(RemoteOperationMeta rom, RemoteMeta rm) { 8856 return rom.getRetries() > 0 ? rom.getRetries() : rm.getRetries(); 8857 } 8858 8859 /** Retryable HTTP statuses: {@code 429} (Too Many Requests) and all {@code 5xx} server errors. */ 8860 private static boolean isRetryableStatus(int statusCode) { 8861 return statusCode == 429 || statusCode >= 500; 8862 } 8863 8864 /** Sleeps a short exponential backoff ({@code 50ms * 2^(attempt-1)}, capped at {@code 1s}) before a retry. */ 8865 private static void backoff(int attempt) { 8866 try { 8867 Thread.sleep(Math.min(50L << (attempt - 1), 1000L)); 8868 } catch (InterruptedException e) { 8869 Thread.currentThread().interrupt(); 8870 } 8871 } 8872 8873 ExecutorService getExecutorService() { 8874 ExecutorService result = executorService.get(); 8875 if (nn(result)) 8876 return result; 8877 synchronized (this) { 8878 result = executorService.get(); 8879 if (nn(result)) 8880 return result; 8881 result = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10)); 8882 executorService.set(result); 8883 return result; 8884 } 8885 } 8886 8887 <T extends Context> T getInstance(Class<T> c) { 8888 var o = requestContexts.computeIfAbsent(c, k -> { 8889 if (Serializer.class.isAssignableFrom(k)) { 8890 return Serializer.createSerializerBuilder((Class<? extends Serializer>)k).marshallingContext(getMarshallingContext()).build(); 8891 } else if (Parser.class.isAssignableFrom(k)) { 8892 return Parser.createParserBuilder((Class<? extends Parser>)k).marshallingContext(getMarshallingContext()).build(); 8893 } 8894 return null; 8895 }); 8896 return (T)o; 8897 } 8898 8899 /* 8900 * Returns the parser that best matches the specified content type. 8901 * If no match found or the content type is <jk>null</jk>, returns the parser in the list if it's a list of one. 8902 * Returns <jk>null</jk> if no parsers are defined. 8903 */ 8904 Parser getMatchingParser(String mediaType) { 8905 if (parsers.isEmpty()) 8906 return null; 8907 if (nn(mediaType)) { 8908 var p = parsers.getParser(mediaType).orElse(null); 8909 if (nn(p)) 8910 return p; 8911 } 8912 var l = parsers.getParsers(); 8913 return (l.size() == 1 ? l.get(0) : null); 8914 } 8915 8916 /* 8917 * Returns the serializer that best matches the specified content type. 8918 * If no match found or the content type is <jk>null</jk>, returns the serializer in the list if it's a list of one. 8919 * Returns <jk>null</jk> if no serializers are defined. 8920 */ 8921 Serializer getMatchingSerializer(String mediaType) { 8922 if (serializers.isEmpty()) 8923 return null; 8924 if (nn(mediaType)) { 8925 var s = serializers.getSerializer(mediaType).orElse(null); 8926 if (nn(s)) 8927 return s; 8928 } 8929 var l = serializers.getSerializers(); 8930 return (l.size() == 1 ? l.get(0) : null); 8931 } 8932 8933 boolean hasParsers() { 8934 return ! parsers.getParsers().isEmpty(); 8935 } 8936 8937 boolean hasSerializers() { 8938 return ! serializers.getSerializers().isEmpty(); 8939 } 8940 8941 URI toUri(Object x, String rootUrl) throws RestCallException { 8942 try { 8943 if (x instanceof URI x2) 8944 return x2; 8945 if (x instanceof URL x2) 8946 return x2.toURI(); 8947 if (x instanceof URIBuilder x2) 8948 return x2.build(); 8949 var s = x == null ? "" : x.toString(); 8950 if (nn(rootUrl) && ! absUrlPattern.matcher(s).matches()) { 8951 if (s.isEmpty()) 8952 s = rootUrl; 8953 else { 8954 var sb = new StringBuilder(rootUrl); 8955 if (! s.startsWith("/")) 8956 sb.append('/'); 8957 sb.append(s); 8958 s = sb.toString(); 8959 } 8960 } 8961 s = fixUrl(s); 8962 return new URI(s); 8963 } catch (URISyntaxException e) { 8964 throw new RestCallException(null, e, "Invalid URI encountered: %s", x); // Shouldn't happen. 8965 } 8966 } 8967}