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