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