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.server; 018 019import static java.time.format.DateTimeFormatter.*; 020import static java.time.temporal.ChronoUnit.*; 021import static org.apache.juneau.commons.httppart.HttpPartType.*; 022import static org.apache.juneau.commons.utils.Shorts.*; 023import static org.apache.juneau.commons.utils.StringUtils.*; 024 025import java.io.*; 026import java.nio.charset.*; 027import java.time.*; 028import java.util.*; 029import java.util.regex.*; 030 031import org.apache.juneau.commons.http.*; 032import org.apache.juneau.commons.httppart.*; 033import org.apache.juneau.http.*; 034import org.apache.juneau.http.header.*; 035import org.apache.juneau.http.response.*; 036import org.apache.juneau.httppart.bean.*; 037import org.apache.juneau.marshall.*; 038import org.apache.juneau.marshall.collections.*; 039import org.apache.juneau.marshall.encoders.*; 040import org.apache.juneau.marshall.httppart.*; 041import org.apache.juneau.marshall.marshaller.*; 042import org.apache.juneau.marshall.oapi.*; 043import org.apache.juneau.marshall.serializer.*; 044import org.apache.juneau.rest.server.httppart.*; 045import org.apache.juneau.rest.server.sse.*; 046import org.apache.juneau.rest.server.util.*; 047 048import jakarta.servlet.*; 049import jakarta.servlet.http.*; 050 051/** 052 * Represents an HTTP response for a REST resource. 053 * 054 * <p> 055 * The {@link RestResponse} object is an extension of the <l>HttpServletResponse</l> class 056 * with various built-in convenience methods for use in building REST interfaces. 057 * It can be accessed by passing it as a parameter on your REST Java method: 058 * </p> 059 * 060 * <p class='bjava'> 061 * <ja>@RestPost</ja>(...) 062 * <jk>public</jk> Object myMethod(RestResponse <jv>res</jv>) {...} 063 * </p> 064 * 065 * <p> 066 * The primary methods on this class are: 067 * </p> 068 * <ul class='javatree'> 069 * <li class='jc'>{@link RestResponse} 070 * <ul class='spaced-list'> 071 * <li>Methods for setting response headers: 072 * <ul class='javatreec'> 073 * <li class='jm'>{@link RestResponse#addHeader(HttpHeader) addHeader(HttpHeader)} 074 * <li class='jm'>{@link RestResponse#addHeader(String,String) addHeader(String,String)} 075 * <li class='jm'>{@link RestResponse#containsHeader(String) containsHeader(String)} 076 * <li class='jm'>{@link RestResponse#getHeader(String) getHeader(String)} 077 * <li class='jm'>{@link RestResponse#setCharacterEncoding(String) setCharacterEncoding(String)} 078 * <li class='jm'>{@link RestResponse#setContentType(String) setContentType(String)} 079 * <li class='jm'>{@link RestResponse#setHeader(HttpHeader) setHeader(HttpHeader)} 080 * <li class='jm'>{@link RestResponse#setHeader(HttpPartSchema,String,Object) setHeader(HttpPartSchema,String,Object)} 081 * <li class='jm'>{@link RestResponse#setHeader(String,Object) setHeader(String,Object)} 082 * <li class='jm'>{@link RestResponse#setHeader(String,String) setHeader(String,String)} 083 * <li class='jm'>{@link RestResponse#setMaxHeaderLength(int) setMaxHeaderLength(int)} 084 * <li class='jm'>{@link RestResponse#setSafeHeaders() setSafeHeaders()} 085 * <li class='jm'>{@link RestResponse#setUnsafeHeaders() setUnsafeHeaders()} 086 * <li class='jm'>{@link RestResponse#downloadAs(String) downloadAs(String)} 087 * <li class='jm'>{@link RestResponse#eTag(String) eTag(String)} 088 * <li class='jm'>{@link RestResponse#eTag(EntityTag) eTag(EntityTag)} 089 * <li class='jm'>{@link RestResponse#lastModified(Instant) lastModified(Instant)} 090 * <li class='jm'>{@link RestResponse#lastModified(ZonedDateTime) lastModified(ZonedDateTime)} 091 * <li class='jm'>{@link RestResponse#cacheControl(String) cacheControl(String)} 092 * <li class='jm'>{@link RestResponse#cacheControl(CacheControl.Builder) cacheControl(CacheControl.Builder)} 093 * </ul> 094 * <li>Methods for setting response bodies: 095 * <ul class='javatreec'> 096 * <li class='jm'>{@link RestResponse#flushBuffer() flushBuffer()} 097 * <li class='jm'>{@link RestResponse#getDirectWriter(String) getDirectWriter(String)} 098 * <li class='jm'>{@link RestResponse#getNegotiatedOutputStream() getNegotiatedOutputStream()} 099 * <li class='jm'>{@link RestResponse#getNegotiatedWriter() getNegotiatedWriter()} 100 * <li class='jm'>{@link RestResponse#getSerializerMatch() getSerializerMatch()} 101 * <li class='jm'>{@link RestResponse#getWriter() getWriter()} 102 * <li class='jm'>{@link RestResponse#sendPlainText(String) sendPlainText(String)} 103 * <li class='jm'>{@link RestResponse#sendRedirect(String) sendRedirect(String)} 104 * <li class='jm'>{@link RestResponse#sendSafeRedirect(String,String...) sendSafeRedirect(String,String...)} 105 * <li class='jm'>{@link RestResponse#setContentSchema(HttpPartSchema) setContentSchema(HttpPartSchema)} 106 * <li class='jm'>{@link RestResponse#setContent(Object) setContent(Object)} 107 * <li class='jm'>{@link RestResponse#setSerializer(Serializer) setSerializer(Serializer)} 108 * <li class='jm'>{@link RestResponse#setResponseBeanMeta(ResponseBeanMeta) setResponseBeanMeta(ResponseBeanMeta)} 109 * <li class='jm'>{@link RestResponse#setException(Throwable) setException(Throwable)} 110 * </ul> 111 * <li>Other: 112 * <ul class='javatreec'> 113 * <li class='jm'>{@link RestResponse#getAttributes() getAttributes()} 114 * <li class='jm'>{@link RestResponse#getContext() getContext()} 115 * <li class='jm'>{@link RestResponse#getOpContext() getOpContext()} 116 * <li class='jm'>{@link RestResponse#setAttribute(String,Object) setAttribute(String,Object)} 117 * <li class='jm'>{@link RestResponse#setNoTrace() setNoTrace()} 118 * <li class='jm'>{@link RestResponse#setStatus(int) setStatus(int)} 119 * </ul> 120 * </ul> 121 * </ul> 122 * 123 */ 124@SuppressWarnings({ 125 "java:S115", // Constants use UPPER_snakeCase convention (e.g., HEADER_ContentType) 126 "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants 127 "java:S2789", // The Optional content field is null until setContent() is called, and null (not Optional.empty()) means 'never set'; getRawOutput() null-checks it. 128 "java:S3776", // Mainly getNegotiatedOutputStream(), whose Accept-Encoding negotiation nests several conditions. 129 "resource" // HttpServletResponseWrapper is managed by servlet container 130}) 131public class RestResponse extends HttpServletResponseWrapper { 132 133 private static final String HEADER_ContentType = "Content-Type"; 134 135 /** Headers a client can never ask the server to set through the <c>x-response-headers</c> request header. */ 136 private static final Set<String> NEVER_PASS_THROUGH_HEADERS = Set.of("set-cookie", "location", "content-security-policy", "content-type"); 137 private static final Pattern ENCODING_DISABLED_PATTERN = Pattern.compile("(identity|\\*)\\s*;\\s*q\\s*=\\s*(0(?!\\.)|0\\.0)"); 138 139 private final HttpServletResponse inner; 140 private final RestRequest request; 141 142 private Optional<Object> content; // The POJO being sent to the output. 143 private ServletOutputStream sos; 144 private FinishableServletOutputStream os; 145 private FinishablePrintWriter w; 146 private ResponseBeanMeta responseBeanMeta; 147 private final RestOpContext opContext; 148 private Optional<HttpPartSchema> contentSchema; 149 private Serializer serializer; 150 private Optional<SerializerMatch> serializerMatch; 151 private boolean safeHeaders = true; 152 private int maxHeaderLength = 8096; 153 154 /** 155 * Constructor. 156 */ 157 @SuppressWarnings({ 158 "java:S112" // throws Exception intentional - callback/lifecycle method 159 }) 160 RestResponse(RestOpContext opContext, RestSession session, RestRequest req) throws Exception { 161 super(session.getResponse()); 162 163 inner = session.getResponse(); 164 request = req; 165 166 this.opContext = opContext; 167 responseBeanMeta = opContext.getResponseMeta(); 168 169 var context = session.getContext(); 170 171 try { 172 var passThroughHeaders = request.getHeaderParam("x-response-headers").orElse(null); 173 if (nn(passThroughHeaders)) { 174 var m = context.getPartParser().getPartSession().read(HEADER, null, passThroughHeaders, MarshallingContext.DEFAULT.getClassMeta(JsonMap.class)); 175 var allowed = context.getAllowedResponseHeaders(); 176 for (var e : m.entrySet()) 177 if (allowed.contains(e.getKey()) && ! NEVER_PASS_THROUGH_HEADERS.contains(e.getKey().toLowerCase(Locale.ROOT))) 178 addHeader(e.getKey(), resolveUris(e.getValue())); 179 } 180 } catch (Exception e1) { 181 throw new BadRequest(e1, "Invalid format for header 'x-response-headers'. Must be in URL-encoded format."); 182 } 183 184 // Find acceptable charset 185 var h = request.getHeaderParam("accept-charset").orElse(null); 186 Charset charset = null; 187 if (h == null) 188 charset = opContext.getDefaultCharset(); 189 else 190 for (var r : StringRanges.of(h).toList()) { 191 if (r.getQValue() > 0) { 192 if (eq(r.getName(), "*")) 193 charset = opContext.getDefaultCharset(); 194 else if (Charset.isSupported(r.getName())) 195 charset = Charset.forName(r.getName()); 196 if (nn(charset)) 197 break; 198 } 199 } 200 201 request.getContext().getDefaultResponseHeaders().forEach(x -> addHeader(x.getName(), resolveCspNonce(maybeResolveUris(x.getName(), x.getValue())))); // Done this way to avoid list/array copy. 202 203 opContext.getDefaultResponseHeaders().forEach(x -> addHeader(x.getName(), resolveCspNonce(maybeResolveUris(x.getName(), x.getValue())))); 204 205 if (charset == null) 206 throw new NotAcceptable("No supported charsets in header 'Accept-Charset': '%s'", request.getHeaderParam("Accept-Charset").orElse(null)); 207 inner.setCharacterEncoding(charset.name()); 208 209 } 210 211 /** 212 * Adds a response header. 213 * 214 * <p> 215 * Any previous header values are preserved. 216 * 217 * <p> 218 * Value is added at the end of the headers. 219 * 220 * <p> 221 * If the header is a {@link HttpUriHeader}, the URI will be resolved using the {@link RestRequest#getUriResolver()} object. 222 * 223 * <p> 224 * Note that per <a class='doclink' href='https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2'>RFC2616</a>, 225 * only headers defined as comma-delimited lists [i.e., #(values)] should be defined as multiple message header fields. 226 * 227 * @param header The header. 228 * <br>Can be <jk>null</jk> (ignored). 229 * @return This object. 230 */ 231 public RestResponse addHeader(HttpHeader header) { 232 if (header == null) { 233 // Do nothing. 234 } else if (header instanceof HttpUriHeader header2) { 235 addHeader(header2.getName(), resolveUris(header2.getValue())); 236 } else { 237 addHeader(header.getName(), header.getValue()); 238 } 239 return this; 240 } 241 242 /** 243 * Adds a response header with the given name and value. 244 * 245 * <p> 246 * This method allows response headers to have multiple values. 247 * 248 * <p> 249 * A no-op of either the name or value is <jk>null</jk>. 250 * 251 * <p> 252 * Note that per <a class='doclink' href='https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2'>RFC2616</a>, 253 * only headers defined as comma-delimited lists [i.e., #(values)] should be defined as multiple message header fields. 254 * 255 * @param name The header name. 256 * @param value The header value. 257 */ 258 @Override 259 public void addHeader(String name, String value) { 260 if (nn(name) && nn(value)) { 261 if (eqic(name, HEADER_ContentType)) 262 setHeader(name, value); 263 else { 264 if (safeHeaders) 265 value = stripInvalidHttpHeaderChars(value); 266 value = abbreviate(value, maxHeaderLength); 267 inner.addHeader(name, value); 268 } 269 } 270 } 271 272 /** 273 * Forces any content in the buffer to be written to the client. 274 * 275 * <p> 276 * A call to this method automatically commits the response, meaning the status code and headers will be written. 277 * 278 * @throws IOException If an I/O error occurred. 279 */ 280 @Override 281 public void flushBuffer() throws IOException { 282 if (nn(w)) 283 w.flush(); 284 if (nn(os)) 285 os.flush(); 286 inner.flushBuffer(); 287 } 288 289 /** 290 * Shortcut for calling <c>getRequest().getAttributes()</c>. 291 * 292 * @return The request attributes object. 293 */ 294 public RequestAttributes getAttributes() { return request.getAttributes(); } 295 296 /** 297 * Wrapper around {@link #getCharacterEncoding()} that converts the value to a {@link Charset}. 298 * 299 * @return The request character encoding converted to a {@link Charset}, or <jk>null</jk> if no character encoding is set. 300 */ 301 public Charset getCharset() { 302 var s = getCharacterEncoding(); 303 return s == null ? null : Charset.forName(s); 304 } 305 306 /** 307 * Returns the output that was set by calling {@link #setContent(Object)}. 308 * 309 * <p> 310 * If it's null, then {@link #setContent(Object)} wasn't called. 311 * <br>If it contains an empty, then <c>setObject(<jk>null</jk>)</c> was called. 312 * <br>Otherwise, {@link #setContent(Object)} was called with a non-null value. 313 * 314 * @return The output object, or <jk>null</jk> if {@link #setContent(Object)} was never called. 315 */ 316 public Optional<Object> getContent() { return content; } 317 318 /** 319 * Returns this value cast to the specified class. 320 * 321 * @param <T> The class to cast to. 322 * @param c The class to cast to. 323 * <br>Must not be <jk>null</jk>. 324 * @return This value cast to the specified class, or <jk>null</jk> if the object doesn't exist or isn't the specified type. 325 */ 326 @SuppressWarnings({ 327 "unchecked" // Type erasure requires unchecked cast 328 }) 329 public <T> T getContent(Class<T> c) { 330 if (isContentOfType(c)) 331 return (T)getRawOutput(); 332 return null; 333 } 334 335 /** 336 * Returns the schema of the response content. 337 * 338 * @return The schema of the response content, never <jk>null</jk>. 339 */ 340 public Optional<HttpPartSchema> getContentSchema() { 341 if (nn(contentSchema)) 342 return contentSchema; 343 if (nn(responseBeanMeta)) 344 contentSchema = o(responseBeanMeta.getSchema()); 345 else { 346 var rbm = opContext.getResponseBeanMeta(getContent(Object.class)); 347 if (nn(rbm)) 348 contentSchema = o(rbm.getSchema()); 349 else 350 contentSchema = oe(); 351 } 352 return contentSchema; 353 } 354 355 /** 356 * Returns access to the inner {@link RestContext} of the class of this method. 357 * 358 * @return The {@link RestContext} of this class. Never <jk>null</jk>. 359 */ 360 public RestContext getContext() { return request.getContext(); } 361 362 /** 363 * Convenience method meant to be used when rendering directly to a browser with no buffering. 364 * 365 * <p> 366 * Sets the header <js>"x-content-type-options=nosniff"</js> so that output is rendered immediately on IE and Chrome 367 * without any buffering for content-type sniffing. 368 * 369 * <p> 370 * This can be useful if you want to render a streaming 'console' on a web page. 371 * 372 * @param contentType The value to set as the <c>Content-Type</c> on the response. 373 * @return The raw writer. 374 * @throws IOException Thrown by underlying stream. 375 */ 376 public PrintWriter getDirectWriter(String contentType) throws IOException { 377 setContentType(contentType); 378 setHeader("X-Content-Type-Options", "nosniff"); 379 setHeader("Content-Encoding", "identity"); 380 return getWriter(true, true); 381 } 382 383 /** 384 * Returns the wrapped servlet response. 385 * 386 * @return The wrapped servlet response. 387 */ 388 public HttpServletResponse getHttpServletResponse() { return inner; } 389 390 /** 391 * Returns the <c>Content-Type</c> header stripped of the charset attribute if present. 392 * 393 * @return The <c>media-type</c> portion of the <c>Content-Type</c> header. 394 */ 395 public MediaType getMediaType() { return MediaType.of(getContentType()); } 396 397 /** 398 * Equivalent to {@link HttpServletResponse#getOutputStream()}, except wraps the output stream if an {@link Encoder} 399 * was found that matched the <c>Accept-Encoding</c> header. 400 * 401 * @return A negotiated output stream. 402 * @throws NotAcceptable If unsupported Accept-Encoding value specified. 403 * @throws IOException Thrown by underlying stream. 404 */ 405 public FinishableServletOutputStream getNegotiatedOutputStream() throws NotAcceptable, IOException { 406 if (os == null) { 407 Encoder encoder = null; 408 var encoders = request.getOpContext().getEncoders(); 409 410 var ae = request.getHeaderParam("Accept-Encoding").orElse(null); 411 if (ine(ae)) { 412 var match = encoders.getEncoderMatch(ae); 413 if (match == null) { 414 // Identity should always match unless "identity;q=0" or "*;q=0" is specified. 415 if (ENCODING_DISABLED_PATTERN.matcher(ae).find()) { 416 throw new NotAcceptable("Unsupported encoding in request header 'Accept-Encoding': '%s'\n\tSupported codings: %s", ae, Json5.of(encoders.getSupportedEncodings())); 417 } 418 } else { 419 encoder = match.getEncoder(); 420 var encoding = match.getEncoding(); 421 422 // Some clients don't recognize identity as an encoding, so don't set it. 423 if (neq(encoding, "identity")) 424 setHeader("content-encoding", encoding); 425 } 426 } 427 var sos2 = getOutputStream(); 428 os = new FinishableServletOutputStream(encoder == null ? sos2 : encoder.getOutputStream(sos2)); 429 } 430 return os; 431 } 432 433 /** 434 * Equivalent to {@link HttpServletResponse#getWriter()}, except wraps the output stream if an {@link Encoder} was 435 * found that matched the <c>Accept-Encoding</c> header and sets the <c>Content-Encoding</c> 436 * header to the appropriate value. 437 * 438 * @return The negotiated writer. 439 * @throws NotAcceptable If unsupported charset in request header Accept-Charset. 440 * @throws IOException Thrown by underlying stream. 441 */ 442 public FinishablePrintWriter getNegotiatedWriter() throws NotAcceptable, IOException { return getWriter(false, false); } 443 444 /** 445 * Returns access to the inner {@link RestOpContext} of this method. 446 * 447 * @return The {@link RestOpContext} of this method. Never <jk>null</jk>. 448 */ 449 public RestOpContext getOpContext() { return request.getOpContext(); } 450 451 /** 452 * Returns a ServletOutputStream suitable for writing binary data in the response. 453 * 454 * <p> 455 * The servlet container does not encode the binary data. 456 * 457 * <p> 458 * Calling <c>flush()</c> on the ServletOutputStream commits the response. 459 * Either this method or <c>getWriter</c> may be called to write the content, not both, except when reset has been called. 460 * 461 * @return The stream. 462 * @throws IOException If stream could not be accessed. 463 */ 464 @Override 465 public ServletOutputStream getOutputStream() throws IOException { 466 if (sos == null) 467 sos = inner.getOutputStream(); 468 return sos; 469 } 470 471 /** 472 * Returns <jk>true</jk> if {@link #getOutputStream()} has been called. 473 * 474 * @return <jk>true</jk> if {@link #getOutputStream()} has been called. 475 */ 476 public boolean getOutputStreamCalled() { return nn(sos); } 477 478 /** 479 * Returns the metadata about this response. 480 * 481 * @return 482 * The metadata about this response. 483 * <br>Can be <jk>null</jk> if the response method has no {@link Response @Response} metadata (or was explicitly cleared). 484 */ 485 public ResponseBeanMeta getResponseBeanMeta() { return responseBeanMeta; } 486 487 /** 488 * Returns the matching serializer and media type for this response. 489 * 490 * @return The matching serializer, never <jk>null</jk>. 491 */ 492 public Optional<SerializerMatch> getSerializerMatch() { 493 if (nn(serializerMatch)) 494 return serializerMatch; 495 if (nn(serializer)) { 496 serializerMatch = o(new SerializerMatch(getMediaType(), serializer)); 497 } else { 498 serializerMatch = opContext.getSerializers().getSerializerMatch(request.getHeaderParam("Accept").orElse("*/*")); 499 } 500 return serializerMatch; 501 } 502 503 /** 504 * Returns the writer to the response content. 505 * 506 * <p> 507 * This methods bypasses any specified encoders and returns a regular unbuffered writer. 508 * Use the {@link #getNegotiatedWriter()} method if you want to use the matched encoder (if any). 509 * 510 * @return The writer. 511 * @throws IOException If writer could not be accessed. 512 */ 513 @Override 514 public PrintWriter getWriter() throws IOException { return getWriter(true, false); } 515 516 /** 517 * Returns <jk>true</jk> if the response contains output. 518 * 519 * <p> 520 * This implies {@link #setContent(Object)} has been called on this object. 521 * 522 * <p> 523 * Note that this also returns <jk>true</jk> even if {@link #setContent(Object)} was called with a <jk>null</jk> 524 * value as this means the response contains an output value of <jk>null</jk> as opposed to no value at all. 525 * 526 * @return <jk>true</jk> if the response contains output. 527 */ 528 public boolean hasContent() { 529 return nn(content); 530 } 531 532 /** 533 * Returns <jk>true</jk> if this response object is of the specified type. 534 * 535 * @param c The type to check against. 536 * <br>Must not be <jk>null</jk>. 537 * @return <jk>true</jk> if this response object is of the specified type. 538 */ 539 public boolean isContentOfType(Class<?> c) { 540 return c.isInstance(getRawOutput()); 541 } 542 543 /** 544 * Sets the output to a plain-text message regardless of the content type. 545 * 546 * @param text The output text to send. 547 * <br>Must not be <jk>null</jk>. 548 * @return This object. 549 * @throws IOException If a problem occurred trying to write to the writer. 550 */ 551 public RestResponse sendPlainText(String text) throws IOException { 552 setContentType("text/plain"); 553 getNegotiatedWriter().write(text); 554 return this; 555 } 556 557 /** 558 * Creates a fluent Server-Sent Events helper for this response. 559 * 560 * @return The SSE response helper. 561 * @throws IOException If the writer could not be created. 562 */ 563 public SseResponseSupport sse() throws IOException { 564 return new SseResponseSupport(this); 565 } 566 567 /** 568 * Redirects to the specified URI. 569 * 570 * <p> 571 * Relative URIs are always interpreted as relative to the context root. 572 * This is similar to how WAS handles redirect requests, and is different from how Tomcat handles redirect requests. 573 * 574 * <p> 575 * This method forwards <c>uri</c> to the container as-is. If the target is built from request input (e.g. 576 * a query parameter or header value), a caller can steer users to an arbitrary external site; use 577 * {@link #sendSafeRedirect(String,String...) sendSafeRedirect(String,String...)} instead in that case, which 578 * validates the target is either relative or points at an allow-listed host. 579 * 580 * @param uri The redirection URL. 581 * @throws IOException If an input or output exception occurs 582 */ 583 @Override 584 public void sendRedirect(String uri) throws IOException { 585 var c = (uri.isEmpty() ? 0 : uri.charAt(0)); 586 if (c != '/' && uri.indexOf("://") == -1) 587 uri = request.getContextPath() + '/' + uri; 588 inner.sendRedirect(uri); 589 } 590 591 /** 592 * Redirects to the specified URI, but only if it's a relative path (interpreted per {@link #sendRedirect(String) 593 * sendRedirect(String)}) or an absolute/protocol-relative URI whose host matches one of <c>allowedHosts</c>. 594 * 595 * <p> 596 * Intended for use when the redirect target is derived from request input rather than a fixed, trusted 597 * literal, so that input can't be used to redirect a user to an arbitrary external site. 598 * 599 * @param uri The redirection URL. 600 * @param allowedHosts The hosts (case-insensitive) an absolute or protocol-relative <c>uri</c> is allowed to target. Ignored for relative URIs. 601 * @throws IOException If an input or output exception occurs. 602 * @throws BadRequest If <c>uri</c> is absolute or protocol-relative and its host isn't in <c>allowedHosts</c>. 603 */ 604 public void sendSafeRedirect(String uri, String...allowedHosts) throws IOException { 605 if (! isSafeRedirectUri(uri, allowedHosts)) 606 throw new BadRequest("Redirect target '%s' is not a relative path or an allowed host.", uri); 607 sendRedirect(uri); 608 } 609 610 /** 611 * Returns <jk>true</jk> if <c>uri</c> is safe to pass to {@link #sendRedirect(String) sendRedirect(String)} 612 * without risk of redirecting to an unintended external site: either a relative path, or an absolute/ 613 * protocol-relative URI whose host is in <c>allowedHosts</c>. 614 * 615 * @param uri The candidate redirection URL. 616 * @param allowedHosts The hosts (case-insensitive) an absolute or protocol-relative <c>uri</c> is allowed to target. 617 * @return <jk>true</jk> if the URI is safe to redirect to. 618 */ 619 static boolean isSafeRedirectUri(String uri, String...allowedHosts) { 620 if (ie(uri)) 621 return true; 622 for (var i = 0; i < uri.length(); i++) { 623 var c = uri.charAt(i); 624 if (c == '\\' || c <= 0x20 || c == 0x7f) 625 return false; 626 } 627 if (uri.charAt(0) == '/' && ! uri.startsWith("//")) 628 return true; 629 if (uri.indexOf("://") == -1 && ! uri.startsWith("//")) 630 return true; 631 String host; 632 try { 633 host = new java.net.URI(uri.startsWith("//") ? "http:" + uri : uri).getHost(); 634 } catch (java.net.URISyntaxException e) { 635 return false; 636 } 637 if (host == null || allowedHosts == null) 638 return false; 639 for (var h : allowedHosts) 640 if (eqic(host, h)) 641 return true; 642 return false; 643 } 644 645 /** 646 * Shortcut for calling <c>getRequest().setAttribute(String,Object)</c>. 647 * 648 * @param name The property name. 649 * @param value The property value. 650 * @return This object. 651 */ 652 public RestResponse setAttribute(String name, Object value) { 653 request.setAttribute(name, value); 654 return this; 655 } 656 657 /** 658 * Sets the HTTP output on the response. 659 * 660 * <p> 661 * The object type can be anything allowed by the registered response handlers. 662 * 663 * <p> 664 * Calling this method is functionally equivalent to returning the object in the REST Java method. 665 * 666 * <h4 class='section'>Example:</h4> 667 * <p class='bjava'> 668 * <ja>@RestGet</ja>(<js>"/example2/{personId}"</js>) 669 * <jk>public void</jk> doGet(RestResponse <jv>res</jv>, <ja>@Path</ja> UUID <jv>personId</jv>) { 670 * Person <jv>person</jv> = getPersonById(<jv>personId</jv>); 671 * <jv>res</jv>.setContent(<jv>person</jv>); 672 * } 673 * </p> 674 * 675 * <h4 class='section'>Notes:</h4><ul> 676 * <li class='note'> 677 * Calling this method with a <jk>null</jk> value is NOT the same as not calling this method at all. 678 * <br>A <jk>null</jk> output value means we want to serialize <jk>null</jk> as a response (e.g. as a JSON <c>null</c>). 679 * <br>Not calling this method or returning a value means you're handing the response yourself via the underlying stream or writer. 680 * </ul> 681 * 682 * <h4 class='section'>See Also:</h4><ul> 683 * <li class='ja'>{@link Rest#responseProcessors()} 684 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestOpAnnotatedMethods">@RestOp-Annotated Method</a> 685 * </ul> 686 * 687 * @param output The output to serialize to the connection. 688 * @return This object. 689 */ 690 public RestResponse setContent(Object output) { 691 this.content = o(output); 692 return this; 693 } 694 695 /** 696 * Specifies the schema for the response content. 697 * 698 * <p> 699 * Used by schema-aware serializers such as {@link OpenApiSerializer}. Ignored by other serializers. 700 * 701 * @param schema The content schema 702 * <br>Can be <jk>null</jk> (clears any previously-set schema). 703 * @return This object. 704 */ 705 public RestResponse setContentSchema(HttpPartSchema schema) { 706 this.contentSchema = o(schema); 707 return this; 708 } 709 710 /** 711 * Forces the {@link Serializer} used to serialize the response body set via {@link #setContent(Object)} (or an 712 * equivalent return from the REST method), instead of choosing one from the <c>Accept</c> header. 713 * 714 * <p> 715 * {@link org.apache.juneau.rest.server.processor.SerializedPojoProcessor} uses {@link #getSerializerMatch()}, which 716 * returns a {@link SerializerMatch} built from this serializer when non-<jk>null</jk>. 717 * 718 * <p> 719 * <c>Content-Type</c> is still applied by the response processor: it prefers {@link #getMediaType()} if set, then 720 * the match media type, then {@link Serializer#getResponseContentType()}. Call {@link #setContentType(String)} (or 721 * another header setter) if you need a specific type before serialization runs. 722 * 723 * @param value The serializer to use. Can be <jk>null</jk> to clear the override and use normal <c>Accept</c> 724 * negotiation on the next {@link #getSerializerMatch()} call. 725 * @return This object. 726 */ 727 public RestResponse setSerializer(Serializer value) { 728 serializer = value; 729 serializerMatch = null; 730 return this; 731 } 732 733 /** 734 * Returns the captured (bounded) response body bytes for debug logging. 735 * 736 * <p> 737 * Populated by the two-phase debug pipeline only when the resolved logger is loggable at 738 * {@link java.util.logging.Level#FINEST FINEST}; otherwise returns <jk>null</jk>. The captured copy is capped at the 739 * formatter's body cap (default 8 KB); use {@link #getCachedContentLength()} for the full byte count. 740 * 741 * @return The captured response body bytes, or <jk>null</jk> if body caching was not installed. 742 */ 743 public byte[] getCachedContent() { 744 return inner instanceof CachingHttpServletResponse c ? c.getContent() : null; 745 } 746 747 /** 748 * Returns the total number of response body bytes written, including any beyond the capture cap. 749 * 750 * @return The total response body length in bytes, or {@code -1} if body caching was not installed. 751 */ 752 public long getCachedContentLength() { 753 return inner instanceof CachingHttpServletResponse c ? c.getTotalLength() : -1; 754 } 755 756 /** 757 * Sets the <js>"Exception"</js> attribute to the specified throwable. 758 * 759 * <p> 760 * This exception is surfaced by the debug pipeline as the {@code thrown} of the emitted log record. 761 * 762 * @param t The attribute value. 763 * @return This object. 764 */ 765 public RestResponse setException(Throwable t) { 766 request.setException(t); 767 return this; 768 } 769 770 /** 771 * Sets a response header. 772 * 773 * <p> 774 * Any previous header values are removed. 775 * 776 * <p> 777 * Value is added at the end of the headers. 778 * 779 * @param header The header. 780 * <br>Can be <jk>null</jk> (ignored). 781 * @return This object. 782 */ 783 public RestResponse setHeader(HttpHeader header) { 784 if (header == null) { 785 // Do nothing. 786 } else if (header instanceof HttpUriHeader header2) { 787 setHeader(header2.getName(), resolveUris(header2.getValue())); 788 } else { 789 var v = header.getValue(); 790 if (nn(v) && v.indexOf("://") != -1) 791 v = resolveUris(v); 792 setHeader(header.getName(), v); 793 } 794 return this; 795 } 796 797 /** 798 * Sets <l>Content-Disposition</l> to <js>attachment</js> so browsers typically download the body, using the given 799 * suggested file name (quoted {@code filename} parameter). 800 * 801 * <p> 802 * Shorthand for {@link #setHeader(HttpHeader) setHeader}({@link ContentDisposition#attachment(String) 803 * ContentDisposition.attachment(filename)}). 804 * </p> 805 * 806 * <h4 class='figure'>Example</h4> 807 * <p class='bjava'> 808 * <jv>res</jv>.downloadAs(<js>"example.pdf"</js>).setContent(<jv>pdfBytes</jv>); 809 * </p> 810 * 811 * @param filename Suggested download name. Must not be <jk>null</jk>, blank, or contain CR/LF. 812 * @return This object. 813 * @throws IllegalArgumentException If {@code filename} is invalid. 814 * @see ContentDisposition#attachment(String) 815 */ 816 public RestResponse downloadAs(String filename) { 817 return setHeader(ContentDisposition.attachment(filename)); 818 } 819 820 /** 821 * Sets the <c>ETag</c> response header to the supplied wire value. 822 * 823 * <p> 824 * The value is validated through {@link EntityTag#of(Object)} — strong tags must be quoted 825 * (<c>"v1"</c>), weak tags must be prefixed with <c>W/</c> (<c>W/"v1"</c>), and the wildcard 826 * <c>*</c> is accepted. The header is serialized in canonical form (re-quoted for strong tags, 827 * <c>W/</c>-prefixed for weak tags). 828 * 829 * <h4 class='section'>Example:</h4> 830 * <p class='bjava'> 831 * <jv>res</jv>.eTag(<js>"\"v42\""</js>); <jc>// ETag: "v42"</jc> 832 * <jv>res</jv>.eTag(<js>"W/\"v42\""</js>); <jc>// ETag: W/"v42"</jc> 833 * </p> 834 * 835 * @param value The entity-tag wire value. Must not be <jk>null</jk>; must match the 836 * {@code entity-tag} grammar per RFC 7232 §2.3. 837 * @return This object. 838 * @throws IllegalArgumentException If {@code value} is malformed. 839 * @see RestRequest#checkPreconditions(RestResponse) 840 */ 841 public RestResponse eTag(String value) { 842 return eTag(EntityTag.of(value)); 843 } 844 845 /** 846 * Sets the <c>ETag</c> response header to the canonical wire form of the supplied {@link EntityTag}. 847 * 848 * @param value The entity tag. Must not be <jk>null</jk>. 849 * @return This object. 850 * @throws IllegalArgumentException If {@code value} is <jk>null</jk>. 851 */ 852 public RestResponse eTag(EntityTag value) { 853 reqnn("value", value); 854 return setHeader(ETag.of(value.toString())); 855 } 856 857 /** 858 * Sets the <c>Last-Modified</c> response header to the supplied instant formatted as an 859 * <a class='doclink' href='https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1'>RFC 7231 IMF-fixdate</a>. 860 * 861 * <p> 862 * The instant is rendered in GMT regardless of the JVM's default timezone. The fractional-second 863 * portion is truncated, matching the per-spec one-second resolution of HTTP-date timestamps. 864 * 865 * <h4 class='section'>Example:</h4> 866 * <p class='bjava'> 867 * <jv>res</jv>.lastModified(Instant.<jsm>parse</jsm>(<js>"2026-05-22T00:00:00Z"</js>)); 868 * <jc>// Last-Modified: Fri, 22 May 2026 00:00:00 GMT</jc> 869 * </p> 870 * 871 * @param value The last-modified timestamp. Must not be <jk>null</jk>. 872 * @return This object. 873 * @throws IllegalArgumentException If {@code value} is <jk>null</jk>. 874 * @see RestRequest#checkPreconditions(RestResponse) 875 */ 876 public RestResponse lastModified(Instant value) { 877 reqnn("value", value); 878 return lastModified(value.atZone(ZoneOffset.UTC)); 879 } 880 881 /** 882 * Sets the <c>Last-Modified</c> response header to the supplied date-time formatted as an 883 * <a class='doclink' href='https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1'>RFC 7231 IMF-fixdate</a>. 884 * 885 * <p> 886 * The supplied date-time is converted to GMT and truncated to whole seconds before formatting. 887 * 888 * @param value The last-modified timestamp. Must not be <jk>null</jk>. 889 * @return This object. 890 * @throws IllegalArgumentException If {@code value} is <jk>null</jk>. 891 */ 892 public RestResponse lastModified(ZonedDateTime value) { 893 reqnn("value", value); 894 var z = value.withZoneSameInstant(ZoneOffset.UTC).truncatedTo(SECONDS); 895 return setHeader(LastModified.of(RFC_1123_DATE_TIME.format(z))); 896 } 897 898 /** 899 * Sets the <c>Cache-Control</c> response header to the supplied directive string. 900 * 901 * <p> 902 * The value is written verbatim — the caller is responsible for supplying a comma-separated 903 * directive list per <a class='doclink' href='https://www.rfc-editor.org/rfc/rfc9111#name-cache-control'>RFC 904 * 9111 §5.2</a>. 905 * 906 * @param value The directive list (e.g. <js>"public, max-age=3600"</js>). Must not be <jk>null</jk>. 907 * @return This object. 908 * @throws IllegalArgumentException If {@code value} is <jk>null</jk>. 909 * @see #cacheControl(CacheControl.Builder) 910 */ 911 public RestResponse cacheControl(String value) { 912 reqnn("value", value); 913 return setHeader(CacheControl.of(value)); 914 } 915 916 /** 917 * Sets the <c>Cache-Control</c> response header from a {@link org.apache.juneau.http.header.CacheControl.Builder CacheControl.Builder}. 918 * 919 * <h4 class='section'>Example:</h4> 920 * <p class='bjava'> 921 * <jv>res</jv>.cacheControl(CacheControl.<jsm>create</jsm>().publicCache().maxAge(3600)); 922 * <jc>// Cache-Control: public, max-age=3600</jc> 923 * </p> 924 * 925 * @param value The builder. Must not be <jk>null</jk>. 926 * @return This object. 927 * @throws IllegalArgumentException If {@code value} is <jk>null</jk>. 928 */ 929 public RestResponse cacheControl(CacheControl.Builder value) { 930 reqnn("value", value); 931 return cacheControl(value.build()); 932 } 933 934 /** 935 * Sets a header on the request. 936 * 937 * @param schema 938 * The schema to use to serialize the header, or <jk>null</jk> to use the default schema. 939 * @param name The header name. 940 * @param value The header value. 941 * <ul> 942 * <li>Can be any POJO. 943 * <li>Converted to a string using the specified part serializer. 944 * </ul> 945 * @return This object. 946 * @throws SchemaValidationException Header failed schema validation. 947 * @throws SerializeException Header could not be serialized. 948 */ 949 public RestResponse setHeader(HttpPartSchema schema, String name, Object value) throws SchemaValidationException, SerializeException { 950 setHeader(name, request.getPartSerializerSession().write(HEADER, schema, value)); 951 return this; 952 } 953 954 /** 955 * Sets a header on the request. 956 * 957 * @param name The header name. 958 * @param value The header value. 959 * <ul> 960 * <li>Can be any POJO. 961 * <li>Converted to a string using the specified part serializer. 962 * </ul> 963 * @return This object. 964 * @throws SchemaValidationException Header failed schema validation. 965 * @throws SerializeException Header could not be serialized. 966 */ 967 public RestResponse setHeader(String name, Object value) throws SchemaValidationException, SerializeException { 968 setHeader(name, request.getPartSerializerSession().write(HEADER, null, value)); 969 return this; 970 } 971 972 /** 973 * Sets a response header with the given name and value. 974 * 975 * <p> 976 * If the header had already been set, the new value overwrites the previous one. 977 * 978 * <p> 979 * The {@link #containsHeader(String)} method can be used to test for the presence of a header before setting its value. 980 * 981 * @param name The header name. 982 * @param value The header value. 983 */ 984 @Override 985 public void setHeader(String name, String value) { 986 987 // Jetty doesn't set the content type correctly if set through this method. 988 // Tomcat/WAS does. 989 if (eqic(name, HEADER_ContentType)) { 990 inner.setContentType(value); 991 ContentType ct = ContentType.of(value); 992 if (nn(ct) && nn(ct.getParameter("charset"))) 993 inner.setCharacterEncoding(ct.getParameter("charset")); 994 } else { 995 if (safeHeaders) 996 value = stripInvalidHttpHeaderChars(value); 997 value = abbreviate(value, maxHeaderLength); 998 inner.setHeader(name, value); 999 } 1000 } 1001 1002 /** 1003 * Specifies the maximum length for header values. 1004 * 1005 * <p> 1006 * Header values that exceed this length will get truncated. 1007 * 1008 * @param value The new value for this setting. The default is <c>8096</c>. 1009 * @return This object. 1010 */ 1011 public RestResponse setMaxHeaderLength(int value) { 1012 maxHeaderLength = value; 1013 return this; 1014 } 1015 1016 /** 1017 * Shortcut for calling <c>setNoTrace(<jk>true</jk>)</c>. 1018 * 1019 * @return This object. 1020 */ 1021 public RestResponse setNoTrace() { 1022 return setNoTrace(true); 1023 } 1024 1025 /** 1026 * Sets the <js>"NoTrace"</js> attribute to the specified boolean. 1027 * 1028 * <p> 1029 * This flag tells the framework not to trace the current request: the access-log record for the call is still 1030 * emitted, but without the exception's stack trace. A <c>No-Trace: true</c> request header has the same effect; when both are present, the attribute wins. 1031 * 1032 * @param b The attribute value. 1033 * @return This object. 1034 */ 1035 public RestResponse setNoTrace(Boolean b) { 1036 request.setNoTrace(b); 1037 return this; 1038 } 1039 1040 /** 1041 * Sets metadata about this response. 1042 * 1043 * @param rbm The metadata about this response. 1044 * <br>Can be <jk>null</jk> (clears the metadata). 1045 * @return This object. 1046 */ 1047 public RestResponse setResponseBeanMeta(ResponseBeanMeta rbm) { 1048 this.responseBeanMeta = rbm; 1049 return this; 1050 } 1051 1052 /** 1053 * Enables safe-header mode. 1054 * 1055 * <p> 1056 * When enabled (the default), invalid characters such as CTRL characters (including a raw CR or LF that 1057 * could otherwise be used to inject an additional header or split the response) are stripped from header 1058 * values via {@link org.apache.juneau.commons.utils.StringUtils#stripInvalidHttpHeaderChars(String) 1059 * StringUtils.stripInvalidHttpHeaderChars(String)} before they get set. This is a no-op call retained for 1060 * apps that called it explicitly before this became the default; see {@link #setUnsafeHeaders()} to opt 1061 * back out. 1062 * 1063 * @return This object. 1064 */ 1065 public RestResponse setSafeHeaders() { 1066 this.safeHeaders = true; 1067 return this; 1068 } 1069 1070 /** 1071 * Disables safe-header mode, restoring the pre-hardening behavior of passing header values through to the 1072 * underlying {@link HttpServletResponse} verbatim (aside from the usual {@link #setMaxHeaderLength(int)} 1073 * truncation). 1074 * 1075 * <p> 1076 * Only call this for a header value the application has already validated itself; most servlet containers 1077 * reject a raw CR/LF in a header value outright regardless of this setting, but other control characters may 1078 * still pass through once safe-header mode is off. 1079 * 1080 * @return This object. 1081 */ 1082 public RestResponse setUnsafeHeaders() { 1083 this.safeHeaders = false; 1084 return this; 1085 } 1086 1087 private Object getRawOutput() { return content == null ? null : content.orElse(null); } 1088 1089 private FinishablePrintWriter getWriter(boolean raw, boolean autoflush) throws NotAcceptable, IOException { 1090 if (nn(w)) 1091 return w; 1092 1093 // If plain text requested, override it now. 1094 if (request.isPlainText()) 1095 setHeader(HEADER_ContentType, "text/plain"); 1096 1097 try { 1098 OutputStream out = (raw ? getOutputStream() : getNegotiatedOutputStream()); 1099 w = new FinishablePrintWriter(out, getCharacterEncoding(), autoflush); 1100 return w; 1101 } catch (@SuppressWarnings("unused") UnsupportedEncodingException e) { 1102 var ce = getCharacterEncoding(); 1103 setCharacterEncoding("UTF-8"); 1104 throw new NotAcceptable("Unsupported charset in request header 'Accept-Charset': '%s'", ce); 1105 } 1106 } 1107 1108 private String resolveUris(Object value) { 1109 var s = s(value); 1110 return request.getUriResolver().resolve(s); 1111 } 1112 1113 private String maybeResolveUris(String name, Object value) { 1114 return isUriBearingHeader(name) ? resolveUris(value) : s(value); 1115 } 1116 1117 /** 1118 * If a (Content-Security-Policy) header value contains a nonce placeholder, mints a single per-response nonce 1119 * (cached as a request attribute so the serializer stamps the SAME value onto inline {@code <script>}/{@code <style>} 1120 * tags) and substitutes it into the value. Returns the value unchanged when no placeholder is present, so this is 1121 * a no-op for every non-CSP header and for CSP headers that don't use a nonce. 1122 * 1123 * @param value The already-URI-resolved header value. May be <jk>null</jk>. 1124 * @return The header value with any nonce placeholder resolved. 1125 */ 1126 private String resolveCspNonce(String value) { 1127 if (value == null || ! value.contains(ContentSecurityPolicy.Builder.NONCE_PLACEHOLDER)) 1128 return value; 1129 var nonce = request.getAttribute(RestRequest.CSP_NONCE_ATTR).as(String.class).orElse(null); 1130 if (nonce == null) { 1131 nonce = ContentSecurityPolicy.Builder.generateNonce(); 1132 request.setAttribute(RestRequest.CSP_NONCE_ATTR, nonce); 1133 } 1134 return ContentSecurityPolicy.Builder.resolveNonce(value, nonce); 1135 } 1136 1137 private static boolean isUriBearingHeader(String name) { 1138 if (name == null) 1139 return false; 1140 return eqic(name, "Location") 1141 || eqic(name, "Content-Location") 1142 || eqic(name, "Referer"); 1143 } 1144}