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