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 *      https://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;
021import java.util.Objects;
022
023import org.apache.commons.collections4.FunctorException;
024import org.apache.commons.collections4.Transformer;
025
026/**
027 * Transformer implementation that creates a new object instance by reflection.
028 * <p>
029 * <strong>WARNING:</strong> from v4.1 onwards this class will <strong>not</strong> be serializable anymore
030 * in order to prevent potential remote code execution exploits. Please refer to
031 * <a href="https://issues.apache.org/jira/browse/COLLECTIONS-580">COLLECTIONS-580</a>
032 * for more details.
033 * </p>
034 *
035 * @param <T> The type of the input to the function.
036 * @param <R> The type of the result of the function.
037 * @since 3.0
038 */
039public class InvokerTransformer<T, R> implements Transformer<T, R> {
040
041    /**
042     * Gets an instance of this transformer calling a specific method with no arguments.
043     *
044     * @param <I>  the input type
045     * @param <O>  the output type
046     * @param methodName  The method name to call
047     * @return An invoker transformer
048     * @throws NullPointerException if methodName is null
049     * @since 3.1
050     */
051    public static <I, O> Transformer<I, O> invokerTransformer(final String methodName) {
052        return new InvokerTransformer<>(Objects.requireNonNull(methodName, "methodName"));
053    }
054
055    /**
056     * Gets an instance of this transformer calling a specific method with specific values.
057     *
058     * @param <I>  the input type
059     * @param <O>  the output type
060     * @param methodName  The method name to call
061     * @param paramTypes  The parameter types of the method
062     * @param args  The arguments to pass to the method
063     * @return An invoker transformer
064     * @throws NullPointerException if methodName is null
065     * @throws IllegalArgumentException if paramTypes does not match args
066     */
067    public static <I, O> Transformer<I, O> invokerTransformer(final String methodName, final Class<?>[] paramTypes,
068                                                              final Object[] args) {
069        Objects.requireNonNull(methodName, "methodName");
070        if (paramTypes == null && args != null
071            || paramTypes != null && args == null
072            || paramTypes != null && args != null && paramTypes.length != args.length) {
073            throw new IllegalArgumentException("The parameter types must match the arguments");
074        }
075        if (paramTypes == null || paramTypes.length == 0) {
076            return new InvokerTransformer<>(methodName);
077        }
078        return new InvokerTransformer<>(methodName, paramTypes, args);
079    }
080
081    /** The method name to call */
082    private final String iMethodName;
083
084    /** The array of reflection parameter types */
085    private final Class<?>[] iParamTypes;
086
087    /** The array of reflection arguments */
088    private final Object[] iArgs;
089
090    /**
091     * Constructor for no arg instance.
092     *
093     * @param methodName  The method to call
094     */
095    private InvokerTransformer(final String methodName) {
096        iMethodName = methodName;
097        iParamTypes = null;
098        iArgs = null;
099    }
100
101    /**
102     * Constructor that performs no validation.
103     * Use {@code invokerTransformer} 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        iMethodName = methodName;
113        iParamTypes = paramTypes != null ? paramTypes.clone() : null;
114        iArgs = args != null ? args.clone() : null;
115    }
116
117    /**
118     * Transforms the input to result by invoking a method on the input.
119     *
120     * @param input  The input object to transform
121     * @return The transformed result, null if null input
122     */
123    @Override
124    @SuppressWarnings("unchecked")
125    public R transform(final Object input) {
126        if (input == null) {
127            return null;
128        }
129        try {
130            final Class<?> cls = input.getClass();
131            final Method method = cls.getMethod(iMethodName, iParamTypes);
132            return (R) method.invoke(input, iArgs);
133        } catch (final NoSuchMethodException ex) {
134            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
135                                       input.getClass() + "' does not exist");
136        } catch (final IllegalAccessException ex) {
137            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
138                                       input.getClass() + "' cannot be accessed");
139        } catch (final InvocationTargetException ex) {
140            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
141                                       input.getClass() + "' threw an exception", ex);
142        }
143    }
144
145}