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 org.apache.juneau.commons.httppart.HttpPartType.*; 020import static org.apache.juneau.commons.utils.ClassUtils.*; 021import static org.apache.juneau.commons.utils.CollectionUtils.*; 022import static org.apache.juneau.commons.utils.IoUtils.*; 023import static org.apache.juneau.commons.utils.Shorts.*; 024import static org.apache.juneau.http.classic.HttpEntities.*; 025import static org.apache.juneau.http.classic.HttpHeaders.*; 026import static org.apache.juneau.rest.RestSharedConstants.*; 027import static org.apache.juneau.rest.client.classic.RestOperation.*; 028 029import java.io.*; 030import java.lang.reflect.*; 031import java.net.*; 032import java.util.*; 033import java.util.concurrent.*; 034import java.util.function.*; 035import java.util.logging.*; 036import java.util.regex.*; 037 038import org.apache.http.*; 039import org.apache.http.ParseException; 040import org.apache.http.client.*; 041import org.apache.http.client.config.*; 042import org.apache.http.client.entity.*; 043import org.apache.http.client.methods.*; 044import org.apache.http.client.protocol.HttpClientContext; 045import org.apache.http.client.utils.*; 046import org.apache.http.concurrent.*; 047import org.apache.http.entity.BasicHttpEntity; 048import org.apache.http.params.*; 049import org.apache.http.protocol.*; 050import org.apache.http.util.*; 051import org.apache.juneau.commons.bean.*; 052import org.apache.juneau.commons.collections.*; 053import org.apache.juneau.commons.httppart.*; 054import org.apache.juneau.commons.reflect.*; 055import org.apache.juneau.http.classic.*; 056import org.apache.juneau.http.classic.HttpHeaders; 057import org.apache.juneau.http.classic.entity.*; 058import org.apache.juneau.http.classic.header.*; 059import org.apache.juneau.http.classic.header.ContentType; 060import org.apache.juneau.http.classic.part.*; 061import org.apache.juneau.http.classic.resource.*; 062import org.apache.juneau.http.remote.*; 063import org.apache.juneau.rest.client.RedirectSecurity; 064import org.apache.juneau.rest.client.classic.remote.*; 065import org.apache.juneau.marshall.*; 066import org.apache.juneau.marshall.bson.*; 067import org.apache.juneau.marshall.html.*; 068import org.apache.juneau.marshall.httppart.*; 069import org.apache.juneau.marshall.jcs.*; 070import org.apache.juneau.marshall.json.*; 071import org.apache.juneau.marshall.json5.*; 072import org.apache.juneau.marshall.marshaller.*; 073import org.apache.juneau.marshall.marshaller.Uon; 074import org.apache.juneau.marshall.msgpack.*; 075import org.apache.juneau.marshall.oapi.*; 076import org.apache.juneau.marshall.parser.*; 077import org.apache.juneau.marshall.plaintext.*; 078import org.apache.juneau.marshall.serializer.*; 079import org.apache.juneau.marshall.stream.*; 080import org.apache.juneau.marshall.uon.*; 081import org.apache.juneau.marshall.urlencoding.*; 082import org.apache.juneau.marshall.xml.*; 083 084/** 085 * Represents a request to a remote REST resource. 086 * 087 * <p> 088 * Instances of this class are created by the various creator methods on the {@link RestClient} class. 089 * 090 * <h2 class='section'>Example:</h2> 091 * <p class='bjava'> 092 * <jc>// Create a request and automatically close it.</jc> 093 * <jk>try</jk> (<jv>RestRequest</jv> <jv>req</jv> = <jv>client</jv>.get(<js>"/myResource"</js>)) { 094 * <jv>req</jv> 095 * .queryData(<js>"foo"</js>, <js>"bar"</js>) 096 * .run() 097 * .assertStatus().asCode().is(200); 098 * } 099 * </p> 100 * 101 * <p> 102 * The {@link #close()} method will automatically close any associated {@link RestResponse} if one was created via {@link #run()}. 103 * 104 * <h2 class='section'>Notes:</h2><ul> 105 * <li class='warn'>This class is not thread safe. 106 * <li class='note'>This class implements {@link AutoCloseable} and can be used in try-with-resources blocks. 107 * The {@link #close()} method allows unchecked exceptions to propagate for debuggability, 108 * while catching and logging checked exceptions to follow AutoCloseable best practices. 109 * </ul> 110 * 111 * <h2 class='section'>See Also:</h2><ul> 112 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauRestClient">juneau-rest-client-classic</a> 113 * </ul> 114 */ 115@SuppressWarnings({ 116 "java:S1133", // Intentional deprecation retained for backward compatibility until the documented removal; the reminder is not actionable now. 117 "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants 118 "java:S3776", // Cognitive complexity acceptable for request-building and dispatch logic. 119 "java:S3740", // Raw Class/Supplier types used for fluent REST request building where response type is unknown at construction time 120 "java:S6539", // Monster class; RestRequest is intentionally a single per-request fluent builder aggregating headers/query/form/body/serialization config 121 "resource", // Resource management handled externally 122 "unchecked" // toMap() casts a value already verified to be a Map to Map<Object,Object>. 123}) 124public class RestRequest extends MarshallingSession implements HttpUriRequest, Configurable, AutoCloseable { 125 126 private static final String HEADER_ACCEPT = org.apache.juneau.http.header.Accept.NAME; 127 private static final String HEADER_CONTENT_TYPE = org.apache.juneau.http.header.ContentType.NAME; 128 129 // URI path separator (always "/" per RFC 3986) 130 private static final String URI_PATH_SEPARATOR = "/"; 131 132 private class SimpleFormData extends SimplePart { 133 SimpleFormData(NameValuePair x) { 134 super(x, client.isSkipEmptyFormData()); 135 } 136 } 137 138 private class SimpleHeader extends SimplePart implements Header { 139 140 SimpleHeader(NameValuePair x) { 141 super(x, client.isSkipEmptyHeaderData()); 142 } 143 144 @Override 145 public HeaderElement[] getElements() throws ParseException { return new HeaderElement[0]; } 146 } 147 148 private class SimplePart implements NameValuePair { 149 final String name; 150 final String value; 151 152 SimplePart(NameValuePair x, boolean skipIfEmpty) { 153 name = x.getName(); 154 if (x instanceof SerializedHeader x2) { 155 value = x2.copyWith(getPartSerializerSession(), null).getValue(); 156 } else if (x instanceof SerializedPart x2) { 157 value = x2.copyWith(getPartSerializerSession(), null).getValue(); 158 } else { 159 var v = x.getValue(); 160 value = (ie(v) && skipIfEmpty) ? null : v; 161 } 162 } 163 164 @Override 165 public String getName() { return name; } 166 167 @Override 168 public String getValue() { return value; } 169 170 boolean isValid() { 171 return !(ie(name) || value == null); 172 } 173 } 174 175 private class SimplePath extends SimplePart { 176 SimplePath(NameValuePair x) { 177 super(x, false); 178 } 179 } 180 181 private class SimpleQuery extends SimplePart { 182 SimpleQuery(NameValuePair x) { 183 super(x, client.isSkipEmptyQueryData()); 184 } 185 } 186 187 private static final ContentType TEXT_PLAIN = ContentType.TEXT_PLAIN; 188 189 private static boolean isHeaderArray(Object o) { 190 if (! isArray(o)) 191 return false; 192 return Header.class.isAssignableFrom(o.getClass().getComponentType()); 193 } 194 195 private static boolean isNameValuePairArray(Object o) { 196 if (! isArray(o)) 197 return false; 198 return NameValuePair.class.isAssignableFrom(o.getClass().getComponentType()); 199 } 200 201 private static Map<Object,Object> toMap(Object o) { 202 return (Map<Object,Object>)o; 203 } 204 205 final RestClient client; // The client that created this call. 206 private final HttpRequestBase request; // The request. 207 private boolean ignoreErrors; 208 private boolean suppressLogging; 209 private HttpContext context; 210 // Set for the request of an SSRF-guard-active @Remote call (by RestClient, or by run() while the calling thread runs 211 // a guarded call); it then sends every hop with the SsrfGuardMarker on its context. Volatile: the request's 212 // HttpClient may run on another thread. 213 private volatile boolean ssrfGuarded; 214 private HttpHost target; 215 private HttpPartSchema contentSchema; 216 private HttpPartSerializerSession partSerializerSession; 217 private final HeaderList headerData; 218 private List<Class<? extends Throwable>> rethrow; 219 List<RestCallInterceptor> interceptors = list(); // Used for intercepting and altering requests. 220 private Object content; 221 private Parser parser; 222 private final PartList formData; 223 private final PartList pathData; 224 private final PartList queryData; 225 private Predicate<Integer> errorCodes; 226 private RestResponse response; // The response. 227 private Serializer serializer; 228 private final URIBuilder uriBuilder; 229 230 private final Map<HttpPartSerializer,HttpPartSerializerSession> partSerializerSessions = new IdentityHashMap<>(); 231 232 /** 233 * Constructs a REST call with the specified method name. 234 * 235 * @param client The client that created this request. 236 * <br>Cannot be <jk>null</jk>. 237 * @param uri The target URI. 238 * <br>Cannot be <jk>null</jk>. 239 * @param method The HTTP method name (uppercase). 240 * <br>Cannot be <jk>null</jk>. 241 * @param hasBody Whether this method has a body. 242 * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt. 243 */ 244 protected RestRequest(RestClient client, URI uri, String method, boolean hasBody) throws RestCallException { 245 super(reqnn("client", client).getMarshallingContext().createSession()); 246 this.client = client; 247 this.request = createInnerRequest(reqnn("method", method), reqnn("uri", uri), hasBody); 248 this.errorCodes = client.errorCodes; 249 this.formData = client.createFormData(); 250 this.headerData = client.createHeaderData(); 251 this.ignoreErrors = client.ignoreErrors; 252 this.pathData = client.createPathData(); 253 this.queryData = client.createQueryData(); 254 this.uriBuilder = new URIBuilder(request.getURI()); 255 } 256 257 /** 258 * Aborts this http request. Any active execution of this method should return immediately. 259 * 260 * If the request has not started, it will abort after the next execution. 261 * <br>Aborting this request will cause all subsequent executions with this request to fail. 262 */ 263 @Override /* Overridden from HttpUriRequest */ 264 public void abort() throws UnsupportedOperationException { 265 request.abort(); 266 } 267 268 /** 269 * Sets the value for the <c>Accept</c> request header. 270 * 271 * <p> 272 * This overrides the media type specified on the parser, but is overridden by calling 273 * <code>header(<js>"Accept"</js>, value);</code> 274 * 275 * @param value The new header value. 276 * <br>Can be <jk>null</jk> (header will not be set). 277 * @return This object. 278 * @throws RestCallException Invalid input. 279 */ 280 public RestRequest accept(String value) throws RestCallException { 281 return header(Accept.of(value)); 282 } 283 284 /** 285 * Sets the value for the <c>Accept-Charset</c> request header. 286 * 287 * <p> 288 * This is a shortcut for calling <code>header(<js>"Accept-Charset"</js>, value);</code> 289 * 290 * @param value The new header value. 291 * <br>Can be <jk>null</jk> (header will not be set). 292 * @return This object. 293 * @throws RestCallException Invalid input. 294 */ 295 public RestRequest acceptCharset(String value) throws RestCallException { 296 return header(AcceptCharset.of(value)); 297 } 298 299 /** 300 * Adds a header to this message. 301 * 302 * The header will be appended to the end of the list. 303 * 304 * <h4 class='section'>Notes:</h4><ul> 305 * <li class='note'>{@link #header(Header)} is an equivalent method and the preferred method for fluent-style coding. 306 * </ul> 307 * 308 * @param header The header to append. 309 * <br>Can be <jk>null</jk> (ignored). 310 */ 311 @Override /* Overridden from HttpMessage */ 312 public void addHeader(Header header) { 313 headerData.append(header); 314 } 315 316 /** 317 * Adds a header to this message. 318 * 319 * The header will be appended to the end of the list. 320 * 321 * <h4 class='section'>Notes:</h4><ul> 322 * <li class='note'>{@link #header(String,Object)} is an equivalent method and the preferred method for fluent-style coding. 323 * </ul> 324 * 325 * @param name The name of the header. 326 * <br>Cannot be <jk>null</jk> or empty (header will not be created). 327 * @param value The value of the header. 328 * <br>Can be <jk>null</jk>. 329 */ 330 @Override /* Overridden from HttpMessage */ 331 public void addHeader(String name, String value) { 332 headerData.append(stringHeader(name, value)); 333 } 334 335 /** 336 * Sets {@link Cancellable} for the ongoing operation. 337 * 338 * @param cancellable The cancellable object. 339 * <br>Can be <jk>null</jk> (no cancellation will be available). 340 * @return This object. 341 */ 342 public RestRequest cancellable(Cancellable cancellable) { 343 request.setCancellable(cancellable); 344 return this; 345 } 346 347 /** 348 * Closes this request and its associated response (if one was created). 349 * 350 * <p> 351 * This method is idempotent and can be called multiple times without side effects. 352 * 353 * <h4 class='section'>Implementation Notes:</h4> 354 * <p> 355 * This implementation represents a compromise between strict AutoCloseable compliance and debuggability: 356 * <ul> 357 * <li>Unchecked exceptions ({@link RuntimeException} and {@link Error}) from the response close are allowed to propagate. 358 * This ensures programming errors and serious issues are visible during development and testing. 359 * <li>Checked exceptions (including {@link RestCallException}) are caught and logged but not thrown. 360 * This follows AutoCloseable best practices and prevents close exceptions from interfering with 361 * try-with-resources cleanup or masking the original exception. 362 * </ul> 363 */ 364 @Override /* Overridden from AutoCloseable */ 365 public void close() { 366 try { 367 if (nn(response)) { 368 response.close(); 369 } 370 } catch (RuntimeException e) { 371 // Let unchecked exceptions propagate for debuggability 372 throw e; 373 } catch (Exception e) { 374 // Log checked exceptions but don't throw - follows AutoCloseable best practices 375 client.log(Level.WARNING, e, "Error closing RestResponse"); 376 } 377 } 378 379 /** 380 * Same as {@link #run()} but immediately calls {@link RestResponse#consume()} to clean up the response. 381 * 382 * <p> 383 * Use this method if you're only interested in the status line of the response and not the response entity. 384 * Attempts to call any of the methods on the response object that retrieve the body (e.g. {@link ResponseContent#asReader()} 385 * will cause a {@link RestCallException} to be thrown. 386 * 387 * <h4 class='section'>Notes:</h4><ul> 388 * <li class='note'>You do not need to execute {@link InputStream#close()} on the response body to consume the response. 389 * </ul> 390 * 391 * <h4 class='section'>Example:</h4> 392 * <p class='bjava'> 393 * <jc>// Get the response code. 394 * // No need to call close() on the RestResponse object.</jc> 395 * <jk>int</jk> <jv>rc</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).complete().getResponseCode(); 396 * </p> 397 * 398 * @return The response object. 399 * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt. 400 */ 401 public RestResponse complete() throws RestCallException { 402 return run().consume(); 403 } 404 405 /** 406 * Used in combination with {@link #cancellable(Cancellable)}. 407 * 408 * @deprecated Since 10.0, for removal. 409 * @return This object. 410 */ 411 @Deprecated(since = "10.0", forRemoval = true) 412 public RestRequest completed() { 413 request.completed(); 414 return this; 415 } 416 417 /** 418 * Same as {@link #complete()} but allows you to run the call asynchronously. 419 * 420 * <h4 class='section'>Example:</h4> 421 * <p class='bjava'> 422 * Future<RestResponse> <jv>future</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).completeFuture(); 423 * 424 * <jc>// Do some other stuff</jc> 425 * 426 * <jk>int</jk> <jv>rc</jv> = <jv>future</jv>.get().getResponseStatus(); 427 * </p> 428 * 429 * <h4 class='section'>Notes:</h4><ul> 430 * <li class='note'>Use the {@link RestClient.Builder#executorService(ExecutorService, boolean)} method to customize the 431 * executor service used for creating {@link Future Futures}. 432 * <li class='note'>You do not need to execute {@link InputStream#close()} on the response body to consume the response. 433 * </ul> 434 * 435 * @return The HTTP status code. 436 * @throws RestCallException If the executor service was not defined. 437 */ 438 public Future<RestResponse> completeFuture() throws RestCallException { 439 return client.getExecutorService().submit(this::complete); 440 } 441 442 /** 443 * Sets the actual request configuration. 444 * 445 * @param value The new value. 446 * <br>Can be <jk>null</jk> (default configuration will be used). 447 * @return This object. 448 */ 449 public RestRequest config(RequestConfig value) { 450 request.setConfig(value); 451 return this; 452 } 453 454 /** 455 * Checks if a certain header is present in this message. 456 * 457 * Header values are ignored. 458 * 459 * @param name The header name to check for. 460 * <br>Cannot be <jk>null</jk>. 461 * @return <jk>true</jk> if at least one header with this name is present. 462 */ 463 @Override /* Overridden from HttpMessage */ 464 public boolean containsHeader(String name) { 465 return headerData.contains(name); 466 } 467 468 /** 469 * Sets the body of this request. 470 * 471 * @param value 472 * The input to be sent to the REST resource (only valid for PUT/POST/PATCH) requests. 473 * <br>Can be of the following types: 474 * <ul class='spaced-list'> 475 * <li> 476 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 477 * <li> 478 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 479 * <li> 480 * {@link HttpResource} - Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. 481 * <li> 482 * {@link HttpEntity}/{@link BasicHttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 483 * <li> 484 * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the 485 * {@link RestClient}. 486 * <li> 487 * {@link PartList} - Converted to a URL-encoded FORM post. 488 * <li> 489 * A {@link Supplier} of anything on this list. 490 * </ul> 491 * <br>Can be <jk>null</jk> (no body will be sent). 492 * @return This object. 493 */ 494 public RestRequest content(Object value) { 495 content = value; 496 return this; 497 } 498 499 /** 500 * Sets the body of this request. 501 * 502 * @param input 503 * The input to be sent to the REST resource (only valid for PUT/POST/PATCH) requests. 504 * <br>Can be of the following types: 505 * <ul class='spaced-list'> 506 * <li> 507 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 508 * <li> 509 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 510 * <li> 511 * {@link HttpResource} - Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. 512 * <li> 513 * {@link HttpEntity}/{@link BasicHttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 514 * <li> 515 * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the 516 * {@link RestClient}. 517 * <li> 518 * {@link PartList} - Converted to a URL-encoded FORM post. 519 * <li> 520 * A {@link Supplier} of anything on this list. 521 * </ul> 522 * @param schema The schema object that defines the format of the output. 523 * <ul> 524 * <li>If <jk>null</jk>, defaults to {@link HttpPartSchema#DEFAULT}. 525 * <li>Only used if serializer is schema-aware (e.g. {@link OpenApiSerializer}). 526 * </ul> 527 * @return This object. 528 */ 529 public RestRequest content(Object input, HttpPartSchema schema) { 530 this.content = input; 531 this.contentSchema = schema; 532 return this; 533 } 534 535 /** 536 * Sets the body of this request as straight text bypassing the serializer. 537 * 538 * <p class='bjava'> 539 * <jv>client</jv> 540 * .put(<js>"/foo"</js>) 541 * .content(<jk>new</jk> StringReader(<js>"foo"</js>)) 542 * .contentType(<js>"text/foo"</js>) 543 * .run(); 544 * 545 * <jv>client</jv> 546 * .put(<js>"/foo"</js>) 547 * .bodyString(<js>"foo"</js>) 548 * .run(); 549 * </p> 550 * 551 * <p> 552 * Note that this is different than the following which will serialize <l>foo</l> as a JSON string <l>"foo"</l>. 553 * <p class='bjava'> 554 * <jv>client</jv> 555 * .put(<js>"/foo"</js>) 556 * .json() 557 * .content(<js>"foo"</js>) 558 * .run(); 559 * </p> 560 * 561 * @param input 562 * The input to be sent to the REST resource (only valid for PUT/POST/PATCH) requests. 563 * @return This object. 564 * @throws RestCallException If a retry was attempted, but the entity was not repeatable. 565 */ 566 public RestRequest contentString(Object input) throws RestCallException { 567 return content(input == null ? null : new StringReader(s(input))); 568 } 569 570 /** 571 * Sets the value for the <c>Content-Type</c> request header. 572 * 573 * <p> 574 * This overrides the media type specified on the serializer, but is overridden by calling 575 * <code>header(<js>"Content-Type"</js>, value);</code> 576 * 577 * @param value The new header value. 578 * <br>Can be <jk>null</jk> (header will not be set). 579 * @return This object. 580 * @throws RestCallException Invalid input. 581 */ 582 public RestRequest contentType(String value) throws RestCallException { 583 return header(ContentType.of(value)); 584 } 585 586 /** 587 * Override the context to use for the execution. 588 * 589 * @param context The context to use for the execution, or <jk>null</jk> to use the default context. 590 * @return This object. 591 */ 592 public RestRequest context(HttpContext context) { 593 this.context = context; 594 return this; 595 } 596 597 /** 598 * Sets <c>Debug: value</c> header on this request. 599 * 600 * @return This object. 601 * @throws RestCallException Invalid input. 602 */ 603 public RestRequest debug() throws RestCallException { 604 header("Debug", true); 605 return this; 606 } 607 608 /** 609 * Allows you to override what status codes are considered error codes that would result in a {@link RestCallException}. 610 * 611 * <p> 612 * The default error code predicate is: <code>x -> x >= 400</code>. 613 * 614 * @param value The new predicate for calculating error codes. 615 * <br>Cannot be <jk>null</jk>. 616 * @return This object. 617 */ 618 public RestRequest errorCodes(Predicate<Integer> value) { 619 errorCodes = reqnn("value", value); 620 return this; 621 } 622 623 /** 624 * Appends multiple form-data parameters to the request. 625 * 626 * <h4 class='section'>Example:</h4> 627 * <p class='bjava'> 628 * <jc>// Appends two form-data parameters to the request.</jc> 629 * <jv>client</jv> 630 * .get(<jsf>URI</jsf>) 631 * .formData( 632 * BasicStringPart.<jsm>of</jsm>(<js>"foo"</js>, <js>"bar"</js>), 633 * BasicBooleanPart.<jsm>of</jsm>(<js>"baz"</js>, <jk>true</jk>) 634 * ) 635 * .run(); 636 * </p> 637 * 638 * @param parts 639 * The parameters to set. 640 * <jk>null</jk> values are ignored. 641 * @return This object. 642 */ 643 public RestRequest formData(NameValuePair...parts) { 644 formData.append(parts); 645 return this; 646 } 647 648 /** 649 * Adds a form-data parameter to the request body. 650 * 651 * <h4 class='section'>Example:</h4> 652 * <p class='bjava'> 653 * <jc>// Adds form data parameter "foo=bar".</jc> 654 * <jv>client</jv> 655 * .formPost(<jsf>URI</jsf>) 656 * .formData(<js>"foo"</js>, <js>"bar"</js>) 657 * .run(); 658 * </p> 659 * 660 * @param name 661 * The parameter name. 662 * <br>Cannot be <jk>null</jk> or empty (parameter will not be created). 663 * @param value 664 * The parameter value. 665 * <br>Non-string values are converted to strings using the {@link HttpPartSerializer} defined on the client. 666 * <br>Can be <jk>null</jk>. 667 * @return This object. 668 */ 669 public RestRequest formData(String name, Object value) { 670 formData.append(createPart(FORMDATA, name, value)); 671 return this; 672 } 673 674 /** 675 * Appends multiple form-data parameters to the request from properties defined on a Java bean. 676 * 677 * <h4 class='section'>Example:</h4> 678 * <p class='bjava'> 679 * <jk>public class</jk> MyFormData { 680 * <jk>public</jk> String getFooBar() { <jk>return</jk> <js>"baz"</js>; } 681 * <jk>public</jk> Integer getQux() { <jk>return</jk> 123; } 682 * } 683 * 684 * <jc>// Appends form data "fooBar=baz&qux=123".</jc> 685 * <jv>client</jv> 686 * .get(<jsf>URI</jsf>) 687 * .formDataBean(<jk>new</jk> MyFormData()) 688 * .run(); 689 * </p> 690 * 691 * @param value The bean containing the properties to set as form-data parameter values. 692 * <br>Cannot be <jk>null</jk>. 693 * @return This object. 694 */ 695 public RestRequest formDataBean(Object value) { 696 req(isBean(reqnn("value", value)), "Object passed into formDataBean(Object) is not a bean."); 697 var b = formData; 698 toBeanMap(value).forEach((k, v) -> b.append(createPart(FORMDATA, k, v))); 699 return this; 700 } 701 702 /** 703 * Adds form-data parameters as the entire body of the request. 704 * 705 * <h4 class='section'>Example:</h4> 706 * <p class='bjava'> 707 * <jc>// Creates form data "foo=bar&baz=qux".</jc> 708 * <jv>client</jv> 709 * .formPost(<jsf>URI</jsf>) 710 * .formDataCustom(<js>"foo=bar&baz=qux"</js>) 711 * .run(); 712 * 713 * <jc>// Creates form data "foo=bar&baz=qux" using StringEntity.</jc> 714 * <jv>client</jv> 715 * .formPost(<jsf>URI</jsf>) 716 * .formDataCustom(<jk>new</jk> StringEntity(<js>"foo=bar&baz=qux"</js>,<js>"application/x-www-form-urlencoded"</js>)) 717 * .run(); 718 * 719 * <jc>// Creates form data "foo=bar&baz=qux" using StringEntity and body().</jc> 720 * <jv>client</jv> 721 * .formPost(<jsf>URI</jsf>) 722 * .content(<jk>new</jk> StringEntity(<js>"foo=bar&baz=qux"</js>,<js>"application/x-www-form-urlencoded"</js>)) 723 * .run(); 724 * </p> 725 * 726 * @param value The parameter value. 727 * <br>Can be any of the following types: 728 * <ul class='spaced-list'> 729 * <li> 730 * {@link CharSequence} 731 * <li> 732 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 733 * <li> 734 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 735 * <li> 736 * {@link HttpResource} - Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. 737 * <li> 738 * {@link HttpEntity}/{@link BasicHttpEntity} - Bypass Juneau serialization and pass HttpEntity directly to HttpClient. 739 * <li> 740 * {@link Object} - POJO to be converted to text using the {@link Serializer} registered with the 741 * {@link RestClient}. 742 * <li> 743 * {@link PartList} - Converted to a URL-encoded FORM post. 744 * </ul> 745 * <br>Can be <jk>null</jk> (no body will be sent). 746 * @return This object. 747 */ 748 public RestRequest formDataCustom(Object value) { 749 header(ContentType.APPLICATION_FORM_URLENCODED); 750 content(value instanceof CharSequence ? new StringReader(value.toString()) : value); 751 return this; 752 } 753 754 /** 755 * Adds form-data parameters to the request body using free-form key/value pairs. 756 * 757 * <h4 class='section'>Example:</h4> 758 * <p class='bjava'> 759 * <jc>// Creates form data "key1=val1&key2=val2".</jc> 760 * <jv>client</jv> 761 * .formPost(<jsf>URI</jsf>) 762 * .formDataPairs(<js>"key1"</js>,<js>"val1"</js>,<js>"key2"</js>,<js>"val2"</js>) 763 * .run(); 764 * </p> 765 * 766 * @param pairs The form-data key/value pairs. 767 * <ul> 768 * <li>Values can be any POJO. 769 * <li>Values converted to a string using the configured part serializer. 770 * </ul> 771 * <br>Cannot be <jk>null</jk>. 772 * <br>Must have an even number of elements (key/value pairs). 773 * <br>Null keys are ignored (parameter will not be created). 774 * <br>Null values are allowed. 775 * @return This object. 776 * @throws RestCallException Invalid input. 777 */ 778 public RestRequest formDataPairs(String...pairs) throws RestCallException { 779 req(pairs.length % 2 == 0, "Odd number of parameters passed into formDataPairs(String...)"); 780 var b = formData; 781 for (var i = 0; i < pairs.length; i += 2) 782 b.append(pairs[i], pairs[i + 1]); 783 return this; 784 } 785 786 /** 787 * Returns all the headers of this message. 788 * 789 * Headers are ordered in the sequence they will be sent over a connection. 790 * 791 * @return All the headers of this message 792 */ 793 @Override /* Overridden from HttpMessage */ 794 public Header[] getAllHeaders() { return headerData.getAll(); } 795 796 /** 797 * Returns the actual request configuration. 798 * 799 * @return The actual request configuration. 800 */ 801 @Override /* Overridden from Configurable */ 802 public RequestConfig getConfig() { return request.getConfig(); } 803 804 /** 805 * Returns the first header with a specified name of this message. 806 * 807 * Header values are ignored. 808 * <br>If there is more than one matching header in the message the first element of {@link #getHeaders(String)} is returned. 809 * <br>If there is no matching header in the message <jk>null</jk> is returned. 810 * 811 * @param name The name of the header to return. 812 * <br>Cannot be <jk>null</jk>. 813 * @return The first header whose name property equals name or <jk>null</jk> if no such header could be found. 814 */ 815 @Override /* Overridden from HttpMessage */ 816 public Header getFirstHeader(String name) { 817 return headerData.getFirst(name).orElse(null); 818 } 819 820 /** 821 * Returns the form data for the request. 822 * 823 * @return An immutable list of form data to send on the request. 824 */ 825 public PartList getFormData() { return formData; } 826 827 /** 828 * Returns the header data for the request. 829 * 830 * @return An immutable list of headers to send on the request. 831 */ 832 public HeaderList getHeaders() { return headerData; } 833 834 /** 835 * Returns all the headers with a specified name of this message. 836 * 837 * Header values are ignored. 838 * <br>Headers are ordered in the sequence they will be sent over a connection. 839 * 840 * @param name The name of the headers to return. 841 * <br>Cannot be <jk>null</jk>. 842 * @return The headers whose name property equals name. 843 */ 844 @Override /* Overridden from HttpMessage */ 845 public Header[] getHeaders(String name) { 846 return headerData.getAll(name); 847 } 848 849 /** 850 * Returns the body of this request. 851 * 852 * @return The body of this request, or <jk>null</jk> if it doesn't have a body. 853 */ 854 public HttpEntity getHttpEntity() { return hasHttpEntity() ? ((HttpEntityEnclosingRequestBase)request).getEntity() : null; } 855 856 /** 857 * Returns the last header with a specified name of this message. 858 * 859 * Header values are ignored. 860 * <br>If there is more than one matching header in the message the last element of {@link #getHeaders(String)} is returned. 861 * <br>If there is no matching header in the message, <jk>null</jk> is returned. 862 * 863 * @param name The name of the header to return. 864 * <br>Cannot be <jk>null</jk>. 865 * @return The last header whose name property equals name or <jk>null</jk> if no such header could be found. 866 */ 867 @Override /* Overridden from HttpMessage */ 868 public Header getLastHeader(String name) { 869 return headerData.getLast(name).orElse(null); 870 } 871 872 /** 873 * Returns the HTTP method this request uses, such as GET, PUT, POST, or other. 874 * 875 * @return The HTTP method this request uses, such as GET, PUT, POST, or other. 876 */ 877 @Override /* Overridden from HttpUriRequest */ 878 public String getMethod() { return request.getMethod(); } 879 880 /** 881 * Returns the parameters effective for this message as set by {@link #setParams(HttpParams)}. 882 * 883 * @return The parameters effective for this message as set by {@link #setParams(HttpParams)}. 884 * @deprecated Use constructor parameters of configuration API provided by HttpClient. 885 */ 886 @Override /* Overridden from HttpMessage */ 887 @Deprecated(since = "10.0", forRemoval = true) 888 public HttpParams getParams() { return request.getParams(); } 889 890 /** 891 * Returns the path data for the request. 892 * 893 * @return An immutable list of path data to send on the request. 894 */ 895 public PartList getPathData() { return pathData; } 896 897 /** 898 * Returns the protocol version this message is compatible with. 899 * 900 * @return The protocol version. 901 */ 902 @Override /* Overridden from HttpMessage */ 903 public ProtocolVersion getProtocolVersion() { return request.getProtocolVersion(); } 904 905 /** 906 * Returns the query data for the request. 907 * 908 * @return An immutable list of query data to send on the request. 909 */ 910 public PartList getQueryData() { return queryData; } 911 912 /** 913 * Returns the request line of this request. 914 * 915 * @return The request line. 916 */ 917 @Override /* Overridden from HttpRequest */ 918 public RequestLine getRequestLine() { return request.getRequestLine(); } 919 920 /** 921 * A shortcut for calling <c>run().getContent().as(<js>type</js>)</c>. 922 * 923 * @param type The object type to create. 924 * <br>Cannot be <jk>null</jk>. 925 * @param <T> The object type to create. 926 * @see ResponseContent#as(Class) 927 * @return The response content as a simple string. 928 * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt. 929 */ 930 public <T> T getResponse(Class<T> type) throws RestCallException { 931 return run().getContent().as(type); 932 } 933 934 /** 935 * A shortcut for calling <c>run().getContent().as(<js>type</js>,<js>args</js>)</c>. 936 * 937 * @param <T> 938 * The object type to create. 939 * @param type 940 * The object type to create. 941 * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType} 942 * <br>Cannot be <jk>null</jk>. 943 * @param args 944 * The type arguments of the class if it's a collection or map. 945 * <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType} 946 * <br>Ignored if the main type is not a map or collection. 947 * <br>Can contain <jk>null</jk> values (ignored). 948 * @see ResponseContent#as(Type,Type...) 949 * @return The response content as a simple string. 950 * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt. 951 */ 952 public <T> T getResponse(Type type, Type...args) throws RestCallException { 953 return run().getContent().as(type, args); 954 } 955 956 /** 957 * A shortcut for calling <c>run().getContent().asString()</c>. 958 * 959 * @return The response content as a simple string. 960 * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt. 961 */ 962 public String getResponseAsString() throws RestCallException { return run().getContent().asString(); } 963 964 /** 965 * Returns the original request URI. 966 * 967 * <h4 class='section'>Notes:</h4><ul> 968 * <li class='note'>URI remains unchanged in the course of request execution and is not updated if the request is redirected to another location. 969 * </ul> 970 * 971 * @return The original request URI. 972 */ 973 @Override /* Overridden from HttpUriRequest */ 974 public URI getURI() { return request.getURI(); } 975 976 /** 977 * Returns <jk>true</jk> if this request has a body. 978 * 979 * @return <jk>true</jk> if this request has a body. 980 */ 981 public boolean hasHttpEntity() { 982 return request instanceof HttpEntityEnclosingRequestBase; 983 } 984 985 /** 986 * Appends a header to the request. 987 * 988 * <h4 class='section'>Example:</h4> 989 * <p class='bjava'> 990 * <jc>// Adds header "Foo: bar".</jc> 991 * <jv>client</jv> 992 * .get(<jsf>URI</jsf>) 993 * .header(Accept.<jsf>TEXT_XML</jsf>) 994 * .run(); 995 * </p> 996 * 997 * @param part 998 * The parameter to set. 999 * <jk>null</jk> values are ignored. 1000 * @return This object. 1001 */ 1002 public RestRequest header(Header part) { 1003 return headers(part); 1004 } 1005 1006 /** 1007 * Appends a header to the request. 1008 * 1009 * <h4 class='section'>Example:</h4> 1010 * <p class='bjava'> 1011 * <jc>// Adds header "Foo: bar".</jc> 1012 * <jv>client</jv> 1013 * .get(<jsf>URI</jsf>) 1014 * .header(<js>"Foo"</js>, <js>"bar"</js>) 1015 * .run(); 1016 * </p> 1017 * 1018 * @param name 1019 * The parameter name. 1020 * @param value 1021 * The parameter value. 1022 * <br>Non-string values are converted to strings using the {@link HttpPartSerializer} defined on the client. 1023 * @return This object. 1024 */ 1025 public RestRequest header(String name, Object value) { 1026 headerData.append(createHeader(name, value)); 1027 return this; 1028 } 1029 1030 /** 1031 * Returns an iterator of all the headers. 1032 * 1033 * @return Iterator that returns {@link Header} objects in the sequence they are sent over a connection. 1034 */ 1035 @Override /* Overridden from HttpMessage */ 1036 public HeaderIterator headerIterator() { 1037 return headerData.headerIterator(); 1038 } 1039 1040 /** 1041 * Returns an iterator of the headers with a given name. 1042 * 1043 * @param name the name of the headers over which to iterate, or <jk>null</jk> for all headers. 1044 * @return Iterator that returns {@link Header} objects with the argument name in the sequence they are sent over a connection. 1045 */ 1046 @Override /* Overridden from HttpMessage */ 1047 public HeaderIterator headerIterator(String name) { 1048 return headerData.headerIterator(name); 1049 } 1050 1051 /** 1052 * Appends multiple headers to the request using freeform key/value pairs. 1053 * 1054 * <h4 class='section'>Example:</h4> 1055 * <p class='bjava'> 1056 * <jc>// Adds headers "Foo: bar" and "Baz: qux".</jc> 1057 * <jv>client</jv> 1058 * .get(<jsf>URI</jsf>) 1059 * .headerPairs(<js>"Foo"</js>,<js>"bar"</js>,<js>"Baz"</js>,<js>"qux"</js>) 1060 * .run(); 1061 * </p> 1062 * 1063 * @param pairs The header key/value pairs. 1064 * <br>Cannot be <jk>null</jk>. 1065 * <br>Must have an even number of elements (key/value pairs). 1066 * <br>Null keys are ignored (header will not be created). 1067 * <br>Null values are allowed. 1068 * @return This object. 1069 */ 1070 public RestRequest headerPairs(String...pairs) { 1071 req(pairs.length % 2 == 0, "Odd number of parameters passed into headerPairs(String...)"); 1072 var b = headerData; 1073 for (var i = 0; i < pairs.length; i += 2) 1074 b.append(pairs[i], pairs[i + 1]); 1075 return this; 1076 } 1077 1078 /** 1079 * Appends multiple headers to the request. 1080 * 1081 * <h4 class='section'>Example:</h4> 1082 * <p class='bjava'> 1083 * <jc>// Appends two headers to the request.</jc> 1084 * <jv>client</jv> 1085 * .get(<jsf>URI</jsf>) 1086 * .headers( 1087 * BasicHeader.<jsm>of</jsm>(<js>"Foo"</js>, <js>"bar"</js>), 1088 * Accept.<jsf>TEXT_XML</jsf> 1089 * ) 1090 * .run(); 1091 * </p> 1092 * 1093 * @param parts 1094 * The parameters to set. 1095 * <jk>null</jk> values are ignored. 1096 * @return This object. 1097 */ 1098 public RestRequest headers(Header...parts) { 1099 headerData.append(parts); 1100 return this; 1101 } 1102 1103 /** 1104 * Appends multiple headers to the request from properties defined on a Java bean. 1105 * 1106 * <p> 1107 * Uses {@link PropertyNamerDUCS} for resolving the header names from property names. 1108 * 1109 * <h4 class='section'>Example:</h4> 1110 * <p class='bjava'> 1111 * <ja>@Marshalled</ja> 1112 * <jk>public class</jk> MyHeaders { 1113 * <jk>public</jk> String getFooBar() { <jk>return</jk> <js>"baz"</js>; } 1114 * <jk>public</jk> Integer getQux() { <jk>return</jk> 123; } 1115 * } 1116 * 1117 * <jc>// Appends headers "Foo-Bar: baz" and "Qux: 123".</jc> 1118 * <jv>client</jv> 1119 * .get(<jsf>URI</jsf>) 1120 * .headersBean(<jk>new</jk> MyHeaders()) 1121 * .run(); 1122 * </p> 1123 * 1124 * @param value The bean containing the properties to set as header values. 1125 * <br>Cannot be <jk>null</jk>. 1126 * @return This object. 1127 */ 1128 public RestRequest headersBean(Object value) { 1129 req(isBean(reqnn("value", value)), "Object passed into headersBean(Object) is not a bean."); 1130 var b = headerData; 1131 toBeanMap(value, PropertyNamerDUCS.INSTANCE).forEach((k, v) -> b.append(createHeader(k, v))); 1132 return this; 1133 } 1134 1135 /** 1136 * Convenience method for specifying HTML as the marshalling transmission media type for this request only. 1137 * 1138 * <p> 1139 * POJOs are converted to HTML without any sort of doc wrappers. 1140 * 1141 * <p> 1142 * {@link HtmlSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 1143 * <ul> 1144 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 1145 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1146 * </ul> 1147 * <p> 1148 * {@link HtmlParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 1149 * <ul> 1150 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1151 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1152 * </ul> 1153 * <p> 1154 * <c>Accept</c> request header will be set to <js>"text/html"</js> unless overridden 1155 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 1156 * <p> 1157 * <c>Content-Type</c> request header will be set to <js>"text/html"</js> unless overridden 1158 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 1159 * <p> 1160 * Identical to calling <c>serializer(HtmlSerializer.<jk>class</jk>).parser(HtmlParser.<jk>class</jk>)</c>. 1161 * 1162 * @return This object. 1163 */ 1164 public RestRequest html() { 1165 return serializer(HtmlSerializer.class).parser(HtmlParser.class); 1166 } 1167 1168 /** 1169 * Convenience method for specifying HTML DOC as the marshalling transmission media type for this request only. 1170 * 1171 * <p> 1172 * POJOs are converted to fully renderable HTML pages. 1173 * 1174 * <p> 1175 * {@link HtmlDocSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 1176 * <ul> 1177 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 1178 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1179 * </ul> 1180 * <p> 1181 * {@link HtmlParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 1182 * <ul> 1183 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1184 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1185 * </ul> 1186 * <p> 1187 * <c>Accept</c> request header will be set to <js>"text/html"</js> unless overridden 1188 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 1189 * <p> 1190 * <c>Content-Type</c> request header will be set to <js>"text/html"</js> unless overridden 1191 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 1192 * <p> 1193 * Identical to calling <c>serializer(HtmlDocSerializer.<jk>class</jk>).parser(HtmlParser.<jk>class</jk>)</c>. 1194 * 1195 * @return This object. 1196 */ 1197 public RestRequest htmlDoc() { 1198 return serializer(HtmlDocSerializer.class).parser(HtmlParser.class); 1199 } 1200 1201 /** 1202 * Convenience method for specifying Stripped HTML DOC as the marshalling transmission media type for this request only. 1203 * 1204 * <p> 1205 * Same as {@link #htmlDoc()} but without the header and body tags and page title and description. 1206 * 1207 * <p> 1208 * {@link HtmlStrippedDocSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 1209 * <ul> 1210 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 1211 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1212 * </ul> 1213 * <p> 1214 * {@link HtmlParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 1215 * <ul> 1216 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1217 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1218 * </ul> 1219 * <p> 1220 * <c>Accept</c> request header will be set to <js>"text/html+stripped"</js> unless overridden 1221 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 1222 * <p> 1223 * <c>Content-Type</c> request header will be set to <js>"text/html+stripped"</js> unless overridden 1224 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 1225 * <p> 1226 * Identical to calling <c>serializer(HtmlStrippedDocSerializer.<jk>class</jk>).parser(HtmlParser.<jk>class</jk>)</c>. 1227 * 1228 * @return This object. 1229 */ 1230 public RestRequest htmlStrippedDoc() { 1231 return serializer(HtmlStrippedDocSerializer.class).parser(HtmlParser.class); 1232 } 1233 1234 /** 1235 * Prevent {@link RestCallException RestCallExceptions} from being thrown when HTTP status 400+ is encountered. 1236 * 1237 * <p> 1238 * This overrides the <l>ignoreErrors</l> property on the client. 1239 * 1240 * @return This object. 1241 */ 1242 public RestRequest ignoreErrors() { 1243 this.ignoreErrors = true; 1244 return this; 1245 } 1246 1247 /** 1248 * Add one or more interceptors for this call only. 1249 * 1250 * @param interceptors The interceptors to add to this call. 1251 * <br>Cannot contain <jk>null</jk> values. 1252 * @return This object. 1253 * @throws RestCallException If init method on interceptor threw an exception. 1254 */ 1255 public RestRequest interceptors(RestCallInterceptor...interceptors) throws RestCallException { 1256 reqnns("interceptors", interceptors); 1257 try { 1258 for (var i : interceptors) { 1259 this.interceptors.add(i); 1260 i.onInit(this); 1261 } 1262 } catch (RuntimeException | RestCallException e) { 1263 throw e; 1264 } catch (Exception e) { 1265 throw new RestCallException(null, e, "Interceptor threw an exception on init."); 1266 } 1267 1268 return this; 1269 } 1270 1271 @Override /* Overridden from HttpUriRequest */ 1272 public boolean isAborted() { return request.isAborted(); } 1273 1274 /** 1275 * Returns <jk>true</jk> if debug mode is currently enabled. 1276 */ 1277 @Override 1278 public boolean isDebug() { return headerData.get("Debug", Boolean.class).orElse(false); } 1279 1280 /** 1281 * Convenience method for specifying JSON as the marshalling transmission media type for this request only. 1282 * 1283 * <p> 1284 * {@link JsonSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 1285 * <ul> 1286 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 1287 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1288 * </ul> 1289 * <p> 1290 * {@link JsonParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 1291 * <ul> 1292 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1293 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1294 * </ul> 1295 * <p> 1296 * <c>Accept</c> request header will be set to <js>"application/json"</js> unless overridden 1297 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 1298 * <p> 1299 * <c>Content-Type</c> request header will be set to <js>"application/json"</js> unless overridden 1300 * {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 1301 * <p> 1302 * Identical to calling <c>serializer(JsonSerializer.<jk>class</jk>).parser(JsonParser.<jk>class</jk>)</c>. 1303 * 1304 * @return This object. 1305 */ 1306 public RestRequest json() { 1307 return serializer(JsonSerializer.class).parser(JsonParser.class); 1308 } 1309 1310 /** 1311 * Convenience method for specifying Simplified JSON as the marshalling transmission media type for this request only. 1312 * 1313 * <p> 1314 * Simplified JSON is typically useful for automated tests because you can do simple string comparison of results 1315 * without having to escape lots of quotes. 1316 * 1317 * <p> 1318 * {@link Json5Serializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 1319 * <ul> 1320 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 1321 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1322 * </ul> 1323 * <p> 1324 * {@link Json5Parser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 1325 * <ul> 1326 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1327 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1328 * </ul> 1329 * <p> 1330 * <c>Accept</c> request header will be set to <js>"application/json5"</js> unless overridden 1331 * by {@link #header(String,Object)} or {@link #accept(String)}, or per-request via {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 1332 * <p> 1333 * <c>Content-Type</c> request header will be set to <js>"application/json5"</js> unless overridden 1334 * by {@link #header(String,Object)} or {@link #contentType(String)}, or per-request via {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 1335 * <p> 1336 * A server that only handles JSON may reply <c>406 Not Acceptable</c> or <c>415 Unsupported Media Type</c> to these 1337 * JSON5 media types. 1338 * <p> 1339 * Can be combined with other marshaller setters such as {@link #xml()} to provide support for multiple languages. 1340 * <ul> 1341 * <li>When multiple languages are supported, the <c>Accept</c> and <c>Content-Type</c> headers control which marshallers are used, or uses the 1342 * last-enabled language if the headers are not set. 1343 * </ul> 1344 * <p> 1345 * Identical to calling <c>serializer(Json5Serializer.<jk>class</jk>).parser(Json5Parser.<jk>class</jk>)</c>. 1346 * 1347 * @return This object. 1348 */ 1349 public RestRequest json5() { 1350 return serializer(Json5Serializer.class).parser(Json5Parser.class); 1351 } 1352 1353 /** 1354 * Convenience method for specifying JCS (JSON Canonicalization Scheme, RFC 8785) as the marshalling transmission media type for this request only. 1355 * 1356 * <p> 1357 * {@link JcsSerializer} will be used to serialize POJOs to request bodies. 1358 * {@link JsonParser} will be used to parse POJOs from response bodies (JCS output is valid JSON). 1359 * <p> 1360 * <c>Accept</c> and <c>Content-Type</c> will be set to <js>"application/jcs+json"</js>. 1361 * <p> 1362 * Identical to calling <c>serializer(JcsSerializer.<jk>class</jk>).parser(JsonParser.<jk>class</jk>)</c>. 1363 * 1364 * @return This object. 1365 */ 1366 public RestRequest jcs() { 1367 return serializer(JcsSerializer.class).parser(JsonParser.class); 1368 } 1369 1370 /** 1371 * Logs a message. 1372 * 1373 * @param level The log level. 1374 * <br>Cannot be <jk>null</jk>. 1375 * @param msg The message with {@link String#format(String, Object...) String.format}-style (<c>%s</c>) arguments. 1376 * <br>Cannot be <jk>null</jk>. 1377 * @param args The arguments. 1378 * <br>Can contain <jk>null</jk> values. 1379 * @return This object. 1380 */ 1381 public RestRequest log(Level level, String msg, Object...args) { 1382 client.log(level, msg, args); 1383 return this; 1384 } 1385 1386 /** 1387 * Logs a message. 1388 * 1389 * @param level The log level. 1390 * <br>Cannot be <jk>null</jk>. 1391 * @param t The throwable cause. 1392 * <br>Can be <jk>null</jk> (no exception details are logged). 1393 * @param msg The message with {@link String#format(String, Object...) String.format}-style (<c>%s</c>) arguments. 1394 * <br>Cannot be <jk>null</jk>. 1395 * @param args The arguments. 1396 * <br>Can contain <jk>null</jk> values. 1397 * @return This object. 1398 */ 1399 public RestRequest log(Level level, Throwable t, String msg, Object...args) { 1400 client.log(level, t, msg, args); 1401 return this; 1402 } 1403 1404 /** 1405 * Shortcut for setting the <c>Accept</c> and <c>Content-Type</c> headers on a request. 1406 * 1407 * @param value The new header values. 1408 * <br>Can be <jk>null</jk> (headers will not be set). 1409 * @return This object. 1410 * @throws RestCallException Invalid input. 1411 */ 1412 public RestRequest mediaType(String value) throws RestCallException { 1413 return header(Accept.of(value)).header(ContentType.of(value)); 1414 } 1415 1416 /** 1417 * Convenience method for specifying BSON as the marshalling transmission media type for this request only. 1418 * 1419 * <p> 1420 * Identical to calling <c>serializer(BsonSerializer.<jk>class</jk>).parser(BsonParser.<jk>class</jk>)</c>. 1421 * 1422 * @return This object. 1423 */ 1424 public RestRequest bson() { 1425 return serializer(BsonSerializer.class).parser(BsonParser.class); 1426 } 1427 1428 /** 1429 * Convenience method for specifying MessagePack as the marshalling transmission media type for this request only. 1430 * 1431 * <p> 1432 * MessagePack is a binary equivalent to JSON that takes up considerably less space than JSON. 1433 * 1434 * <p> 1435 * {@link MsgPackSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 1436 * <ul> 1437 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 1438 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1439 * </ul> 1440 * <p> 1441 * {@link MsgPackParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 1442 * <ul> 1443 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1444 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1445 * </ul> 1446 * <p> 1447 * <c>Accept</c> request header will be set to <js>"application/msgpack"</js> unless overridden 1448 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 1449 * <p> 1450 * <c>Content-Type</c> request header will be set to <js>"application/msgpack"</js> unless overridden 1451 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 1452 * <p> 1453 * Identical to calling <c>serializer(MsgPackSerializer.<jk>class</jk>).parser(MsgPackParser.<jk>class</jk>)</c>. 1454 * 1455 * @return This object. 1456 */ 1457 public RestRequest msgPack() { 1458 return serializer(MsgPackSerializer.class).parser(MsgPackParser.class); 1459 } 1460 1461 /** 1462 * When called, <c>No-Trace: true</c> is added to requests. 1463 * 1464 * <p> 1465 * This gives the opportunity for the servlet to not log errors on invalid requests. 1466 * This is useful for testing purposes when you don't want your log file to show lots of errors that are simply the 1467 * results of testing. 1468 * 1469 * @return This object. 1470 * @throws RestCallException Invalid input. 1471 */ 1472 public RestRequest noTrace() throws RestCallException { 1473 return header(NoTrace.TRUE); 1474 } 1475 1476 /** 1477 * Convenience method for specifying OpenAPI as the marshalling transmission media type for this request only. 1478 * 1479 * <p> 1480 * OpenAPI is a language that allows serialization to formats that use {@link HttpPartSchema} objects to describe their structure. 1481 * 1482 * <p> 1483 * {@link OpenApiSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 1484 * <ul> 1485 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 1486 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1487 * <li>Typically the {@link RestRequest#content(Object, HttpPartSchema)} method will be used to specify the body of the request with the 1488 * schema describing it's structure. 1489 * </ul> 1490 * <p> 1491 * {@link OpenApiParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 1492 * <ul> 1493 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1494 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1495 * <li>Typically the {@link ResponseContent#schema(HttpPartSchema)} method will be used to specify the structure of the response body. 1496 * </ul> 1497 * <p> 1498 * <c>Accept</c> request header will be set to <js>"text/openapi"</js> unless overridden 1499 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 1500 * <p> 1501 * <c>Content-Type</c> request header will be set to <js>"text/openapi"</js> unless overridden 1502 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 1503 * <p> 1504 * Identical to calling <c>serializer(OpenApiSerializer.<jk>class</jk>).parser(OpenApiParser.<jk>class</jk>)</c>. 1505 * 1506 * @return This object. 1507 */ 1508 public RestRequest openApi() { 1509 return serializer(OpenApiSerializer.class).parser(OpenApiParser.class); 1510 } 1511 1512 /** 1513 * Specifies the parser to use on the response body. 1514 * 1515 * <p> 1516 * Overrides the parsers specified on the {@link RestClient}. 1517 * 1518 * <p> 1519 * The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1520 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1521 * 1522 * <p> 1523 * If the <c>Accept</c> header is not set on the request, it will be set to the media type of this parser. 1524 * 1525 * @param parser The parser used to parse POJOs from the body of the HTTP response. 1526 * <br>Cannot be <jk>null</jk>. 1527 * @return This object. 1528 */ 1529 public RestRequest parser(Class<? extends Parser> parser) { 1530 this.parser = client.getInstance(reqnn("parser", parser)); 1531 return this; 1532 } 1533 1534 /** 1535 * Specifies the parser to use on the response body. 1536 * 1537 * <p> 1538 * Overrides the parsers specified on the {@link RestClient}. 1539 * 1540 * <p> 1541 * The parser is not modified by any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1542 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1543 * 1544 * <p> 1545 * If the <c>Accept</c> header is not set on the request, it will be set to the media type of this parser. 1546 * 1547 * @param parser The parser used to parse POJOs from the body of the HTTP response. 1548 * <br>Cannot be <jk>null</jk>. 1549 * @return This object. 1550 */ 1551 public RestRequest parser(Parser parser) { 1552 this.parser = reqnn("parser", parser); 1553 return this; 1554 } 1555 1556 /** 1557 * Sets or replaces multiple path parameters on the request. 1558 * 1559 * <h4 class='section'>Example:</h4> 1560 * <p class='bjava'> 1561 * <jc>// Appends two path parameters to the request.</jc> 1562 * <jv>client</jv> 1563 * .get(<jsf>URI</jsf>) 1564 * .pathData( 1565 * BasicStringPart.<jsm>of</jsm>(<js>"foo"</js>, <js>"bar"</js>), 1566 * BasicBooleanPart.<jsm>of</jsm>(<js>"baz"</js>, <jk>true</jk>) 1567 * ) 1568 * .run(); 1569 * </p> 1570 * 1571 * @param parts 1572 * The parameters to set. 1573 * <jk>null</jk> values are ignored. 1574 * @return This object. 1575 */ 1576 public RestRequest pathData(NameValuePair...parts) { 1577 pathData.set(parts); 1578 return this; 1579 } 1580 1581 /** 1582 * Sets or replaces a path parameter of the form <js>"{name}"</js> in the URI. 1583 * 1584 * <h4 class='section'>Example:</h4> 1585 * <p class='bjava'> 1586 * <jc>// Sets path to "/bar".</jc> 1587 * <jv>client</jv> 1588 * .get(<js>"/{foo}"</js>) 1589 * .pathData(<js>"foo"</js>, <js>"bar"</js>) 1590 * .run(); 1591 * </p> 1592 * 1593 * @param name 1594 * The parameter name. 1595 * <br>Cannot be <jk>null</jk> or empty (parameter will not be created). 1596 * @param value 1597 * The parameter value. 1598 * <br>Non-string values are converted to strings using the {@link HttpPartSerializer} defined on the client. 1599 * <br>Can be <jk>null</jk>. 1600 * @return This object. 1601 */ 1602 public RestRequest pathData(String name, Object value) { 1603 pathData.set(createPart(PATH, name, value)); 1604 return this; 1605 } 1606 1607 /** 1608 * Sets multiple path parameters to the request from properties defined on a Java bean. 1609 * 1610 * <h4 class='section'>Example:</h4> 1611 * <p class='bjava'> 1612 * <jk>public class</jk> MyPathVars { 1613 * <jk>public</jk> String getFooBar() { <jk>return</jk> <js>"baz"</js>; } 1614 * <jk>public</jk> Integer getQux() { <jk>return</jk> 123; } 1615 * } 1616 * 1617 * <jc>// Given path "/{fooBar}/{qux}/", gets converted to "/baz/123/".</jc> 1618 * <jv>client</jv> 1619 * .get(<jsf>URI</jsf>) 1620 * .pathDataBean(<jk>new</jk> MyPathVars()) 1621 * .run(); 1622 * </p> 1623 * 1624 * @param value The bean containing the properties to set as path parameter values. 1625 * <br>Cannot be <jk>null</jk>. 1626 * @return This object. 1627 */ 1628 public RestRequest pathDataBean(Object value) { 1629 req(isBean(reqnn("value", value)), "Object passed into pathDataBean(Object) is not a bean."); 1630 var b = pathData; 1631 toBeanMap(value).forEach((k, v) -> b.set(createPart(PATH, k, v))); 1632 return this; 1633 } 1634 1635 /** 1636 * Replaces path parameters of the form <js>"{name}"</js> in the URI using free-form key/value pairs. 1637 * 1638 * <h4 class='section'>Example:</h4> 1639 * <p class='bjava'> 1640 * <jc>// Sets path to "/baz/qux".</jc> 1641 * <jv>client</jv> 1642 * .get(<js>"/{foo}/{bar}"</js>) 1643 * .pathDataPairs( 1644 * <js>"foo"</js>,<js>"baz"</js>, 1645 * <js>"bar"</js>,<js>"qux"</js> 1646 * ) 1647 * .run(); 1648 * </p> 1649 * 1650 * @param pairs The path key/value pairs. 1651 * <ul> 1652 * <li>Values can be any POJO. 1653 * <li>Values converted to a string using the configured part serializer. 1654 * </ul> 1655 * <br>Cannot be <jk>null</jk>. 1656 * <br>Must have an even number of elements (key/value pairs). 1657 * <br>Null keys are ignored (parameter will not be created). 1658 * <br>Null values are allowed. 1659 * @return This object. 1660 */ 1661 public RestRequest pathDataPairs(String...pairs) { 1662 req(pairs.length % 2 == 0, "Odd number of parameters passed into pathDataPairs(String...)"); 1663 var b = pathData; 1664 for (var i = 0; i < pairs.length; i += 2) 1665 b.set(pairs[i], pairs[i + 1]); 1666 return this; 1667 } 1668 1669 /** 1670 * Convenience method for specifying Plain Text as the marshalling transmission media type for this request only. 1671 * 1672 * <p> 1673 * Plain text marshalling typically only works on simple POJOs that can be converted to and from strings using 1674 * swaps, swap methods, etc... 1675 * 1676 * <p> 1677 * {@link PlainTextSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 1678 * <ul> 1679 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 1680 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1681 * </ul> 1682 * <p> 1683 * {@link PlainTextParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 1684 * <ul> 1685 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 1686 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 1687 * </ul> 1688 * <p> 1689 * <c>Accept</c> request header will be set to <js>"text/plain"</js> unless overridden 1690 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 1691 * <p> 1692 * <c>Content-Type</c> request header will be set to <js>"text/plain"</js> unless overridden 1693 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 1694 * <p> 1695 * Identical to calling <c>serializer(PlainTextSerializer.<jk>class</jk>).parser(PlainTextParser.<jk>class</jk>)</c>. 1696 * 1697 * @return This object. 1698 */ 1699 public RestRequest plainText() { 1700 return serializer(PlainTextSerializer.class).parser(PlainTextParser.class); 1701 } 1702 1703 /** 1704 * Sets the {@code X-Juneau-Serializer-Options} header for this request. 1705 * 1706 * <p> 1707 * The value is a JSON5 object whose keys are serializer session property names and values are the overrides. 1708 * Example: <js>"{escapeSolidus:true,maxIndent:4}"</js>. 1709 * 1710 * @param json5 1711 * Serializer session options as JSON5. Can be <jk>null</jk> (header is not set). 1712 * @return This object. 1713 */ 1714 public RestRequest serializerSessionOptionsHeader(String json5) { 1715 return header(HEADER_JuneauSerializerOptions, json5); 1716 } 1717 1718 /** 1719 * Sets the {@code X-Juneau-Parser-Options} header for this request. 1720 * 1721 * <p> 1722 * The value is a JSON5 object whose keys are parser session property names and values are the overrides. 1723 * 1724 * @param json5 1725 * Parser session options as JSON5. Can be <jk>null</jk> (header is not set). 1726 * @return This object. 1727 */ 1728 public RestRequest parserSessionOptionsHeader(String json5) { 1729 return header(HEADER_JuneauParserOptions, json5); 1730 } 1731 1732 /** 1733 * Convenience for {@link #serializerSessionOptionsHeader(String)} using a map serialized with {@link Json5#of(Object)}. 1734 * 1735 * @param properties 1736 * Property map for serializer session options. Can be <jk>null</jk> (treated as empty). 1737 * @return This object. 1738 * @throws SerializeException If serializing {@code properties} to JSON5 fails. 1739 */ 1740 public RestRequest serializerSessionOptionsHeader(Map<String,?> properties) { 1741 if (isEmpty(properties)) 1742 return this; 1743 return header(HEADER_JuneauSerializerOptions, Json5.of(properties)); 1744 } 1745 1746 /** 1747 * Convenience for {@link #parserSessionOptionsHeader(String)} using a map serialized with {@link Json5#of(Object)}. 1748 * 1749 * @param properties 1750 * Property map for parser session options. Can be <jk>null</jk> (treated as empty). 1751 * @return This object. 1752 * @throws SerializeException If serializing {@code properties} to JSON5 fails. 1753 */ 1754 public RestRequest parserSessionOptionsHeader(Map<String,?> properties) { 1755 if (isEmpty(properties)) 1756 return this; 1757 return header(HEADER_JuneauParserOptions, Json5.of(properties)); 1758 } 1759 1760 /** 1761 * Sets the {@code juneauSerializerOptions} query parameter for this request (UON-encoded map). 1762 * 1763 * <p> 1764 * Example: <js>"(escapeSolidus=true,maxIndent=4)"</js>. 1765 * 1766 * @param uon 1767 * Serializer session options in UON form. Can be <jk>null</jk> (parameter is not set). 1768 * @return This object. 1769 */ 1770 public RestRequest serializerSessionOptionsQuery(String uon) { 1771 return queryData(QUERY_juneauSerializerOptions, uon); 1772 } 1773 1774 /** 1775 * Sets the {@code juneauParserOptions} query parameter for this request (UON-encoded map). 1776 * 1777 * @param uon 1778 * Parser session options in UON form. Can be <jk>null</jk> (parameter is not set). 1779 * @return This object. 1780 */ 1781 public RestRequest parserSessionOptionsQuery(String uon) { 1782 return queryData(QUERY_juneauParserOptions, uon); 1783 } 1784 1785 /** 1786 * Convenience for {@link #serializerSessionOptionsQuery(String)} using {@link Uon#of(Object)}. 1787 * 1788 * @param properties 1789 * Property map for serializer session options. Can be <jk>null</jk> (treated as empty). 1790 * @return This object. 1791 * @throws SerializeException If serializing {@code properties} to UON fails. 1792 */ 1793 public RestRequest serializerSessionOptionsQuery(Map<String,?> properties) { 1794 if (isEmpty(properties)) 1795 return this; 1796 return serializerSessionOptionsQuery(Uon.of(properties)); 1797 } 1798 1799 /** 1800 * Convenience for {@link #parserSessionOptionsQuery(String)} using {@link Uon#of(Object)}. 1801 * 1802 * @param properties 1803 * Property map for parser session options. Can be <jk>null</jk> (treated as empty). 1804 * @return This object. 1805 * @throws SerializeException If serializing {@code properties} to UON fails. 1806 */ 1807 public RestRequest parserSessionOptionsQuery(Map<String,?> properties) { 1808 if (isEmpty(properties)) 1809 return this; 1810 return parserSessionOptionsQuery(Uon.of(properties)); 1811 } 1812 1813 /** 1814 * Sets the protocol version for this request. 1815 * 1816 * @param version The protocol version for this request. 1817 * <br>Can be <jk>null</jk> (default protocol version will be used). 1818 * @return This object. 1819 */ 1820 public RestRequest protocolVersion(ProtocolVersion version) { 1821 request.setProtocolVersion(version); 1822 return this; 1823 } 1824 1825 /** 1826 * Adds a free-form custom query. 1827 * 1828 * <h4 class='section'>Example:</h4> 1829 * <p class='bjava'> 1830 * <jc>// Adds query parameter "foo=bar&baz=qux".</jc> 1831 * <jv>client</jv> 1832 * .get(<jsf>URI</jsf>) 1833 * .queryCustom(<js>"foo=bar&baz=qux"</js>) 1834 * .run(); 1835 * </p> 1836 * 1837 * @param value The parameter value. 1838 * <br>Can be any of the following types: 1839 * <ul> 1840 * <li> 1841 * {@link CharSequence} 1842 * <li> 1843 * {@link Reader} - Raw contents of {@code Reader} will be serialized to remote resource. 1844 * <li> 1845 * {@link InputStream} - Raw contents of {@code InputStream} will be serialized to remote resource. 1846 * <li> 1847 * {@link PartList} - Converted to a URL-encoded query. 1848 * </ul> 1849 * <br>Can be <jk>null</jk> (no custom query will be set). 1850 * @return This object. 1851 */ 1852 public RestRequest queryCustom(Object value) { 1853 try { 1854 String q = null; 1855 if (value instanceof Reader value2) 1856 q = read(value2); 1857 else if (value instanceof InputStream value2) 1858 q = read(value2); 1859 else 1860 q = s(value); // Works for NameValuePairs. 1861 uriBuilder.setCustomQuery(q); 1862 } catch (IOException e) { 1863 throw rex(e, "Could not read custom query."); 1864 } 1865 return this; 1866 } 1867 1868 /** 1869 * Appends multiple query parameters to the request. 1870 * 1871 * <h4 class='section'>Example:</h4> 1872 * <p class='bjava'> 1873 * <jc>// Appends two query parameters to the request.</jc> 1874 * <jv>client</jv> 1875 * .get(<jsf>URI</jsf>) 1876 * .queryData( 1877 * BasicStringPart.<jsm>of</jsm>(<js>"foo"</js>, <js>"bar"</js>), 1878 * BasicBooleanPart.<jsm>of</jsm>(<js>"baz"</js>, <jk>true</jk>) 1879 * ) 1880 * .run(); 1881 * </p> 1882 * 1883 * @param parts 1884 * The parameters to set. 1885 * <jk>null</jk> values are ignored. 1886 * @return This object. 1887 */ 1888 public RestRequest queryData(NameValuePair...parts) { 1889 queryData.append(parts); 1890 return this; 1891 } 1892 1893 /** 1894 * Appends a query parameter to the URI of the request. 1895 * 1896 * <h4 class='section'>Example:</h4> 1897 * <p class='bjava'> 1898 * <jc>// Adds query parameter "foo=bar".</jc> 1899 * <jv>client</jv> 1900 * .get(<jsf>URI</jsf>) 1901 * .queryData(<js>"foo"</js>, <js>"bar"</js>) 1902 * .run(); 1903 * </p> 1904 * 1905 * @param name 1906 * The parameter name. 1907 * <br>Cannot be <jk>null</jk> or empty (parameter will not be created). 1908 * @param value 1909 * The parameter value. 1910 * <br>Non-string values are converted to strings using the {@link HttpPartSerializer} defined on the client. 1911 * <br>Can be <jk>null</jk>. 1912 * @return This object. 1913 */ 1914 public RestRequest queryData(String name, Object value) { 1915 queryData.append(createPart(QUERY, name, value)); 1916 return this; 1917 } 1918 1919 /** 1920 * Appends multiple query parameters to the request from properties defined on a Java bean. 1921 * 1922 * <h4 class='section'>Example:</h4> 1923 * <p class='bjava'> 1924 * <jk>public class</jk> MyQuery { 1925 * <jk>public</jk> String getFooBar() { <jk>return</jk> <js>"baz"</js>; } 1926 * <jk>public</jk> Integer getQux() { <jk>return</jk> 123; } 1927 * } 1928 * 1929 * <jc>// Appends query "fooBar=baz&qux=123".</jc> 1930 * <jv>client</jv> 1931 * .get(<jsf>URI</jsf>) 1932 * .queryDataBean(<jk>new</jk> MyQuery()) 1933 * .run(); 1934 * </p> 1935 * 1936 * @param value The bean containing the properties to set as query parameter values. 1937 * <br>Cannot be <jk>null</jk>. 1938 * @return This object. 1939 */ 1940 public RestRequest queryDataBean(Object value) { 1941 req(isBean(reqnn("value", value)), "Object passed into queryDataBean(Object) is not a bean."); 1942 var b = queryData; 1943 toBeanMap(value).forEach((k, v) -> b.append(createPart(QUERY, k, v))); 1944 return this; 1945 } 1946 1947 /** 1948 * Adds query parameters to the URI query using free-form key/value pairs.. 1949 * 1950 * <h4 class='section'>Example:</h4> 1951 * <p class='bjava'> 1952 * <jc>// Adds query parameters "foo=bar&baz=qux".</jc> 1953 * <jv>client</jv> 1954 * .get(<jsf>URI</jsf>) 1955 * .queryDataPairs(<js>"foo"</js>,<js>"bar"</js>,<js>"baz"</js>,<js>"qux"</js>) 1956 * .run(); 1957 * </p> 1958 * 1959 * @param pairs The query key/value pairs. 1960 * <ul> 1961 * <li>Values can be any POJO. 1962 * <li>Values converted to a string using the configured part serializer. 1963 * </ul> 1964 * <br>Cannot be <jk>null</jk>. 1965 * <br>Must have an even number of elements (key/value pairs). 1966 * <br>Null keys are ignored (parameter will not be created). 1967 * <br>Null values are allowed. 1968 * @return This object. 1969 * @throws RestCallException Invalid input. 1970 */ 1971 public RestRequest queryDataPairs(String...pairs) throws RestCallException { 1972 req(pairs.length % 2 == 0, "Odd number of parameters passed into queryDataPairs(String...)"); 1973 var b = queryData; 1974 for (var i = 0; i < pairs.length; i += 2) 1975 b.append(pairs[i], pairs[i + 1]); 1976 return this; 1977 } 1978 1979 /** 1980 * Removes a header from this message. 1981 * 1982 * @param header The header to remove. 1983 * <br>Can be <jk>null</jk> (no-op). 1984 */ 1985 @Override /* Overridden from HttpMessage */ 1986 public void removeHeader(Header header) { 1987 headerData.remove(header); 1988 } 1989 1990 /** 1991 * Removes all headers with a certain name from this message. 1992 * 1993 * @param name The name of the headers to remove. 1994 * <br>Cannot be <jk>null</jk>. 1995 */ 1996 @Override /* Overridden from HttpMessage */ 1997 public void removeHeaders(String name) { 1998 headerData.remove(name); 1999 } 2000 2001 /** 2002 * Rethrow any of the specified exception types if a matching <c>Exception-Name</c> header is found. 2003 * 2004 * <p> 2005 * Rethrown exceptions will be set on the caused-by exception of {@link RestCallException} when 2006 * thrown from the {@link #run()} method. 2007 * 2008 * <p> 2009 * Can be called multiple times to append multiple rethrows. 2010 * 2011 * @param values The classes to rethrow. 2012 * <br>Cannot be <jk>null</jk>. 2013 * <br>Null elements are ignored (only non-null classes that extend {@link Throwable} are added). 2014 * @return This object. 2015 */ 2016 public RestRequest rethrow(Class<?>...values) { 2017 if (rethrow == null) 2018 rethrow = list(); 2019 for (var v : values) { 2020 if (nn(v) && Throwable.class.isAssignableFrom(v)) 2021 rethrow.add((Class<? extends Throwable>)v); 2022 } 2023 return this; 2024 } 2025 2026 /** 2027 * Runs this request and returns the resulting response object. 2028 * 2029 * <h4 class='section'>Example:</h4> 2030 * <p class='bjava'> 2031 * <jk>try</jk> { 2032 * <jk>int</jk> <jv>rc</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).execute().getResponseStatus(); 2033 * <jc>// Succeeded!</jc> 2034 * } <jk>catch</jk> (RestCallException <jv>e</jv>) { 2035 * <jc>// Failed!</jc> 2036 * } 2037 * </p> 2038 * 2039 * <h4 class='section'>Notes:</h4><ul> 2040 * <li class='note'>Calling this method multiple times will return the same original response object. 2041 * <li class='note'>You must close the returned object if you do not consume the response or execute a method that consumes 2042 * the response. 2043 * <li class='note'>If you are only interested in the response code, use the {@link #complete()} method which will automatically 2044 * consume the response so that you don't need to call {@link InputStream#close()} on the response body. 2045 * </ul> 2046 * 2047 * @return The response object. 2048 * @throws RestCallException If an exception or non-200 response code occurred during the connection attempt. 2049 */ 2050 @SuppressWarnings({ 2051 "java:S3776", // Cognitive complexity acceptable for this specific logic 2052 "java:S6541", // Single-threaded context; synchronization unnecessary 2053 "null" // Null handling verified by context or framework 2054 }) 2055 public RestResponse run() throws RestCallException { 2056 if (nn(response)) 2057 throw new RestCallException(response, null, "run() already called."); 2058 2059 try { 2060 2061 queryData.stream().map(SimpleQuery::new).filter(SimplePart::isValid).forEach(x -> uriBuilder.addParameter(x.name, x.value)); 2062 2063 pathData.stream().map(SimplePath::new).forEach(x -> { 2064 var path = uriBuilder.getPath(); 2065 var name = x.name; 2066 var value = x.value; 2067 var pathVar = "{" + name + "}"; 2068 if (path.indexOf(pathVar) == -1 && neq(name, "/*")) 2069 throw isex("Path variable {%s} was not found in path.", name); 2070 var remainder = eq(name, "/*"); 2071 requireSafePathValue(name, value, remainder); 2072 if (remainder) 2073 path = path.replaceAll("\\/\\*$", Matcher.quoteReplacement(URI_PATH_SEPARATOR + value)); 2074 else 2075 path = path.replace(pathVar, String.valueOf(value)); 2076 uriBuilder.setPath(path); 2077 }); 2078 2079 HttpEntityEnclosingRequestBase request2 = request instanceof HttpEntityEnclosingRequestBase request3 ? request3 : null; 2080 request.setURI(uriBuilder.build()); 2081 2082 // Pick the serializer if it hasn't been overridden. 2083 var hl = headerData; 2084 var h = hl.getLast(HEADER_CONTENT_TYPE); 2085 var contentType = h.isPresent() ? h.get().getValue() : null; 2086 var serializer2 = this.serializer; 2087 if (serializer2 == null) 2088 serializer2 = client.getMatchingSerializer(contentType); 2089 if (contentType == null && nn(serializer2)) 2090 contentType = serializer2.getPrimaryMediaType().toString(); 2091 2092 // Pick the parser if it hasn't been overridden. 2093 h = hl.getLast(HEADER_ACCEPT); 2094 var accept = h.isPresent() ? h.get().getValue() : null; 2095 var parser2 = this.parser; 2096 if (parser2 == null) 2097 parser2 = client.getMatchingParser(accept); 2098 if (accept == null && nn(parser2)) 2099 hl.set(Accept.of(parser2.getPrimaryMediaType())); 2100 2101 headerData.stream().map(SimpleHeader::new).filter(SimplePart::isValid).forEach(request::addHeader); 2102 2103 if (request2 == null && content != NO_BODY) 2104 throw new RestCallException(null, null, "Method does not support content entity. Method=%s, URI=%s", getMethod(), getURI()); 2105 2106 if (nn(request2)) { 2107 2108 Object input2 = null; 2109 if (content != NO_BODY) { 2110 input2 = content; 2111 } else { 2112 input2 = new UrlEncodedFormEntity(formData.stream().map(SimpleFormData::new).filter(SimplePart::isValid).toList()); 2113 } 2114 2115 if (input2 instanceof Supplier<?> s) 2116 input2 = s.get(); 2117 2118 HttpEntity entity = null; 2119 if (input2 instanceof PartList input3) 2120 entity = new UrlEncodedFormEntity(input3.stream().map(SimpleFormData::new).filter(SimplePart::isValid).toList()); 2121 else if (input2 instanceof HttpResource input3) { 2122 input3.getHeaders().forEach(request::addHeader); 2123 entity = (HttpEntity)input2; 2124 } else if (input2 instanceof HttpEntity input3) { 2125 if (input3 instanceof SerializedEntity input4) { 2126 entity = input4.copyWith(serializer2, contentSchema); 2127 } else { 2128 entity = input3; 2129 } 2130 } else if (input2 instanceof Reader input3) 2131 entity = readerEntity(input3, getRequestContentType(TEXT_PLAIN)); 2132 else if (input2 instanceof InputStream input3) 2133 entity = streamEntity(input3, -1, getRequestContentType(ContentType.APPLICATION_OCTET_STREAM)); 2134 else if (input2 instanceof RecordStreamBody input3) 2135 entity = streamBodyEntity(input3, serializer2); 2136 else if (nn(serializer2)) 2137 entity = serializedEntity(input2, serializer2, contentSchema).setContentType(contentType); 2138 else { 2139 if (client.hasSerializers()) { 2140 if (contentType == null) 2141 throw new RestCallException(null, null, 2142 "Content-Type not specified on request. Cannot match correct serializer. Use contentType(String) or mediaType(String) to specify transport language."); 2143 throw new RestCallException(null, null, "No matching serializer for media type '%s'", contentType); 2144 } 2145 entity = stringEntity(input2 == null ? "" : MarshallingContext.DEFAULT.getClassMetaForObject(input2).toString(input2), getRequestContentType(TEXT_PLAIN)); 2146 } 2147 2148 request2.setEntity(entity); 2149 } 2150 2151 if (RemoteUrlPolicyState.isActive()) 2152 ssrfGuarded = true; 2153 var httpResponse = ssrfGuarded ? runWithPolicyRedirects() : runOnce(); 2154 response = client.createResponse(this, httpResponse, parser2); 2155 2156 if (isDebug() || client.logRequests == DetailLevel.FULL) 2157 response.cacheContent(); 2158 2159 for (var rci : interceptors) 2160 rci.onConnect(this, response); 2161 client.onCallConnect(this, response); 2162 2163 var method = getMethod(); 2164 var sc = response.getStatusCode(); 2165 2166 var thrown = response.getHeader("Thrown").asHeader(Thrown.class); 2167 if (thrown.isPresent() && nn(rethrow)) { 2168 var partsOpt = thrown.asParts(); 2169 if (!partsOpt.isPresent() || partsOpt.get().isEmpty()) 2170 return response; 2171 var thrownPart = partsOpt.get().get(0); 2172 var className = thrownPart.getClassName(); 2173 var message = thrownPart.getMessage(); 2174 for (var t : rethrow) { 2175 if (t.getName().equals(className)) { 2176 ConstructorInfo c = null; 2177 var ci = ClassInfo.of(t); 2178 Throwable thrownInstance = null; 2179 c = ci.getPublicConstructor(x -> x.hasParameterTypes(HttpResponse.class)).orElse(null); 2180 if (nn(c)) 2181 thrownInstance = newThrownFromResponse(c); 2182 if (thrownInstance == null) { 2183 c = ci.getPublicConstructor(x -> x.hasParameterTypes(String.class)).orElse(null); 2184 if (nn(c)) { 2185 thrownInstance = c.<Throwable>newInstance(nn(message) ? message : response.getContent().asString()); 2186 } else { 2187 c = ci.getPublicConstructor(x -> x.hasParameterTypes(String.class, Throwable.class)).orElse(null); 2188 if (nn(c)) { 2189 thrownInstance = c.<Throwable>newInstance(nn(message) ? message : response.getContent().asString(), null); 2190 } else { 2191 c = ci.getPublicConstructor(cons -> cons.getParameterCount() == 0).orElse(null); 2192 if (nn(c)) { 2193 thrownInstance = c.<Throwable>newInstance(); 2194 } 2195 } 2196 } 2197 } 2198 if (nn(thrownInstance)) { 2199 if (thrownInstance instanceof Exception thrownInstance2) 2200 throw thrownInstance2; 2201 throw new RestCallException(response, thrownInstance, "Server threw non-Exception: %s", className); 2202 } 2203 } 2204 } 2205 } 2206 2207 if (errorCodes.test(sc) && ! ignoreErrors) { 2208 // Surface the server-reported exception detail from the Thrown header (authoritative and independent of the response body) so callers still see the original failure detail. 2209 throw new RestCallException(response, null, "HTTP method '%s' call to '%s' caused response code '%s, %s'.\nResponse: \n%s%s", method, getURI(), sc, response.getReasonPhrase(), 2210 response.getContent().asAbbreviatedString(1000), getThrownDetailSuffix(thrown)); 2211 } 2212 2213 } catch (RuntimeException | RestCallException e) { 2214 if (nn(response)) 2215 response.close(); 2216 throw e; 2217 } catch (Exception e) { 2218 if (nn(response)) 2219 response.close(); 2220 throw new RestCallException(response, e, "Call failed."); 2221 } 2222 2223 return this.response; 2224 } 2225 2226 // ----------------------------------------------------------------------------------------------------------------- 2227 // SSRF-guard redirect revalidation (active only for a guarded request -- see SsrfGuardMarker) 2228 // ----------------------------------------------------------------------------------------------------------------- 2229 2230 // Marks this as the request of an SSRF-guard-active @Remote call. 2231 void ssrfGuard() { 2232 ssrfGuarded = true; 2233 } 2234 2235 // Whether this is the request of an SSRF-guard-active @Remote call. 2236 boolean isSsrfGuarded() { return ssrfGuarded; } 2237 2238 /** 2239 * Runs this request with Apache HttpClient's own automatic redirect-following disabled (see 2240 * {@code PolicyAwareRedirectStrategy}) and instead follows {@code 3xx} hops in a Juneau-controlled loop that 2241 * re-validates the {@code Location} of every hop against {@link RemoteUrlPolicy} — and, since every hop is 2242 * sent with the {@code SsrfGuardMarker} on its context, every hop leases its connection from the client's dedicated 2243 * pinned pool ({@code SsrfGuardConnectionManager}), which pin-on-connects each hop's resolved address and never hands 2244 * out a connection an ordinary request opened, on whichever thread the client runs it. Only called for a guarded 2245 * request, i.e. for a {@code @Remote} call with the SSRF guard in effect. 2246 */ 2247 private HttpResponse runWithPolicyRedirects() throws IOException { 2248 // A context set with context(...) carries the marker, and the redirect credential guard's origin, for the call only. 2249 var previousMarker = nn(context) ? SsrfGuardMarker.mark(context) : null; 2250 var previousOrigin = nn(context) ? ClassicRedirectCredentialGuard.origin(context) : null; 2251 try { 2252 return runWithPolicyRedirects2(); 2253 } finally { 2254 if (nn(context)) { 2255 context.setAttribute(SsrfGuardMarker.ATTRIBUTE, previousMarker); 2256 ClassicRedirectCredentialGuard.origin(context, previousOrigin); 2257 } 2258 } 2259 } 2260 2261 // A context(...) setting can be reused across calls to different hosts: each call compares redirects with its own first 2262 // origin, and leaves the context's recorded origin as it found it. 2263 private HttpResponse runOnce() throws IOException { 2264 if (context == null) 2265 return client.run(target, request, context); 2266 var previousOrigin = ClassicRedirectCredentialGuard.origin(context); 2267 ClassicRedirectCredentialGuard.origin(context, null); 2268 try { 2269 return client.run(target, request, context); 2270 } finally { 2271 ClassicRedirectCredentialGuard.origin(context, previousOrigin); 2272 } 2273 } 2274 2275 private HttpResponse runWithPolicyRedirects2() throws IOException { 2276 var currentTarget = target; 2277 HttpRequestBase currentRequest = request; 2278 URI firstOrigin = null; 2279 for (var hop = 0; hop < RemoteUrlPolicy.MAX_REDIRECT_HOPS; hop++) { 2280 // Hop 0's URI was already validated (or is the operator-configured client root, which the resolution 2281 // path intentionally does not re-check -- see RemoteUrlPolicy.requireAllowedUrl) before this request 2282 // was built; only a redirect Location -- a URL discovered at runtime -- needs a fresh pre-check here. 2283 if (hop > 0) 2284 requirePolicyAllowed(currentRequest.getURI()); 2285 // Without a context(...) setting each hop gets a fresh context, as Apache HttpClient gives one to a request 2286 // sent with none: sharing one would carry the authentication state of a hop to the next host. 2287 var hopContext = context; 2288 if (hopContext == null) { 2289 hopContext = new BasicHttpContext(); 2290 SsrfGuardMarker.mark(hopContext); 2291 } 2292 // The redirect credential guard compares every hop with the first hop's origin, as it does on the one context 2293 // of a redirect Apache HttpClient follows itself, and strips what the client's interceptors and default headers 2294 // add on another origin. On hop 0 this clears an origin an earlier call left on a context(...) setting. 2295 ClassicRedirectCredentialGuard.origin(hopContext, firstOrigin); 2296 var httpResponse = client.run(currentTarget, currentRequest, hopContext); 2297 if (hop == 0) 2298 firstOrigin = ClassicRedirectCredentialGuard.origin(hopContext); 2299 var sc = httpResponse.getStatusLine().getStatusCode(); 2300 if (! isRedirectStatus(sc)) 2301 return httpResponse; 2302 var locationHeader = httpResponse.getFirstHeader("Location"); 2303 EntityUtils.consumeQuietly(httpResponse.getEntity()); 2304 if (locationHeader == null) 2305 throw new ClientProtocolException("Redirect response (status " + sc + ") is missing a Location header"); 2306 URI target2; 2307 try { 2308 target2 = RemoteUrlPolicy.resolveRedirectLocation(currentRequest.getURI(), locationHeader.getValue()); 2309 } catch (IllegalArgumentException e) { 2310 throw new ClientProtocolException(e.getMessage(), e); 2311 } 2312 // On a context(...) setting shared by all hops, the authentication state of the target is reset on a hop to 2313 // another origin, as Apache HttpClient's own redirect handling resets it on a change of host: otherwise the 2314 // credentials that answered one host's challenge are sent unasked to the next. The credentials provider is 2315 // still asked per AuthScope, and the auth cache is keyed by host, so neither carries them across. 2316 if (nn(context) && crossesOrigin(currentRequest.getURI(), target2)) 2317 resetTargetAuthState(context); 2318 currentRequest = buildRedirectRequest(currentRequest, target2, sc); 2319 currentTarget = null; // Recomputed by the connection route planner from the request's own absolute URI. 2320 } 2321 throw new ClientProtocolException("Redirect limit exceeded (" + RemoteUrlPolicy.MAX_REDIRECT_HOPS 2322 + " hops) while following a policy-covered @Remote redirect chain, starting at: " + request.getURI()); 2323 } 2324 2325 private void requirePolicyAllowed(URI uri) throws ClientProtocolException { 2326 try { 2327 RemoteUrlPolicy.requireAllowedUrl(uri.toString(), false, client.getAllowedAddressRanges()); 2328 } catch (IllegalArgumentException e) { 2329 throw new ClientProtocolException(e.getMessage(), e); 2330 } 2331 } 2332 2333 private static boolean isRedirectStatus(int statusCode) { 2334 return statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307 || statusCode == 308; 2335 } 2336 2337 /** 2338 * Constructs the server-thrown exception through its {@code (HttpResponse)} constructor. 2339 * 2340 * @param c The constructor. 2341 * @return The instance, or <jk>null</jk> if the constructor rejected the response's status code. 2342 */ 2343 private Throwable newThrownFromResponse(ConstructorInfo c) { 2344 try { 2345 return c.<Throwable>newInstance(response); 2346 } catch (ExecutableException e) { 2347 // Only a status-code rejection (IllegalArgumentException from the Xxx(HttpResponse) status check) falls through to the remaining constructors; anything else propagates unchanged. 2348 if (! (e.getCause() instanceof IllegalArgumentException)) 2349 throw e; 2350 return null; 2351 } 2352 } 2353 2354 /** 2355 * Builds the request for the next hop of a policy-covered redirect chain, following conventional {@code 3xx} 2356 * semantics: {@code 301}/{@code 302}/{@code 303} rewrite the method to {@code GET} with no body unless the 2357 * original method was already {@code GET}/{@code HEAD}; {@code 307}/{@code 308} preserve the original method 2358 * and entity. A non-{@linkplain HttpEntity#isRepeatable() repeatable} entity cannot be safely re-sent, so such a 2359 * redirect is refused (fail closed) rather than risking a corrupt or partial replay. 2360 * 2361 * <p> 2362 * A hop to another origin (or an {@code https}→{@code http} downgrade) drops the caller-set credential headers 2363 * ({@link RedirectSecurity#stripOnCrossOrigin()}), as {@code ClassicRedirectCredentialGuard} does for a redirect 2364 * Apache HttpClient follows itself: that guard keys the first origin on the context, and here each hop may have a 2365 * context of its own. Once dropped they stay dropped, even if a later hop comes back to the first origin. 2366 */ 2367 private HttpRequestBase buildRedirectRequest(HttpRequestBase current, URI target2, int statusCode) throws ClientProtocolException { 2368 var method = current.getMethod(); 2369 var preserveMethod = eqic(method, "GET") || eqic(method, "HEAD"); 2370 var rewriteToGet = ! preserveMethod && (statusCode == 301 || statusCode == 302 || statusCode == 303); 2371 var entity = (! rewriteToGet && current instanceof HttpEntityEnclosingRequestBase e) ? e.getEntity() : null; 2372 2373 HttpRequestBase next; 2374 if (entity != null) { 2375 if (! entity.isRepeatable()) 2376 throw new ClientProtocolException("Redirect (status " + statusCode + ") requires re-sending a " 2377 + "non-repeatable request body, which cannot be safely replayed; refusing to follow (fail " 2378 + "closed) for a policy-covered @Remote redirect chain: " + target2); 2379 var next2 = new BasicHttpEntityRequestBase(this, method); 2380 next2.setEntity(entity); 2381 next = next2; 2382 } else { 2383 next = new BasicHttpRequestBase(this, rewriteToGet ? "GET" : method); 2384 } 2385 next.setURI(target2); 2386 var strip = crossesOrigin(current.getURI(), target2); 2387 for (var h : current.getAllHeaders()) 2388 if (! (rewriteToGet && (eqic(h.getName(), "Content-Length") || eqic(h.getName(), HEADER_CONTENT_TYPE))) && ! (strip && isCredentialHeader(h.getName()))) 2389 next.addHeader(h); 2390 return next; 2391 } 2392 2393 // Whether a hop from one URI to the other leaves the origin, or cannot be told not to (either is not absolute). 2394 private static boolean crossesOrigin(URI from, URI to) { 2395 return from.getScheme() == null || from.getHost() == null || to.getScheme() == null || to.getHost() == null 2396 || RedirectSecurity.shouldStripCredentials(from, to); 2397 } 2398 2399 // The shared RedirectSecurity set, plus Proxy-Authorization whatever that set holds: a guarded call never goes 2400 // through a proxy (one is refused), so on any hop it could only be a credential sent to the target itself. 2401 // Defense in depth: the shared set holds Proxy-Authorization today, so no test can tell this pin from it. 2402 // A path variable fills one path segment (or, for the remainder form, a run of segments): dot segments, and a '/' 2403 // inside a single-segment value, would change which resource the call addresses. Query/fragment characters, '\\' and '%' are 2404 // percent-encoded when the URI is built. 2405 private static void requireSafePathValue(String name, Object value, boolean remainder) { 2406 var v = String.valueOf(value); 2407 if (! remainder && (v.indexOf('/') >= 0)) 2408 throw iaex("Path variable {%s} must not contain '/'.", name); 2409 for (var seg : v.split("/", -1)) 2410 if (eq(seg, ".") || eq(seg, "..")) 2411 throw iaex("Path variable {%s} must not contain a '.' or '..' segment.", name); 2412 } 2413 2414 private static boolean isCredentialHeader(String name) { 2415 return eqic(name, "Proxy-Authorization") || RedirectSecurity.mustStrip(name, null); 2416 } 2417 2418 private static void resetTargetAuthState(HttpContext context) { 2419 var state = HttpClientContext.adapt(context).getTargetAuthState(); 2420 if (nn(state)) 2421 state.reset(); 2422 } 2423 2424 /** 2425 * Returns a message suffix describing the first entry of the given {@link Thrown} header, if present and 2426 * non-blank, or an empty string otherwise. 2427 * 2428 * @param thrown The parsed {@code Thrown} response header. 2429 * @return A <js>"\nThrown: <className>: <message>"</js> suffix, or an empty string. 2430 */ 2431 private static String getThrownDetailSuffix(Thrown thrown) { 2432 if (thrown.isPresent()) { 2433 var partsOpt = thrown.asParts(); 2434 if (partsOpt.isPresent() && ! partsOpt.get().isEmpty()) { 2435 var part = partsOpt.get().get(0); 2436 if (inb(part.getClassName()) && inb(part.getMessage())) 2437 return "\nThrown: " + part.getClassName() + ": " + part.getMessage(); 2438 } 2439 } 2440 return ""; 2441 } 2442 2443 /** 2444 * Same as {@link #run()} but allows you to run the call asynchronously. 2445 * 2446 * <h4 class='section'>Example:</h4> 2447 * <p class='bjava'> 2448 * Future<RestResponse> <jv>future</jv> = <jv>client</jv>.get(<jsf>URI</jsf>).runFuture(); 2449 * 2450 * <jc>// Do some other stuff</jc> 2451 * 2452 * <jk>try</jk> { 2453 * String <jv>body</jv> = <jv>future</jv>.get().getContent().asString(); 2454 * <jc>// Succeeded!</jc> 2455 * } <jk>catch</jk> (RestCallException <jv>e</jv>) { 2456 * <jc>// Failed!</jc> 2457 * } 2458 * </p> 2459 * 2460 * <h4 class='section'>Notes:</h4><ul> 2461 * <li class='note'>Use the {@link RestClient.Builder#executorService(ExecutorService, boolean)} method to customize the 2462 * executor service used for creating {@link Future Futures}. 2463 * </ul> 2464 * 2465 * @return The HTTP status code. 2466 * @throws RestCallException If the executor service was not defined. 2467 */ 2468 public Future<RestResponse> runFuture() throws RestCallException { 2469 return client.getExecutorService().submit(this::run); 2470 } 2471 2472 /** 2473 * Specifies the serializer to use on the request body. 2474 * 2475 * <p> 2476 * Overrides the serializers specified on the {@link RestClient}. 2477 * 2478 * <p> 2479 * The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 2480 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 2481 * 2482 * <p> 2483 * If the <c>Content-Type</c> header is not set on the request, it will be set to the media type of this serializer. 2484 * 2485 * @param serializer The serializer used to serialize POJOs to the body of the HTTP request. 2486 * <br>Can be <jk>null</jk> (will use default serializer matching Content-Type). 2487 * @return This object. 2488 */ 2489 public RestRequest serializer(Class<? extends Serializer> serializer) { 2490 this.serializer = serializer == null ? null : client.getInstance(serializer); 2491 return this; 2492 } 2493 2494 /** 2495 * Specifies the serializer to use on the request body. 2496 * 2497 * <p> 2498 * Overrides the serializers specified on the {@link RestClient}. 2499 * 2500 * <p> 2501 * The serializer is not modified by an of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 2502 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 2503 * 2504 * <p> 2505 * If the <c>Content-Type</c> header is not set on the request, it will be set to the media type of this serializer. 2506 * 2507 * @param serializer The serializer used to serialize POJOs to the body of the HTTP request. 2508 * <br>Can be <jk>null</jk> (will use default serializer matching Content-Type). 2509 * @return This object. 2510 */ 2511 public RestRequest serializer(Serializer serializer) { 2512 this.serializer = serializer; 2513 return this; 2514 } 2515 2516 /** 2517 * Overwrites the first header with the same name. 2518 * 2519 * The new header will be appended to the end of the list, if no header with the given name can be found. 2520 * 2521 * @param header The header to set. 2522 * <br>Can be <jk>null</jk> (ignored). 2523 */ 2524 @Override /* Overridden from HttpMessage */ 2525 public void setHeader(Header header) { 2526 headerData.set(header); 2527 } 2528 2529 /** 2530 * Overwrites the first header with the same name. 2531 * 2532 * The new header will be appended to the end of the list, if no header with the given name can be found. 2533 * 2534 * @param name The name of the header. 2535 * <br>Cannot be <jk>null</jk> or empty (header will not be created). 2536 * @param value The value of the header. 2537 * <br>Can be <jk>null</jk>. 2538 */ 2539 @Override /* Overridden from HttpMessage */ 2540 public void setHeader(String name, String value) { 2541 headerData.set(stringHeader(name, value)); 2542 } 2543 2544 /** 2545 * Overwrites all the headers in the message. 2546 * 2547 * @param headers The array of headers to set. 2548 * <br>Can be <jk>null</jk> (all headers will be cleared). 2549 * <br>Can contain <jk>null</jk> values (ignored). 2550 */ 2551 @Override /* Overridden from HttpMessage */ 2552 public void setHeaders(Header[] headers) { 2553 headerData.set(headers); 2554 } 2555 2556 /** 2557 * Provides parameters to be used for the processing of this message. 2558 * 2559 * @param params The parameters. 2560 * <br>Can be <jk>null</jk> (default parameters will be used). 2561 * @deprecated Use constructor parameters of configuration API provided by HttpClient. 2562 */ 2563 @Override /* Overridden from HttpMessage */ 2564 @Deprecated(since = "10.0", forRemoval = true) 2565 public void setParams(HttpParams params) { 2566 request.setParams(params); 2567 } 2568 2569 /** 2570 * Causes logging to be suppressed for the duration of this request. 2571 * 2572 * <p> 2573 * Overrides the {@link #debug()} setting on this request or client. 2574 * 2575 * @return This object. 2576 */ 2577 public RestRequest suppressLogging() { 2578 this.suppressLogging = true; 2579 return this; 2580 } 2581 2582 /** 2583 * Specifies the target host for the request. 2584 * 2585 * @param target The target host for the request. 2586 * Implementations may accept <jk>null</jk> if they can still determine a route, for example to a default 2587 * target or by inspecting the request. 2588 * @return This object. 2589 */ 2590 public RestRequest target(HttpHost target) { 2591 this.target = target; 2592 return this; 2593 } 2594 2595 /** 2596 * Convenience method for specifying UON as the marshalling transmission media type for this request only. 2597 * 2598 * <p> 2599 * UON is Url-Encoding Object notation that is equivalent to JSON but suitable for transmission as URL-encoded 2600 * query and form post values. 2601 * 2602 * <p> 2603 * {@link UonSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 2604 * <ul> 2605 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 2606 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 2607 * </ul> 2608 * <p> 2609 * {@link UonParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 2610 * <ul> 2611 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 2612 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 2613 * </ul> 2614 * <p> 2615 * <c>Accept</c> request header will be set to <js>"text/uon"</js> unless overridden 2616 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 2617 * <p> 2618 * <c>Content-Type</c> request header will be set to <js>"text/uon"</js> unless overridden 2619 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 2620 * <p> 2621 * Identical to calling <c>serializer(UonSerializer.<jk>class</jk>).parser(UonParser.<jk>class</jk>)</c>. 2622 * 2623 * @return This object. 2624 */ 2625 public RestRequest uon() { 2626 return serializer(UonSerializer.class).parser(UonParser.class); 2627 } 2628 2629 /** 2630 * Sets the URI for this request. 2631 * 2632 * <p> 2633 * Can be any of the following types: 2634 * <ul> 2635 * <li>{@link URI} 2636 * <li>{@link URL} 2637 * <li>{@link URIBuilder} 2638 * <li>Anything else converted to a string using {@link Object#toString()}. 2639 * </ul> 2640 * 2641 * <p> 2642 * Relative URI strings will be interpreted as relative to the root URI defined on the client. 2643 * 2644 * @param uri 2645 * The URI of the remote REST resource. 2646 * <br>This overrides the URI passed in from the client. 2647 * <br>Can be any of the following types: 2648 * <ul> 2649 * <li>{@link URIBuilder} 2650 * <li>{@link URI} 2651 * <li>{@link URL} 2652 * <li>{@link String} 2653 * <li>{@link Object} - Converted to <c>String</c> using <c>toString()</c> 2654 * </ul> 2655 * <br>Cannot be <jk>null</jk>. 2656 * @return This object. 2657 * @throws RestCallException Invalid URI syntax detected. 2658 */ 2659 public RestRequest uri(Object uri) throws RestCallException { 2660 var x = client.toUri(uri, null); 2661 if (nn(x.getScheme())) 2662 uriBuilder.setScheme(x.getScheme()); 2663 if (nn(x.getHost())) 2664 uriBuilder.setHost(x.getHost()); 2665 if (x.getPort() != -1) 2666 uriBuilder.setPort(x.getPort()); 2667 if (nn(x.getUserInfo())) 2668 uriBuilder.setUserInfo(x.getUserInfo()); 2669 if (nn(x.getFragment())) 2670 uriBuilder.setFragment(x.getFragment()); 2671 if (nn(x.getQuery())) 2672 uriBuilder.setCustomQuery(x.getQuery()); 2673 uriBuilder.setPath(x.getPath()); 2674 return this; 2675 } 2676 2677 /** 2678 * Sets the URI fragment. 2679 * 2680 * @param fragment The URI fragment. The value is expected to be unescaped and may contain non ASCII characters. 2681 * <br>Can be <jk>null</jk> (fragment will be cleared). 2682 * @return This object. 2683 */ 2684 public RestRequest uriFragment(String fragment) { 2685 uriBuilder.setFragment(fragment); 2686 return this; 2687 } 2688 2689 /** 2690 * Sets the URI host. 2691 * 2692 * @param host The new URI host. 2693 * <br>Can be <jk>null</jk> (host will be cleared). 2694 * @return This object. 2695 */ 2696 public RestRequest uriHost(String host) { 2697 uriBuilder.setHost(host); 2698 return this; 2699 } 2700 2701 /** 2702 * Sets the URI port. 2703 * 2704 * @param port The new URI port. 2705 * @return This object. 2706 */ 2707 public RestRequest uriPort(int port) { 2708 uriBuilder.setPort(port); 2709 return this; 2710 } 2711 2712 /** 2713 * Sets the URI scheme. 2714 * 2715 * @param scheme The new URI scheme. 2716 * <br>Can be <jk>null</jk> (scheme will be cleared). 2717 * @return This object. 2718 */ 2719 public RestRequest uriScheme(String scheme) { 2720 uriBuilder.setScheme(scheme); 2721 return this; 2722 } 2723 2724 /** 2725 * Sets the URI user info. 2726 * 2727 * @param userInfo The new URI user info. 2728 * <br>Can be <jk>null</jk> (user info will be cleared). 2729 * @return This object. 2730 */ 2731 public RestRequest uriUserInfo(String userInfo) { 2732 uriBuilder.setUserInfo(userInfo); 2733 return this; 2734 } 2735 2736 /** 2737 * Sets the URI user info. 2738 * 2739 * @param username The new URI username. 2740 * <br>Can be <jk>null</jk>. 2741 * @param password The new URI password. 2742 * <br>Can be <jk>null</jk>. 2743 * @return This object. 2744 */ 2745 public RestRequest uriUserInfo(String username, String password) { 2746 uriBuilder.setUserInfo(username, password); 2747 return this; 2748 } 2749 2750 /** 2751 * Convenience method for specifying URL-Encoding as the marshalling transmission media type for this request only. 2752 * 2753 * <p> 2754 * {@link UrlEncodingSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 2755 * <ul> 2756 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 2757 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 2758 * <li>This serializer is NOT used when using the {@link RestRequest#formData(String, Object)} (and related) methods for constructing 2759 * the request body. Instead, the part serializer specified via {@link RestClient.Builder#partSerializer(Class)} is used. 2760 * </ul> 2761 * <p> 2762 * {@link UrlEncodingParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 2763 * <ul> 2764 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 2765 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 2766 * </ul> 2767 * <p> 2768 * <c>Accept</c> request header will be set to <js>"application/x-www-form-urlencoded"</js> unless overridden 2769 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 2770 * <p> 2771 * <c>Content-Type</c> request header will be set to <js>"application/x-www-form-urlencoded"</js> unless overridden 2772 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 2773 * <p> 2774 * Identical to calling <c>serializer(UrlEncodingSerializer.<jk>class</jk>).parser(UrlEncodingParser.<jk>class</jk>)</c>. 2775 * 2776 * @return This object. 2777 */ 2778 public RestRequest urlEnc() { 2779 return serializer(UrlEncodingSerializer.class).parser(UrlEncodingParser.class); 2780 } 2781 2782 /** 2783 * Convenience method for specifying XML as the marshalling transmission media type for this request only. 2784 * 2785 * <p> 2786 * {@link XmlSerializer} will be used to serialize POJOs to request bodies unless overridden per request via {@link RestRequest#serializer(Serializer)}. 2787 * <ul> 2788 * <li>The serializer can be configured using any of the serializer property setters (e.g. {@link RestClient.Builder#sortCollections()}) or 2789 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 2790 * </ul> 2791 * <p> 2792 * {@link XmlParser} will be used to parse POJOs from response bodies unless overridden per request via {@link RestRequest#parser(Parser)}. 2793 * <ul> 2794 * <li>The parser can be configured using any of the parser property setters (e.g. {@link RestClient.Builder#ignoreUnknownBeanProperties()}) or 2795 * bean context property setters (e.g. {@link RestClient.Builder#swaps(Class...)}) defined on this builder class. 2796 * </ul> 2797 * <p> 2798 * <c>Accept</c> request header will be set to <js>"text/xml"</js> unless overridden 2799 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#accept(String)}. 2800 * <p> 2801 * <c>Content-Type</c> request header will be set to <js>"text/xml"</js> unless overridden 2802 * by {@link RestRequest#header(String,Object)} or {@link RestRequest#contentType(String)}. 2803 * <p> 2804 * Identical to calling <c>serializer(XmlSerializer.<jk>class</jk>).parser(XmlParser.<jk>class</jk>)</c>. 2805 * 2806 * @return This object. 2807 */ 2808 public RestRequest xml() { 2809 return serializer(XmlSerializer.class).parser(XmlParser.class); 2810 } 2811 2812 private Header createHeader(String name, Object value) { 2813 return createHeader(name, value, null, null, null); 2814 } 2815 2816 private NameValuePair createPart(HttpPartType type, String name, Object value) { 2817 return createPart(name, value, type, null, null, null); 2818 } 2819 2820 private HttpPartSerializerSession getPartSerializerSession(HttpPartSerializer serializer) { 2821 if (serializer == null) 2822 serializer = client.getPartSerializer(); 2823 return partSerializerSessions.computeIfAbsent(serializer, HttpPartSerializer::getPartSession); 2824 } 2825 2826 private ContentType getRequestContentType(ContentType def) { 2827 var h = request.getFirstHeader(HEADER_CONTENT_TYPE); 2828 if (nn(h)) { 2829 var s = h.getValue(); 2830 if (ine(s)) 2831 return ContentType.of(s); 2832 } 2833 return def; 2834 } 2835 2836 /** 2837 * Creates a new header. 2838 * 2839 * @param name The header name. 2840 * @param value The header value. 2841 * @param serializer The part serializer to use, or <jk>null</jk> to use the part serializer defined on the client. 2842 * @param schema Optional HTTP part schema to provide to the part serializer. 2843 * @param skipIfEmpty If <jk>true</jk>, empty string values will be ignored on the request. 2844 * @return A new header. 2845 */ 2846 protected Header createHeader(String name, Object value, HttpPartSerializer serializer, HttpPartSchema schema, Boolean skipIfEmpty) { 2847 if (ie(name)) 2848 return null; 2849 if (skipIfEmpty == null) 2850 skipIfEmpty = client.isSkipEmptyHeaderData(); 2851 if (serializer == null) 2852 serializer = client.getPartSerializer(); 2853 return new SerializedHeader(name, value, getPartSerializerSession(serializer), schema, skipIfEmpty); 2854 } 2855 2856 /** 2857 * Constructs the {@link HttpRequestBase} object that ends up being passed to the client execute method. 2858 * 2859 * <p> 2860 * Subclasses can override this method to create their own request base objects. 2861 * 2862 * @param method The HTTP method. 2863 * @param uri The HTTP URI. 2864 * @param hasBody Whether the HTTP request has a body. 2865 * @return A new {@link HttpRequestBase} object. 2866 */ 2867 protected HttpRequestBase createInnerRequest(String method, URI uri, boolean hasBody) { 2868 var req = hasBody ? new BasicHttpEntityRequestBase(this, method) : new BasicHttpRequestBase(this, method); 2869 req.setURI(uri); 2870 return req; 2871 } 2872 2873 /** 2874 * Creates a new query/form-data/path part. 2875 * 2876 * @param name The part name. 2877 * @param value The part value. 2878 * @param type The HTTP part type. 2879 * @param serializer The part serializer to use, or <jk>null</jk> to use the part serializer defined on the client. 2880 * @param schema Optional HTTP part schema to provide to the part serializer. 2881 * @param skipIfEmpty If <jk>true</jk>, empty string values will be ignored on the request. 2882 * @return A new part. 2883 */ 2884 protected NameValuePair createPart(String name, Object value, HttpPartType type, HttpPartSerializer serializer, HttpPartSchema schema, Boolean skipIfEmpty) { 2885 if (ie(name)) 2886 return null; 2887 if (skipIfEmpty == null) { 2888 if (type == QUERY) 2889 skipIfEmpty = client.isSkipEmptyQueryData(); 2890 else if (type == FORMDATA) 2891 skipIfEmpty = client.isSkipEmptyFormData(); 2892 else 2893 skipIfEmpty = false; 2894 } 2895 if (serializer == null) 2896 serializer = client.getPartSerializer(); 2897 return new SerializedPart(name, value, type, getPartSerializerSession(serializer), schema, skipIfEmpty); 2898 } 2899 2900 @Override /* Overridden from MarshallingSession */ 2901 protected FluentMap<String,Object> properties() { 2902 return super.properties() 2903 .a("client", client.properties()) 2904 .a("ignoreErrors", ignoreErrors) 2905 .a("interceptors", interceptors) 2906 .a("requestBodySchema", contentSchema) 2907 .a("response", response) 2908 .a("serializer", serializer); 2909 } 2910 2911 RestRequest formDataArg(String name, Object value, HttpPartSchema schema, HttpPartSerializer serializer, boolean skipIfEmpty) { 2912 var isMulti = ie(name) || eq(name, "*") || value instanceof PartList || isNameValuePairArray(value); 2913 2914 if (! isMulti) { 2915 if (! (skipIfEmpty && ie(s(value)))) 2916 return formData(createPart(name, value, FORMDATA, serializer, schema, skipIfEmpty)); 2917 return this; 2918 } 2919 2920 List<NameValuePair> l = list(); 2921 2922 if (HttpParts.canCast(value)) { 2923 l.add(HttpParts.cast(value)); 2924 } else if (value instanceof PartList value2) { 2925 value2.forEach(l::add); 2926 } else if (value instanceof Collection<?> value3) { 2927 value3.forEach(x -> l.add(HttpParts.cast(x))); 2928 } else if (isArray(value)) { 2929 for (var i = 0; i < Array.getLength(value); i++) 2930 l.add(HttpParts.cast(Array.get(value, i))); 2931 } else if (value instanceof Map value2) { 2932 toMap(value2).forEach((k, v) -> l.add(createPart(s(k), v, FORMDATA, serializer, schema, skipIfEmpty))); 2933 } else if (isBean(value)) { 2934 toBeanMap(value).forEach((k, v) -> l.add(createPart(k, v, FORMDATA, serializer, schema, skipIfEmpty))); 2935 } else if (nn(value)) { 2936 formDataCustom(value); 2937 return this; 2938 } 2939 2940 if (skipIfEmpty) 2941 l.removeIf(x -> ie(x.getValue())); 2942 2943 formData.append(l); 2944 2945 return this; 2946 } 2947 2948 HttpPartSerializerSession getPartSerializerSession() { 2949 if (partSerializerSession == null) 2950 partSerializerSession = getPartSerializerSession(null); 2951 return partSerializerSession; 2952 } 2953 2954 RestRequest headerArg(String name, Object value, HttpPartSchema schema, HttpPartSerializer serializer, boolean skipIfEmpty) { 2955 var isMulti = ie(name) || eq(name, "*") || value instanceof HeaderList || isHeaderArray(value); 2956 2957 if (! isMulti) { 2958 if (! (skipIfEmpty && ie(s(value)))) 2959 return header(createHeader(name, value, serializer, schema, skipIfEmpty)); 2960 return this; 2961 } 2962 2963 List<Header> l = list(); 2964 2965 if (HttpHeaders.canCast(value)) { 2966 l.add(HttpHeaders.cast(value)); 2967 } else if (value instanceof HeaderList value2) { 2968 value2.forEach(l::add); 2969 } else if (value instanceof Collection<?> value3) { 2970 value3.forEach(x -> l.add(HttpHeaders.cast(x))); 2971 } else if (isArray(value)) { 2972 for (var i = 0; i < Array.getLength(value); i++) 2973 l.add(HttpHeaders.cast(Array.get(value, i))); 2974 } else if (value instanceof Map value2) { 2975 toMap(value2).forEach((k, v) -> l.add(createHeader(s(k), v, serializer, schema, skipIfEmpty))); 2976 } else if (isBean(value)) { 2977 toBeanMap(value).forEach((k, v) -> l.add(createHeader(k, v, serializer, schema, skipIfEmpty))); 2978 } else if (nn(value)) { 2979 throw rex("Invalid value type for header arg '%s': %s", name, cn(value)); 2980 } 2981 2982 if (skipIfEmpty) 2983 l.removeIf(x -> ie(x.getValue())); 2984 2985 headerData.append(l); 2986 2987 return this; 2988 } 2989 2990 boolean isLoggingSuppressed() { return suppressLogging; } 2991 2992 /** 2993 * Returns <jk>true</jk> if the request body can be safely re-sent (required for a gated automatic retry). 2994 * 2995 * <p> 2996 * A missing body is trivially repeatable; a streaming body ({@link InputStream}/{@link Reader}/record-stream) is 2997 * not; an {@link HttpEntity} body defers to {@link HttpEntity#isRepeatable()}; any other (buffered POJO/String) 2998 * body is repeatable. 2999 * 3000 * @return <jk>true</jk> if the body can be safely re-sent. 3001 */ 3002 boolean isBodyRepeatable() { 3003 var c = content; 3004 if (c == null || c == NO_BODY) 3005 return true; 3006 if (c instanceof InputStream || c instanceof Reader || c instanceof RecordStreamBody) 3007 return false; 3008 if (c instanceof HttpEntity e) 3009 return e.isRepeatable(); 3010 return true; 3011 } 3012 3013 RestRequest pathArg(String name, Object value, HttpPartSchema schema, HttpPartSerializer serializer) { 3014 var isMulti = ie(name) || eq(name, "*") || value instanceof PartList || isNameValuePairArray(value); 3015 3016 if (! isMulti) 3017 return pathData(createPart(name, value, PATH, serializer, schema, false)); 3018 3019 List<NameValuePair> l = list(); 3020 3021 if (HttpParts.canCast(value)) { 3022 l.add(HttpParts.cast(value)); 3023 } else if (value instanceof PartList value2) { 3024 value2.forEach(l::add); 3025 } else if (value instanceof Collection<?> value3) { 3026 value3.forEach(x -> l.add(HttpParts.cast(x))); 3027 } else if (isArray(value)) { 3028 for (var i = 0; i < Array.getLength(value); i++) 3029 l.add(HttpParts.cast(Array.get(value, i))); 3030 } else if (value instanceof Map value2) { 3031 toMap(value2).forEach((k, v) -> l.add(createPart(s(k), v, PATH, serializer, schema, false))); 3032 } else if (isBean(value)) { 3033 toBeanMap(value).forEach((k, v) -> l.add(createPart(k, v, PATH, serializer, schema, false))); 3034 } else if (nn(value)) { 3035 throw rex("Invalid value type for path arg '%s': %s", name, cn(value)); 3036 } 3037 3038 pathData.append(l); 3039 3040 return this; 3041 } 3042 3043 RestRequest queryArg(String name, Object value, HttpPartSchema schema, HttpPartSerializer serializer, boolean skipIfEmpty) { 3044 if (schema != null && schema.getCollectionFormat() == HttpPartCollectionFormat.MULTI) { 3045 if (value instanceof Collection<?> value2) { 3046 List<NameValuePair> l = list(); 3047 value2.forEach(x -> l.add(createPart(name, x, QUERY, serializer, schema, skipIfEmpty))); 3048 if (skipIfEmpty) 3049 l.removeIf(x -> ie(x.getValue())); 3050 queryData.append(l); 3051 return this; 3052 } 3053 if (isArray(value) && ! isNameValuePairArray(value)) { 3054 List<NameValuePair> l = list(); 3055 for (var i = 0; i < Array.getLength(value); i++) 3056 l.add(createPart(name, Array.get(value, i), QUERY, serializer, schema, skipIfEmpty)); 3057 if (skipIfEmpty) 3058 l.removeIf(x -> ie(x.getValue())); 3059 queryData.append(l); 3060 return this; 3061 } 3062 if (value instanceof Map<?,?> value2) { 3063 List<NameValuePair> l = list(); 3064 var sess = getPartSerializerSession(serializer); 3065 for (var e : value2.entrySet()) { 3066 try { 3067 var uon = sess.write(QUERY, schema, e.getValue()); 3068 l.add(BasicPart.of(name, s(e.getKey()) + "=" + (uon == null ? "" : uon))); 3069 } catch (SerializeException | SchemaValidationException ex) { 3070 throw rex(ex, "Serialization error on request query part '%s'", name); 3071 } 3072 } 3073 if (skipIfEmpty) 3074 l.removeIf(x -> ie(x.getValue())); 3075 queryData.append(l); 3076 return this; 3077 } 3078 } 3079 3080 var isMulti = ie(name) || eq(name, "*") || value instanceof PartList || isNameValuePairArray(value); 3081 3082 if (! isMulti) { 3083 if (! (skipIfEmpty && ie(s(value)))) 3084 return queryData(createPart(name, value, QUERY, serializer, schema, skipIfEmpty)); 3085 return this; 3086 } 3087 3088 List<NameValuePair> l = list(); 3089 3090 if (HttpParts.canCast(value)) { 3091 l.add(HttpParts.cast(value)); 3092 } else if (value instanceof PartList value2) { 3093 value2.forEach(l::add); 3094 } else if (value instanceof Collection<?> value3) { 3095 value3.forEach(x -> l.add(HttpParts.cast(x))); 3096 } else if (isArray(value)) { 3097 for (var i = 0; i < Array.getLength(value); i++) 3098 l.add(HttpParts.cast(Array.get(value, i))); 3099 } else if (value instanceof Map value2) { 3100 toMap(value2).forEach((k, v) -> l.add(createPart(s(k), v, QUERY, serializer, schema, skipIfEmpty))); 3101 } else if (isBean(value)) { 3102 toBeanMap(value).forEach((k, v) -> l.add(createPart(k, v, QUERY, serializer, schema, skipIfEmpty))); 3103 } else if (nn(value)) { 3104 queryCustom(value); 3105 return this; 3106 } 3107 3108 if (skipIfEmpty) 3109 l.removeIf(x -> ie(x.getValue())); 3110 3111 queryData.append(l); 3112 3113 return this; 3114 } 3115 3116 /** 3117 * Resolves a {@link RecordStreamBody} body by invoking the caller's consumer against a 3118 * cursor opened over a temporary buffer, then sending the buffered bytes as the request 3119 * body. 3120 */ 3121 private HttpEntity streamBodyEntity(RecordStreamBody body, Serializer serializer) { 3122 if (serializer == null) 3123 throw iaex("No serializer registered for cursor-streamed request body."); 3124 try { 3125 var consumer = body.getConsumer(); 3126 var writerKind = body.getWriterKind(); 3127 3128 if (writerKind == TokenWriter.class && !(serializer instanceof TokenWritable)) 3129 throw iaex("Serializer '%s' does not support the token-writer surface.", serializer.getClass().getName()); 3130 if (writerKind == RecordWriter.class && !(serializer instanceof RecordWritable)) 3131 throw iaex("Serializer '%s' does not support the record-writer surface.", serializer.getClass().getName()); 3132 3133 var buf = new ByteArrayOutputStream(); 3134 Object output = serializer.isWriterSerializer() 3135 ? new OutputStreamWriter(buf, java.nio.charset.StandardCharsets.UTF_8) 3136 : buf; 3137 3138 writeCursor(serializer, writerKind, consumer, output); 3139 3140 // Use the serializer's primary produces() media type if no explicit Content-Type set. 3141 var ct = serializer.getPrimaryMediaType(); 3142 var contentType2 = ct != null ? ContentType.of(ct.toString()) : ContentType.APPLICATION_OCTET_STREAM; 3143 return byteArrayEntity(buf.toByteArray(), getRequestContentType(contentType2)); 3144 } catch (IOException e) { 3145 throw rex(e, "I/O error streaming request body."); 3146 } 3147 } 3148 3149 @SuppressWarnings({ 3150 "rawtypes" // The body consumer's element type depends on the writer kind, so it is invoked through a raw Consumer. 3151 }) 3152 private static void writeCursor(Serializer serializer, Class<?> writerKind, Object consumer, Object output) throws IOException { 3153 try (var w = (writerKind == TokenWriter.class) 3154 ? ((TokenWritable) serializer).writeTokens(output) 3155 : ((RecordWritable) serializer).writeRecords(output)) { 3156 ((Consumer) consumer).accept(w); 3157 w.flush(); 3158 } 3159 } 3160}