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