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