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.http.classic.header;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020import static org.apache.juneau.commons.utils.ThrowableUtils.*;
021
022import java.lang.reflect.*;
023import java.util.*;
024import java.util.concurrent.*;
025
026import org.apache.juneau.commons.reflect.*;
027import org.apache.juneau.marshall.httppart.*;
028
029/**
030 * Holds metadata about header beans (POJOs that get serialized as HTTP headers).
031 *
032 * <p>
033 * Header beans are typically annotated with {@link org.apache.juneau.http.Header @Header} although it's not an
034 * absolute requirement.
035 *
036 * <p>
037 * Header beans must have one of the following public constructors:
038 * <ul>
039 *    <li><c><jk>public</jk> X(String <jv>headerValue</jv>)</c>
040 *    <li><c><jk>public</jk> X(Object <jv>headerValue</jv>)</c>
041 *    <li><c><jk>public</jk> X(String <jv>headerName</jv>, String <jv>headerValue</jv>)</c>
042 *    <li><c><jk>public</jk> X(String <jv>headerName</jv>, Object <jv>headerValue</jv>)</c>
043 * </ul>
044 *
045 * <h2 class='figure'>Example</h2>
046 * <p class='bjava'>
047 *    <jc>// Our header bean.</jc>
048 *    <ja>@Header</ja>(<js>"Foo"</js>)
049 *    <jk>public class</jk> FooHeader <jk>extends</jk> BasicStringHeader {
050 *
051 *       <jk>public</jk> FooHeader(String <jv>headerValue</jv>) {
052 *          <jk>super</jk>(<js>"Foo"</js>, <jv>headerValue</jv>);
053 *       }
054 *  }
055 *
056 *  <jc>// Code to retrieve a header bean from a header list in a request.</jc>
057 *  HeaderList <jv>headers</jv> = <jv>httpRequest</jv>.getHeaders();
058 *  FooHeader <jv>foo</jv> = <jv>headers</jv>.get(FooHeader.<jk>class</jk>);
059 * </p>
060 *
061 * <h2 class='section'>See Also:</h2><ul>
062 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauRestCommon">juneau-rest-common</a>
063 * </ul>
064 *
065 * @param <T> The header bean type.
066 */
067public class HeaderBeanMeta<T> {
068
069   private static final ConcurrentHashMap<Class<?>,HeaderBeanMeta<?>> CACHE = new ConcurrentHashMap<>();
070
071   /**
072    * Finds the header bean meta for the specified type.
073    *
074    * @param <T> The header bean type.
075    * @param type The header bean type.  Must not be <jk>null</jk> or a {@link NullPointerException} is thrown.
076    * @return The metadata.  Never <jk>null</jk>.
077    */
078   @SuppressWarnings({
079      "unchecked" // Type erasure requires cast for HeaderBeanMeta creation
080   })
081   public static <T> HeaderBeanMeta<T> of(Class<T> type) {
082      HeaderBeanMeta<?> m = CACHE.computeIfAbsent(type, HeaderBeanMeta::new);
083      return (HeaderBeanMeta<T>)m;
084   }
085
086   private final Class<T> type;
087   private final Constructor<T> constructor;
088
089   private final HttpPartSchema schema;
090
091   private HeaderBeanMeta(Class<T> type) {
092      this.type = type;
093
094      var ci = ClassInfo.of(type);
095
096      // @formatter:off
097      constructor = ci.getPublicConstructor(x -> x.hasParameterTypes(String.class))
098         .or(() -> ci.getPublicConstructor(x -> x.hasParameterTypes(Object.class)))
099         .or(() -> ci.getPublicConstructor(x -> x.hasParameterTypes(String.class, String.class)))
100         .or(() -> ci.getPublicConstructor(x -> x.hasParameterTypes(String.class, Object.class)))
101         .map(x -> x.<T>inner())
102         .orElse(null);
103      // @formatter:on
104
105      this.schema = HttpPartSchema.create(org.apache.juneau.http.Header.class, type);
106   }
107
108   /**
109    * Constructs a header bean with the specified name or value.
110    *
111    * <p>
112    * Can only be used on beans where the header name is known.
113    *
114    * @param value
115    *    The header value.
116    *    <br>Can be <jk>null</jk>, in which case it is passed as-is (or stringified to <jk>null</jk>) to the bean's constructor.
117    * @return A newly constructed bean.
118    * @throws UnsupportedOperationException If bean could not be constructed (e.g. couldn't find a constructor).
119    */
120   public T construct(Object value) {
121      return construct(null, value);
122   }
123
124   /**
125    * Constructs a header bean with the specified name or value.
126    *
127    * @param name
128    *    The header name.
129    *    <br>If <jk>null</jk>, uses the value pulled from the {@link org.apache.juneau.http.Header#name() @Header(name)} or
130    *    {@link org.apache.juneau.http.Header#value() @Header(value)} annotations.
131    * @param value
132    *    The header value.
133    *    <br>Can be <jk>null</jk>, in which case it is passed as-is (or stringified to <jk>null</jk>) to the bean's constructor.
134    * @return A newly constructed bean.
135    * @throws UnsupportedOperationException If bean could not be constructed (e.g. couldn't find a constructor).
136    */
137   public T construct(String name, Object value) {
138
139      if (constructor == null)
140         throw uoex("Constructor for type %s could not be found.", cn(type));
141
142      if (name == null)
143         name = schema.getName();
144
145      var pt = constructor.getParameterTypes();
146      var args = new Object[pt.length];
147      if (pt.length == 1) {
148         args[0] = pt[0] == String.class ? s(value) : value;
149      } else {
150         if (name == null)
151            throw uoex("Constructor for type %s requires a name as the first argument.", cn(type));
152         args[0] = name;
153         args[1] = pt[1] == String.class ? s(value) : value;
154      }
155
156      try {
157         return constructor.newInstance(args);
158      } catch (Exception e) {
159         throw toRex(e);
160      }
161   }
162
163   @Override
164   public boolean equals(Object o) {
165      return o instanceof HeaderBeanMeta<?> other && eq(this, other, (x, y) -> x.type == y.type);
166   }
167
168   @Override
169   public int hashCode() {
170      return Objects.hashCode(type);
171   }
172
173   /**
174    * Returns schema information about this header.
175    *
176    * <p>
177    * This is information pulled from {@link org.apache.juneau.http.Header @Header} annotation on the class.
178    *
179    * @return The schema information.
180    */
181   public HttpPartSchema getSchema() { return schema; }
182}