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.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 Lists.
029 *
030 * <p>
031 * Looks for methods on the class that can be called to swap-in surrogate List objects before serialization and swap-out
032 * surrogate List objects after parsing.
033 *
034 * <h5 class='figure'>Valid surrogate objects</h5>
035 * <ul>
036 *    <li class='jc'>Any subclass of {@link List}
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 toList()</c>
042 *    <li class='jm'><c><jk>public</jk> S toList(BeanSession)</c>
043 *    <li class='jm'><c><jk>public</jk> S toOList()</c>
044 *    <li class='jm'><c><jk>public</jk> S toOList(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 fromList(S)</c>
050 *    <li class='jm'><c><jk>public static</jk> N fromList(BeanSession, S)</c>
051 *    <li class='jm'><c><jk>public static</jk> N fromOList(S)</c>
052 *    <li class='jm'><c><jk>public static</jk> N fromOList(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 AutoListSwap<T> extends PojoSwap<T,List<?>> {
077
078   private static final Set<String>
079      SWAP_METHOD_NAMES = ASet.unmodifiable("toList", "toObjectList", "toOList"),
080      UNSWAP_METHOD_NAMES = ASet.unmodifiable("fromList", "fromObjectList", "fromOList", "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 bc The bean context to use for looking up annotations.
086    * @param ci The class to try to constructor a dynamic swap on.
087    * @return A POJO swap instance, or <jk>null</jk> if one could not be created.
088    */
089   @SuppressWarnings({ "rawtypes" })
090   public static PojoSwap<?,?> find(BeanContext bc, ClassInfo ci) {
091
092      if (shouldIgnore(bc, ci))
093         return null;
094
095      // Find swap() method if present.
096      for (MethodInfo m : ci.getAllMethods()) {
097         if (isSwapMethod(bc, m)) {
098
099            ClassInfo rt = m.getReturnType();
100
101            for (MethodInfo m2 : ci.getAllMethods())
102               if (isUnswapMethod(bc, m2, ci, rt))
103                  return new AutoListSwap(bc, ci, m, m2, null);
104
105            for (ConstructorInfo cs : ci.getDeclaredConstructors())
106               if (isUnswapConstructor(bc, cs, rt))
107                  return new AutoListSwap(bc, ci, m, null, cs);
108
109            return new AutoListSwap(bc, ci, m, null, null);
110         }
111      }
112
113      return null;
114   }
115
116   private static boolean shouldIgnore(BeanContext bc, ClassInfo ci) {
117      return
118         bc.hasAnnotation(BeanIgnore.class, ci)
119         || ci.isNonStaticMemberClass();
120   }
121
122   private static boolean isSwapMethod(BeanContext bc, MethodInfo mi) {
123      return
124         mi.isNotDeprecated()
125         && mi.isNotStatic()
126         && mi.isVisible(bc.getBeanMethodVisibility())
127         && mi.hasName(SWAP_METHOD_NAMES)
128         && mi.hasReturnTypeParent(List.class)
129         && mi.hasFuzzyParamTypes(BeanSession.class)
130         && ! bc.hasAnnotation(BeanIgnore.class, mi);
131   }
132
133   private static boolean isUnswapMethod(BeanContext bc, MethodInfo mi, ClassInfo ci, ClassInfo rt) {
134      return
135         mi.isNotDeprecated()
136         && mi.isStatic()
137         && mi.isVisible(bc.getBeanMethodVisibility())
138         && mi.hasName(UNSWAP_METHOD_NAMES)
139         && mi.hasFuzzyParamTypes(BeanSession.class, rt.inner())
140         && mi.hasReturnTypeParent(ci)
141         && ! bc.hasAnnotation(BeanIgnore.class, mi);
142   }
143
144   private static boolean isUnswapConstructor(BeanContext bc, ConstructorInfo cs, ClassInfo rt) {
145      return
146         cs.isNotDeprecated()
147         && cs.isVisible(bc.getBeanConstructorVisibility())
148         && cs.hasMatchingParamTypes(rt)
149         && ! bc.hasAnnotation(BeanIgnore.class, cs);
150   }
151
152   //------------------------------------------------------------------------------------------------------------------
153
154   private final Method swapMethod, unswapMethod;
155   private final Constructor<?> unswapConstructor;
156
157   private AutoListSwap(BeanContext bc, ClassInfo ci, MethodInfo swapMethod, MethodInfo unswapMethod, ConstructorInfo unswapConstructor) {
158      super(ci.inner(), swapMethod.getReturnType().inner());
159      this.swapMethod = bc.getBeanMethodVisibility().transform(swapMethod.inner());
160      this.unswapMethod = unswapMethod == null ? null : bc.getBeanMethodVisibility().transform(unswapMethod.inner());
161      this.unswapConstructor = unswapConstructor == null ? null : bc.getBeanConstructorVisibility().transform(unswapConstructor.inner());
162   }
163
164   @Override /* PojoSwap */
165   public List<?> swap(BeanSession session, Object o) throws SerializeException {
166      try {
167         return (List<?>)swapMethod.invoke(o, getMatchingArgs(swapMethod.getParameterTypes(), session));
168      } catch (Exception e) {
169         throw SerializeException.create(e);
170      }
171   }
172
173   @SuppressWarnings("unchecked")
174   @Override /* PojoSwap */
175   public T unswap(BeanSession session, List<?> o, ClassMeta<?> hint) throws ParseException {
176      try {
177         if (unswapMethod != null)
178            return (T)unswapMethod.invoke(null, getMatchingArgs(unswapMethod.getParameterTypes(), session, o));
179         if (unswapConstructor != null)
180            return (T)unswapConstructor.newInstance(o);
181         return super.unswap(session, o, hint);
182      } catch (Exception e) {
183         throw ParseException.create(e);
184      }
185   }
186}