001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.freemarker;
016    
017    import com.liferay.portal.security.pacl.PACLClassLoaderUtil;
018    
019    import freemarker.ext.beans.BeansWrapper;
020    
021    import freemarker.template.TemplateMethodModelEx;
022    import freemarker.template.TemplateModelException;
023    
024    import java.util.List;
025    
026    /**
027     * @author Raymond Augé
028     */
029    public class LiferayObjectConstructor implements TemplateMethodModelEx {
030    
031            public Object exec(@SuppressWarnings("rawtypes") List arguments)
032                    throws TemplateModelException {
033    
034                    if (arguments.isEmpty()) {
035                            throw new TemplateModelException(
036                                    "This method must have at least one argument as the name of " +
037                                            "the class to instantiate");
038                    }
039    
040                    Class<?> clazz = null;
041    
042                    try {
043                            String className = String.valueOf(arguments.get(0));
044    
045                            clazz = Class.forName(
046                                    className, true, PACLClassLoaderUtil.getContextClassLoader());
047                    }
048                    catch (Exception e) {
049                            throw new TemplateModelException(e.getMessage());
050                    }
051    
052                    BeansWrapper beansWrapper = BeansWrapper.getDefaultInstance();
053    
054                    Object object = beansWrapper.newInstance(
055                            clazz, arguments.subList(1, arguments.size()));
056    
057                    return beansWrapper.wrap(object);
058            }
059    
060    }