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.processor; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020 021import java.io.*; 022 023import org.apache.juneau.http.*; 024import org.apache.juneau.http.header.*; 025import org.apache.juneau.rest.server.*; 026 027/** 028 * Response handler for {@link HttpResource} objects. 029 * 030 * <p> 031 * {@code HEAD} requests are handled per RFC 7231 §4.3.2: identical headers to the equivalent 032 * {@code GET} are emitted (Content-Type, Content-Length, plus any resource-supplied headers) 033 * but the response body is suppressed. 034 * 035 * <h5 class='section'>See Also:</h5><ul> 036 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ResponseProcessors">Response Processors</a> 037 * </ul> 038 */ 039public class HttpResourceProcessor implements ResponseProcessor { 040 041 @Override /* Overridden from ResponseProcessor */ 042 public int process(RestOpSession opSession) throws IOException { 043 044 var res = opSession.getResponse(); 045 var r = res.getContent(HttpResource.class); 046 047 if (r == null) 048 return NEXT; 049 050 var contentType = r.getContentType(); 051 if (contentType != null) 052 res.setHeader(ContentType.of(contentType)); 053 var contentLength = r.getContentLength(); 054 if (contentLength >= 0) 055 res.setHeader(ContentLength.of(contentLength)); 056 057 r.getHeaders().forEach(res::addHeader); 058 059 // RFC 7231 §4.3.2: HEAD must mirror GET headers but omit the body. 060 if (eqic("HEAD", opSession.getRequest().getMethod())) 061 return FINISHED; 062 063 try (var os = res.getNegotiatedOutputStream()) { 064 r.writeTo(os); 065 os.flush(); 066 } 067 068 return FINISHED; 069 } 070}