001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.rest.response; 014 015import static org.apache.juneau.internal.StringUtils.*; 016 017import java.io.*; 018import java.util.*; 019 020import org.apache.juneau.*; 021import org.apache.juneau.http.*; 022import org.apache.juneau.rest.*; 023 024/** 025 * Response handler for {@link Writable} and {@link ReaderResource} objects. 026 * 027 * <p> 028 * Uses the {@link Writable#writeTo(Writer)} method to send the contents to the {@link RestResponse#getNegotiatedWriter()} writer. 029 * 030 * <h5 class='section'>See Also:</h5> 031 * <ul> 032 * <li class='link'><a class="doclink" href="../../../../../overview-summary.html#juneau-rest-server.MethodReturnTypes">Overview > juneau-rest-server > Method Return Types</a> 033 * </ul> 034 */ 035public final class WritableHandler implements ResponseHandler { 036 037 @Override /* ResponseHandler */ 038 public boolean handle(RestRequest req, RestResponse res, Object output) throws IOException, RestException { 039 if (output instanceof Writable) { 040 if (output instanceof ReaderResource) { 041 ReaderResource r = (ReaderResource)output; 042 MediaType mediaType = r.getMediaType(); 043 if (mediaType != null) 044 res.setContentType(mediaType.toString()); 045 for (Map.Entry<String,Object> h : r.getHeaders().entrySet()) 046 res.setHeader(h.getKey(), asString(h.getValue())); 047 } 048 try (Writer w = res.getNegotiatedWriter()) { 049 ((Writable)output).writeTo(w); 050 } 051 return true; 052 } 053 return false; 054 } 055} 056