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.*;
022import org.apache.juneau.http.header.*;
023import org.apache.juneau.rest.server.*;
024
025/**
026 * Response handler for {@link HttpBody} objects (transport-neutral replacement for the historical
027 * Apache HttpClient 4.5 {@code HttpEntity}-keyed processor).
028 *
029 * <h5 class='section'>See Also:</h5><ul>
030 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ResponseProcessors">Response Processors</a>
031 * </ul>
032 */
033public class HttpBodyProcessor implements ResponseProcessor {
034
035   @Override /* Overridden from ResponseProcessor */
036   public int process(RestOpSession opSession) throws IOException {
037
038      var res = opSession.getResponse();
039      var e = res.getContent(HttpBody.class);
040
041      if (e == null) {
042         var raw = res.getContent(Object.class);
043         if (LegacyHttpResponseAdapter.isLegacyEntity(raw)) {
044            e = LegacyHttpResponseAdapter.adaptEntity(raw);
045            LegacyHttpResponseAdapter.copyResourceHeaders(raw, res::addHeader);
046         } else {
047            return NEXT;
048         }
049      }
050
051      var ct = e.getContentType();
052      if (ct != null)
053         res.setHeader(ContentType.of(ct));
054      var contentLength = e.getContentLength();
055      if (contentLength >= 0)
056         res.setHeader(ContentLength.of(contentLength));
057
058      try (var os = res.getNegotiatedOutputStream()) {
059         e.writeTo(os);
060         os.flush();
061      }
062
063      return FINISHED;
064   }
065}