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 java.io.*; 020 021import org.apache.juneau.http.header.*; 022import org.apache.juneau.http.response.*; 023import org.apache.juneau.rest.server.*; 024 025/** 026 * Response handler for {@link HttpResponseMessage} objects (transport-neutral replacement for {@code HttpResponse}). 027 * 028 * <h5 class='section'>See Also:</h5><ul> 029 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ResponseProcessors">Response Processors</a> 030 * </ul> 031 */ 032public class HttpResponseProcessor implements ResponseProcessor { 033 034 @Override /* Overridden from ResponseProcessor */ 035 public int process(RestOpSession opSession) throws IOException { 036 037 var res = opSession.getResponse(); 038 var r = res.getContent(HttpResponseMessage.class); 039 040 if (r == null) { 041 var raw = res.getContent(Object.class); 042 if (LegacyHttpResponseAdapter.isLegacyResponse(raw)) 043 r = LegacyHttpResponseAdapter.adapt(raw); 044 else 045 return NEXT; 046 } 047 048 opSession.status(r.getStatusLine()); 049 050 var body = r.getBody(); 051 if (body != null) { 052 var ct = body.getContentType(); 053 if (ct != null) 054 res.setHeader(ContentType.of(ct)); 055 var contentLength = body.getContentLength(); 056 if (contentLength >= 0) 057 res.setHeader(ContentLength.of(contentLength)); 058 } 059 060 r.getHeaders().forEach(res::addHeader); 061 062 if (body != null) { 063 try (var os = res.getNegotiatedOutputStream()) { 064 body.writeTo(os); 065 os.flush(); 066 } 067 } 068 069 return FINISHED; 070 } 071}