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.client;
014
015import static org.apache.juneau.internal.IOUtils.*;
016
017import java.io.*;
018
019import org.apache.http.entity.*;
020import org.apache.http.message.*;
021import org.apache.juneau.httppart.*;
022import org.apache.juneau.internal.*;
023import org.apache.juneau.serializer.*;
024import org.apache.juneau.utils.*;
025
026/**
027 * HttpEntity for serializing POJOs as the body of HTTP requests.
028 */
029public final class RestRequestEntity extends BasicHttpEntity {
030   final Object output;
031   final Serializer serializer;
032   final HttpPartSchema schema;
033   byte[] outputBytes;
034
035   /**
036    * Constructor.
037    *
038    * @param input The POJO to serialize.  Can also be a {@link Reader} or {@link InputStream}.
039    * @param serializer The serializer to use to serialize this response.
040    * @param schema The optional schema information about the serialized part.
041    */
042   public RestRequestEntity(Object input, Serializer serializer, HttpPartSchema schema) {
043      this.output = input;
044      this.serializer = serializer;
045      this.schema = schema;
046      if (serializer != null && serializer.getResponseContentType() != null)
047         setContentType(new BasicHeader("Content-Type", serializer.getResponseContentType().toString()));
048   }
049
050   @Override /* BasicHttpEntity */
051   public void writeTo(OutputStream os) throws IOException {
052      os = new NoCloseOutputStream(os);
053      if (output instanceof InputStream) {
054         IOPipe.create(output, os).run();
055      } else if (output instanceof Reader) {
056         try (OutputStreamWriter osw = new OutputStreamWriter(os, UTF8)) {
057            IOPipe.create(output, osw).run();
058         }
059      } else {
060         try {
061            if (serializer == null) {
062               // If no serializer specified, just close the stream.
063               os.close();
064            } else {
065               SerializerSessionArgs sArgs = new SerializerSessionArgs(null, null, null, null, null, schema, false, null, null);
066               SerializerSession session = serializer.createSession(sArgs);
067               try (Closeable c = session.isWriterSerializer() ? new OutputStreamWriter(os, UTF8) : os) {
068                  session.serialize(output, c);
069               }
070            }
071         } catch (SerializeException e) {
072            throw new org.apache.juneau.rest.client.RestCallException(e);
073         }
074      }
075   }
076
077   @Override /* BasicHttpEntity */
078   public boolean isRepeatable() {
079      return true;
080   }
081
082   @Override /* BasicHttpEntity */
083   public InputStream getContent() {
084      if (outputBytes == null) {
085         try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
086            writeTo(baos);
087            outputBytes = baos.toByteArray();
088         } catch (IOException e) {
089            throw new RuntimeException(e);
090         }
091      }
092      return new ByteArrayInputStream(outputBytes);
093   }
094
095   /**
096    * @deprecated Use {@link #RestRequestEntity(Object, Serializer, HttpPartSchema)}
097    */
098   @SuppressWarnings("javadoc")
099   @Deprecated
100   public RestRequestEntity(Object input, Serializer serializer) {
101      this(input, serializer, null);
102   }
103}