001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.collections4.functors;
018
019import java.lang.reflect.InvocationTargetException;
020import java.lang.reflect.Method;
021
022import org.apache.commons.collections4.FunctorException;
023import org.apache.commons.collections4.Transformer;
024
025/**
026 * Transformer implementation that creates a new object instance by reflection.
027 * <p>
028 * <b>WARNING:</b> from v4.1 onwards this class will <b>not</b> be serializable anymore
029 * in order to prevent potential remote code execution exploits. Please refer to
030 * <a href="https://issues.apache.org/jira/browse/COLLECTIONS-580">COLLECTIONS-580</a>
031 * for more details.
032 *
033 * @since 3.0
034 */
035public class InvokerTransformer<I, O> implements Transformer<I, O> {
036
037    /** The method name to call */
038    private final String iMethodName;
039    /** The array of reflection parameter types */
040    private final Class<?>[] iParamTypes;
041    /** The array of reflection arguments */
042    private final Object[] iArgs;
043
044    /**
045     * Gets an instance of this transformer calling a specific method with no arguments.
046     *
047     * @param <I>  the input type
048     * @param <O>  the output type
049     * @param methodName  the method name to call
050     * @return an invoker transformer
051     * @throws NullPointerException if methodName is null
052     * @since 3.1
053     */
054    public static <I, O> Transformer<I, O> invokerTransformer(final String methodName) {
055        if (methodName == null) {
056            throw new NullPointerException("The method to invoke must not be null");
057        }
058        return new InvokerTransformer<>(methodName);
059    }
060
061    /**
062     * Gets an instance of this transformer calling a specific method with specific values.
063     *
064     * @param <I>  the input type
065     * @param <O>  the output type
066     * @param methodName  the method name to call
067     * @param paramTypes  the parameter types of the method
068     * @param args  the arguments to pass to the method
069     * @return an invoker transformer
070     * @throws NullPointerException if methodName is null
071     * @throws IllegalArgumentException if paramTypes does not match args
072     */
073    public static <I, O> Transformer<I, O> invokerTransformer(final String methodName, final Class<?>[] paramTypes,
074                                                              final Object[] args) {
075        if (methodName == null) {
076            throw new NullPointerException("The method to invoke must not be null");
077        }
078        if (((paramTypes == null) && (args != null))
079            || ((paramTypes != null) && (args == null))
080            || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) {
081            throw new IllegalArgumentException("The parameter types must match the arguments");
082        }
083        if (paramTypes == null || paramTypes.length == 0) {
084            return new InvokerTransformer<>(methodName);
085        }
086        return new InvokerTransformer<>(methodName, paramTypes, args);
087    }
088
089    /**
090     * Constructor for no arg instance.
091     *
092     * @param methodName  the method to call
093     */
094    private InvokerTransformer(final String methodName) {
095        super();
096        iMethodName = methodName;
097        iParamTypes = null;
098        iArgs = null;
099    }
100
101    /**
102     * Constructor that performs no validation.
103     * Use <code>invokerTransformer</code> if you want that.
104     * <p>
105     * Note: from 4.0, the input parameters will be cloned
106     *
107     * @param methodName  the method to call
108     * @param paramTypes  the constructor parameter types
109     * @param args  the constructor arguments
110     */
111    public InvokerTransformer(final String methodName, final Class<?>[] paramTypes, final Object[] args) {
112        super();
113        iMethodName = methodName;
114        iParamTypes = paramTypes != null ? paramTypes.clone() : null;
115        iArgs = args != null ? args.clone() : null;
116    }
117
118    /**
119     * Transforms the input to result by invoking a method on the input.
120     *
121     * @param input  the input object to transform
122     * @return the transformed result, null if null input
123     */
124    @Override
125    @SuppressWarnings("unchecked")
126    public O transform(final Object input) {
127        if (input == null) {
128            return null;
129        }
130        try {
131            final Class<?> cls = input.getClass();
132            final Method method = cls.getMethod(iMethodName, iParamTypes);
133            return (O) method.invoke(input, iArgs);
134        } catch (final NoSuchMethodException ex) {
135            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
136                                       input.getClass() + "' does not exist");
137        } catch (final IllegalAccessException ex) {
138            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
139                                       input.getClass() + "' cannot be accessed");
140        } catch (final InvocationTargetException ex) {
141            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
142                                       input.getClass() + "' threw an exception", ex);
143        }
144    }
145
146}