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.parser.*;
023import org.apache.juneau.serializer.*;
024
025/**
026 * Specialized {@link PojoSwap} for {@link Surrogate} classes.
027 *
028 * @param <T> The class type that this transform applies to.
029 * @param <F> The transformed class type.
030 */
031public class SurrogateSwap<T,F> extends PojoSwap<T,F> {
032
033   private Constructor<F> constructor;   // public F(T t);
034   private Method unswapMethod;        // public T build();
035
036   /**
037    * Constructor.
038    *
039    * @param forClass The normal class.
040    * @param constructor The constructor on the surrogate class that takes the normal class as a parameter.
041    * @param unswapMethod The static method that converts surrogate objects into normal objects.
042    */
043   protected SurrogateSwap(Class<T> forClass, Constructor<F> constructor, Method unswapMethod) {
044      super(forClass, constructor.getDeclaringClass());
045      this.constructor = constructor;
046      this.unswapMethod = unswapMethod;
047   }
048
049   /**
050    * Given the specified surrogate class, return the list of POJO swaps.
051    *
052    * <p>
053    * A transform is returned for each public 1-arg constructor found.
054    * Returns an empty list if no public 1-arg constructors are found.
055    *
056    * @param c The surrogate class.
057    * @return The list of POJO swaps that apply to this class.
058    */
059   @SuppressWarnings({"unchecked", "rawtypes"})
060   public static List<SurrogateSwap<?,?>> findPojoSwaps(Class<?> c) {
061      List<SurrogateSwap<?,?>> l = new LinkedList<>();
062      for (Constructor<?> cc : c.getConstructors()) {
063         Class<?>[] pt = cc.getParameterTypes();
064         if (cc.getAnnotation(BeanIgnore.class) == null && hasNumArgs(cc, 1) && isPublic(cc) && pt[0] != c.getDeclaringClass()) {
065            // Find the unswap method if there is one.
066            Method unswapMethod = null;
067            for (Method m : c.getMethods()) {
068               if (pt[0].equals(m.getReturnType()) && isPublic(m))
069               unswapMethod = m;
070            }
071
072            l.add(new SurrogateSwap(pt[0], cc, unswapMethod));
073         }
074      }
075      return l;
076   }
077
078   @Override /* PojoSwap */
079   public F swap(BeanSession session, T o) throws SerializeException {
080      try {
081         return constructor.newInstance(o);
082      } catch (Exception e) {
083         throw new SerializeException(e);
084      }
085   }
086
087   @Override /* PojoSwap */
088   @SuppressWarnings("unchecked")
089   public T unswap(BeanSession session, F f, ClassMeta<?> hint) throws ParseException {
090      if (unswapMethod == null)
091         throw new ParseException("unswap() method not implement on surrogate class ''{1}''",
092            f.getClass().getName(), getNormalClass().getName());
093      try {
094         return (T)unswapMethod.invoke(f);
095      } catch (Exception e) {
096         throw new ParseException((Throwable)e);
097      }
098   }
099}