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.transform;
014
015import static org.apache.juneau.internal.ClassUtils.*;
016import static org.apache.juneau.internal.CollectionUtils.*;
017
018import java.lang.reflect.*;
019import java.util.*;
020
021import org.apache.juneau.*;
022import org.apache.juneau.annotation.*;
023import org.apache.juneau.parser.*;
024import org.apache.juneau.reflect.*;
025import org.apache.juneau.serializer.*;
026
027/**
028 * A dynamic POJO swap based on reflection of a Java class that converts POJOs to serializable Maps.
029 *
030 * <p>
031 * Looks for methods on the class that can be called to swap-in surrogate Map objects before serialization and swap-out
032 * surrogate Map objects after parsing.
033 *
034 * <h5 class='figure'>Valid surrogate objects</h5>
035 * <ul>
036 *    <li class='jc'>Any subclass of {@link Map}
037 * </ul>
038 *
039 * <h5 class='figure'>Valid swap methods (S = Swapped type)</h5>
040 * <ul>
041 *    <li class='jm'><c><jk>public</jk> S toMap()</c>
042 *    <li class='jm'><c><jk>public</jk> S toMap(BeanSession)</c>
043 *    <li class='jm'><c><jk>public</jk> S toObjectMap()</c>
044 *    <li class='jm'><c><jk>public</jk> S toObjectMap(BeanSession)</c>
045 * </ul>
046 *
047 * <h5 class='figure'>Valid unswap methods (N = Normal type, S = Swapped type)</h5>
048 * <ul>
049 *    <li class='jm'><c><jk>public static</jk> N fromMap(S)</c>
050 *    <li class='jm'><c><jk>public static</jk> N fromMap(BeanSession, S)</c>
051 *    <li class='jm'><c><jk>public static</jk> N fromObjectMap(S)</c>
052 *    <li class='jm'><c><jk>public static</jk> N fromObjectMap(BeanSession, S)</c>
053 *    <li class='jm'><c><jk>public static</jk> N create(S)</c>
054 *    <li class='jm'><c><jk>public static</jk> N create(BeanSession, S)</c>
055 *    <li class='jm'><c><jk>public static</jk> N valueOf(S)</c>
056 *    <li class='jm'><c><jk>public static</jk> N valueOf(BeanSession, S)</c>
057 *    <li class='jm'><c><jk>public</jk> N(S)</c>
058 * </ul>
059 *
060 * <p>
061 * Classes are ignored if any of the following are true:
062 * <ul>
063 *    <li>Classes annotated with {@link BeanIgnore @BeanIgnore}.
064 *    <li>Non-static member classes.
065 * </ul>
066 *
067 * <p>
068 * Members/constructors are ignored if any of the following are true:
069 * <ul>
070 *    <li>Members/constructors annotated with {@link BeanIgnore @BeanIgnore}.
071 *    <li>Deprecated members/constructors.
072 * </ul>
073 *
074 * @param <T> The normal class type.
075 */
076public class AutoMapSwap<T> extends PojoSwap<T,Map<?,?>> {
077
078   private static final Set<String>
079      SWAP_METHOD_NAMES = newUnmodifiableHashSet("toMap", "toObjectMap"),
080      UNSWAP_METHOD_NAMES = newUnmodifiableHashSet("fromMap", "fromObjectMap", "create", "valueOf");
081
082   /**
083    * Look for constructors and methods on this class and construct a dynamic swap if it's possible to do so.
084    *
085    * @param ci The class to try to constructor a dynamic swap on.
086    * @return A POJO swap instance, or <jk>null</jk> if one could not be created.
087    */
088   @SuppressWarnings({ "rawtypes" })
089   public static PojoSwap<?,?> find(ClassInfo ci) {
090
091      if (shouldIgnore(ci))
092         return null;
093
094      // Find swap() method if present.
095      for (MethodInfo m : ci.getPublicMethods()) {
096         if (isSwapMethod(m)) {
097
098            ClassInfo rt = m.getReturnType();
099
100            for (MethodInfo m2 : ci.getPublicMethods())
101               if (isUnswapMethod(m2, ci, rt))
102                  return new AutoMapSwap(ci, m, m2, null);
103
104            for (ConstructorInfo cs : ci.getPublicConstructors())
105               if (isUnswapConstructor(cs, rt))
106                  return new AutoMapSwap(ci, m, null, cs);
107
108            return new AutoMapSwap(ci, m, null, null);
109         }
110      }
111
112      return null;
113   }
114
115   private static boolean shouldIgnore(ClassInfo ci) {
116      return
117         ci.hasAnnotation(BeanIgnore.class)
118         || ci.isNonStaticMemberClass();
119   }
120
121   private static boolean isSwapMethod(MethodInfo mi) {
122      return
123         mi.isNotDeprecated()
124         && mi.isNotStatic()
125         && mi.hasName(SWAP_METHOD_NAMES)
126         && mi.hasReturnTypeParent(Map.class)
127         && mi.hasFuzzyParamTypes(BeanSession.class)
128         && ! mi.hasAnnotation(BeanIgnore.class);
129   }
130
131   private static boolean isUnswapMethod(MethodInfo mi, ClassInfo ci, ClassInfo rt) {
132      return
133         mi.isNotDeprecated()
134         && mi.isStatic()
135         && mi.hasName(UNSWAP_METHOD_NAMES)
136         && mi.hasFuzzyParamTypes(BeanSession.class, rt.inner())
137         && mi.hasReturnTypeParent(ci)
138         && ! mi.hasAnnotation(BeanIgnore.class);
139   }
140
141   private static boolean isUnswapConstructor(ConstructorInfo cs, ClassInfo rt) {
142      return
143         cs.isNotDeprecated()
144         && cs.hasParamTypeParents(rt)
145         && ! cs.hasAnnotation(BeanIgnore.class);
146   }
147
148   //------------------------------------------------------------------------------------------------------------------
149
150   private final Method swapMethod, unswapMethod;
151   private final Constructor<?> unswapConstructor;
152
153   private AutoMapSwap(ClassInfo ci, MethodInfo swapMethod, MethodInfo unswapMethod, ConstructorInfo unswapConstructor) {
154      super(ci.inner(), swapMethod.inner().getReturnType());
155      this.swapMethod = swapMethod.inner();
156      this.unswapMethod = unswapMethod == null ? null : unswapMethod.inner();
157      this.unswapConstructor = unswapConstructor == null ? null : unswapConstructor.inner();
158   }
159
160   @Override /* PojoSwap */
161   public Map<?,?> swap(BeanSession session, Object o) throws SerializeException {
162      try {
163         return (Map<?,?>)swapMethod.invoke(o, getMatchingArgs(swapMethod.getParameterTypes(), session));
164      } catch (Exception e) {
165         throw SerializeException.create(e);
166      }
167   }
168
169   @SuppressWarnings("unchecked")
170   @Override /* PojoSwap */
171   public T unswap(BeanSession session, Map<?,?> o, ClassMeta<?> hint) throws ParseException {
172      try {
173         if (unswapMethod != null)
174            return (T)unswapMethod.invoke(null, getMatchingArgs(unswapMethod.getParameterTypes(), session, o));
175         if (unswapConstructor != null)
176            return (T)unswapConstructor.newInstance(o);
177         return super.unswap(session, o, hint);
178      } catch (Exception e) {
179         throw ParseException.create(e);
180      }
181   }
182}