001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.platform.rendering.fm.extensions;
023
024import java.lang.reflect.Constructor;
025import java.util.List;
026
027import freemarker.template.TemplateMethodModelEx;
028import freemarker.template.TemplateModelException;
029
030/**
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033public class NewMethod implements TemplateMethodModelEx {
034
035    @Override
036    public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {
037        int size = arguments.size();
038        if (size < 1) {
039            throw new TemplateModelException("Invalid number of arguments for new(class, ...) method");
040        }
041
042        Class<?> klass;
043        try {
044            String className = (String) arguments.get(0);
045            klass = Class.forName(className);
046            if (size == 1) {
047                return klass.getDeclaredConstructor().newInstance();
048            }
049        } catch (ReflectiveOperationException e) {
050            throw new TemplateModelException("Failed to isntantiate the object", e);
051        }
052        arguments.remove(0);
053        Object[] ar = arguments.toArray();
054        size--;
055        Constructor<?>[] ctors = klass.getConstructors();
056        for (Constructor<?> ctor : ctors) {
057            Class<?>[] params = ctor.getParameterTypes(); // this is cloning params
058            if (params.length == size) { // try this one
059                try {
060                    return ctor.newInstance(ar);
061                } catch (ReflectiveOperationException e) {
062                    // continue
063                }
064            }
065        }
066        throw new TemplateModelException("No suitable constructor found");
067    }
068
069}