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