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.httppart;
018
019import static org.apache.juneau.commons.utils.ThrowableUtils.*;
020import static org.apache.juneau.commons.utils.Utils.*;
021
022import org.apache.http.*;
023
024/**
025 * Represents an instance of an HTTP part.
026 *
027 * <p>
028 * Can be used to represent both request and response parts.
029 *
030 * <h5 class='section'>See Also:</h5><ul>
031 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/HttpPartSerializersParsers">HTTP Part Serializers and Parsers</a>
032 * </ul>
033 */
034public class HttpPart implements NameValuePair {
035   private final String name;
036   private final Object opart;
037   private final String spart;
038   private final HttpPartType partType;
039   private final HttpPartSchema schema;
040   private final HttpPartSerializerSession serializer;
041
042   /**
043    * Constructor.
044    *
045    * <p>
046    * Used when the part is in POJO form and needs to be converted to a String.
047    *
048    * @param name The HTTP part name (e.g. the header name).
049    * @param partType The HTTP part type.
050    * @param schema Schema information about the part.
051    * @param serializer The part serializer to use to serialize the part.
052    * @param part The part POJO being serialized.
053    */
054   public HttpPart(String name, HttpPartType partType, HttpPartSchema schema, HttpPartSerializerSession serializer, Object part) {
055      this.name = name;
056      this.partType = partType;
057      this.schema = schema;
058      this.serializer = serializer;
059      this.opart = part;
060      this.spart = null;
061   }
062
063   @Override /* Overridden from NameValuePair */
064   public String getName() { return name; }
065
066   @Override /* Overridden from NameValuePair */
067   public String getValue() {
068      if (nn(spart))
069         return spart;
070      try {
071         return serializer.serialize(partType, schema, opart);
072      } catch (Exception e) {
073         throw toRex(e);
074      }
075   }
076}