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