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.*;
016
017import java.lang.reflect.*;
018import java.util.*;
019
020import org.apache.juneau.*;
021import org.apache.juneau.annotation.*;
022import org.apache.juneau.collections.*;
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 = ASet.unmodifiable("toNumber", "toInteger", "toInt", "toLong", "toFloat", "toDouble", "toShort", "toByte"),
103      UNSWAP_METHOD_NAMES = ASet.unmodifiable("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 bc The bean context to use for looking up annotations.
109    * @param ci The class to try to constructor a dynamic swap on.
110    * @return A POJO swap instance, or <jk>null</jk> if one could not be created.
111    */
112   @SuppressWarnings({ "rawtypes" })
113   public static PojoSwap<?,?> find(BeanContext bc, ClassInfo ci) {
114
115      if (shouldIgnore(bc, ci))
116         return null;
117
118      // Find swap() method if present.
119      for (MethodInfo m : ci.getAllMethods()) {
120
121         if (isSwapMethod(bc, m)) {
122
123            ClassInfo rt = m.getReturnType();
124
125            for (MethodInfo m2 : ci.getAllMethods())
126               if (isUnswapMethod(bc, m2, ci, rt))
127                  return new AutoNumberSwap(bc, ci, m, m2, null);
128
129            for (ConstructorInfo cs : ci.getDeclaredConstructors())
130               if (isUnswapConstructor(bc, cs, rt))
131                  return new AutoNumberSwap(bc, ci, m, null, cs);
132
133            return new AutoNumberSwap(bc, ci, m, null, null);
134         }
135      }
136
137      return null;
138   }
139
140   private static boolean shouldIgnore(BeanContext bc, ClassInfo ci) {
141      return
142         bc.hasAnnotation(BeanIgnore.class, ci)
143         || ci.isNonStaticMemberClass()
144         || ci.isPrimitive()
145         || ci.isChildOf(Number.class);
146   }
147
148   private static boolean isSwapMethod(BeanContext bc, MethodInfo mi) {
149      ClassInfo rt = mi.getReturnType();
150      return
151         mi.isNotDeprecated()
152         && mi.isNotStatic()
153         && mi.isVisible(bc.getBeanMethodVisibility())
154         && (rt.isChildOf(Number.class) || (rt.isPrimitive() && rt.isAny(int.class, short.class, long.class, float.class, double.class, byte.class)))
155         && mi.hasName(SWAP_METHOD_NAMES)
156         && mi.hasFuzzyParamTypes(BeanSession.class)
157         && ! bc.hasAnnotation(BeanIgnore.class, mi);
158   }
159
160   private static boolean isUnswapMethod(BeanContext bc, MethodInfo mi, ClassInfo ci, ClassInfo rt) {
161      return
162         mi.isNotDeprecated()
163         && mi.isStatic()
164         && mi.isVisible(bc.getBeanMethodVisibility())
165         && mi.hasName(UNSWAP_METHOD_NAMES)
166         && mi.hasFuzzyParamTypes(BeanSession.class, rt.inner())
167         && mi.hasReturnTypeParent(ci)
168         && ! bc.hasAnnotation(BeanIgnore.class, mi);
169   }
170
171   private static boolean isUnswapConstructor(BeanContext bc, ConstructorInfo cs, ClassInfo rt) {
172      return
173         cs.isNotDeprecated()
174         && cs.isVisible(bc.getBeanConstructorVisibility())
175         && cs.hasMatchingParamTypes(rt)
176         && ! bc.hasAnnotation(BeanIgnore.class, cs);
177   }
178
179   //------------------------------------------------------------------------------------------------------------------
180
181   private final Method swapMethod, unswapMethod;
182   private final Constructor<?> unswapConstructor;
183   private final Class<?> unswapType;
184
185   private AutoNumberSwap(BeanContext bc, ClassInfo ci, MethodInfo swapMethod, MethodInfo unswapMethod, ConstructorInfo unswapConstructor) {
186      super(ci.inner(), swapMethod.inner().getReturnType());
187      this.swapMethod = bc.getBeanMethodVisibility().transform(swapMethod.inner());
188      this.unswapMethod = unswapMethod == null ? null : bc.getBeanMethodVisibility().transform(unswapMethod.inner());
189      this.unswapConstructor = unswapConstructor == null ? null : bc.getBeanConstructorVisibility().transform(unswapConstructor.inner());
190
191      Class<?> unswapType = null;
192      if (unswapMethod != null) {
193         for (ParamInfo pi : unswapMethod.getParams())
194            if (! pi.getParameterType().is(BeanSession.class))
195               unswapType = pi.getParameterType().getWrapperIfPrimitive();
196      } else if (unswapConstructor != null) {
197         for (ParamInfo pi : unswapConstructor.getParams())
198            if (! pi.getParameterType().is(BeanSession.class))
199               unswapType = pi.getParameterType().getWrapperIfPrimitive();
200      }
201      this.unswapType = unswapType;
202   }
203
204   @Override /* PojoSwap */
205   public Number swap(BeanSession session, Object o) throws SerializeException {
206      try {
207         return (Number)swapMethod.invoke(o, getMatchingArgs(swapMethod.getParameterTypes(), session));
208      } catch (Exception e) {
209         throw SerializeException.create(e);
210      }
211   }
212
213   @SuppressWarnings("unchecked")
214   @Override /* PojoSwap */
215   public T unswap(BeanSession session, Number o, ClassMeta<?> hint) throws ParseException {
216      if (unswapType == null)
217         throw new ParseException("No unparse methodology found for object.");
218      try {
219         Object o2 = ConverterUtils.toType(o, unswapType);
220         if (unswapMethod != null)
221            return (T)unswapMethod.invoke(null, getMatchingArgs(unswapMethod.getParameterTypes(), session, o2));
222         if (unswapConstructor != null)
223            return (T)unswapConstructor.newInstance(o2);
224         return super.unswap(session, o, hint);
225      } catch (Exception e) {
226         throw ParseException.create(e);
227      }
228   }
229}