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.part;
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.concurrent.*;
024
025import org.apache.juneau.commons.reflect.*;
026import org.apache.juneau.http.*;
027import org.apache.juneau.marshall.httppart.*;
028
029/**
030 * Holds metadata about http part beans (POJOs that get serialized as HTTP parts such as form data or query parameters).
031 *
032 * <p>
033 * HTTP part beans are typically annotated with {@link Query @Query}, {@link FormData @FormData}, or {@link Path @Path}
034 * although it's not an absolute requirement.
035 *
036 * <p>
037 * HTTP part beans must have one of the following public constructors:
038 * <ul>
039 *    <li><c><jk>public</jk> X(String <jv>partValue</jv>)</c>
040 *    <li><c><jk>public</jk> X(Object <jv>partValue</jv>)</c>
041 *    <li><c><jk>public</jk> X(String <jv>partName</jv>, String <jv>partValue</jv>)</c>
042 *    <li><c><jk>public</jk> X(String <jv>partName</jv>, Object <jv>partValue</jv>)</c>
043 * </ul>
044 *
045 * <h2 class='figure'>Example</h2>
046 * <p class='bjava'>
047 *    <jc>// Our part bean.</jc>
048 *    <ja>@Query</ja>(<js>"foo"</js>)
049 *    <jk>public class</jk> FooPart <jk>extends</jk> BasicStringPart {
050 *
051 *       <jk>public</jk> FooPart(String <jv>partValue</jv>) {
052 *          <jk>super</jk>(<js>"foo"</js>, <jv>partValue</jv>);
053 *       }
054 *  }
055 *
056 *  <jc>// Code to retrieve a part bean from a part list in a request.</jc>
057 *  PartList <jv>parts</jv> = <jv>httpRequest</jv>.getFormDataList();
058 *  FooPart <jv>foo</jv> = <jv>parts</jv>.get(FooPart.<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 HTTP part bean type.
066 */
067public class PartBeanMeta<T> {
068
069   private static final ConcurrentHashMap<Class<?>,PartBeanMeta<?>> CACHE = new ConcurrentHashMap<>();
070
071   /**
072    * Finds the part bean meta for the specified type.
073    *
074    * @param <T> The part bean type.
075    * @param type The part bean type.  Must not be <jk>null</jk>.
076    * @return The metadata for the specified type.  Never <jk>null</jk> (a bean with no usable constructor causes {@link #construct(String,Object)} to throw instead).
077    */
078   @SuppressWarnings({
079      "unchecked" // Type erasure requires cast for PartBeanMeta creation
080   })
081   public static <T> PartBeanMeta<T> of(Class<T> type) {
082      PartBeanMeta<?> m = CACHE.computeIfAbsent(type, PartBeanMeta::new);
083      return (PartBeanMeta<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 PartBeanMeta(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      if (ci.hasAnnotation(Query.class))
106         this.schema = HttpPartSchema.create(Query.class, type);
107      else if (ci.hasAnnotation(FormData.class))
108         this.schema = HttpPartSchema.create(FormData.class, type);
109      else if (ci.hasAnnotation(Path.class))
110         this.schema = HttpPartSchema.create(Path.class, type);
111      else
112         this.schema = HttpPartSchema.create(Header.class, type);
113   }
114
115   /**
116    * Constructs a part bean with the specified name or value.
117    *
118    * <p>
119    * Can only be used on beans where the part name is known.
120    *
121    * @param value
122    *    The part value.
123    *    <br>Can be <jk>null</jk>.  The effect is implementation-dependent, depending on the target bean type's constructor shape — see {@link #construct(String, Object)}.
124    * @return A newly constructed bean.
125    * @throws UnsupportedOperationException If bean could not be constructed (e.g. couldn't find a constructor).
126    */
127   public T construct(Object value) {
128      return construct(null, value);
129   }
130
131   /**
132    * Constructs a part bean with the specified name or value.
133    *
134    * @param name
135    *    The part name.
136    *    <br>If <jk>null</jk>, uses the value pulled from the {@link Header#name() @Header(name)} or
137    *    {@link Header#value() @Header(value)} annotations.
138    * @param value
139    *    The part value.
140    *    <br>Can be <jk>null</jk>.  The effect is implementation-dependent, depending on the target bean type's constructor shape (e.g. coerced to <c>String</c> for a single-<c>String</c>-arg constructor, passed through unchanged otherwise).
141    * @return A newly constructed bean.
142    * @throws UnsupportedOperationException If bean could not be constructed (e.g. couldn't find a constructor).
143    */
144   public T construct(String name, Object value) {
145
146      if (constructor == null)
147         throw uoex("Constructor for type %s could not be found.", cn(type));
148
149      if (name == null)
150         name = schema.getName();
151
152      var pt = constructor.getParameterTypes();
153      var args = new Object[pt.length];
154      if (pt.length == 1) {
155         args[0] = pt[0] == String.class ? s(value) : value;
156      } else {
157         if (name == null)
158            throw uoex("Constructor for type %s requires a name as the first argument.", cn(type));
159         args[0] = name;
160         args[1] = pt[1] == String.class ? s(value) : value;
161      }
162
163      try {
164         return constructor.newInstance(args);
165      } catch (Exception e) {
166         throw toRex(e);
167      }
168   }
169
170   /**
171    * Returns schema information about this part.
172    *
173    * <p>
174    * This is information pulled from {@link Query @Query}, {@link FormData @FormData}, or {@link Path @Path} annotations
175    * on the class.
176    *
177    * @return The schema information.
178    */
179   public HttpPartSchema getSchema() { return schema; }
180}