/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * Subscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.template.freemarker.internal;

import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringUtil;

import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.InvalidPropertyException;
import freemarker.ext.beans.StringModel;

import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

import java.util.Set;

/**
 * @author Marta Medio
 */
public class LiferayFreeMarkerStringModel extends StringModel {

	public LiferayFreeMarkerStringModel(Object object, BeansWrapper wrapper) {
		super(object, wrapper);
	}

	@Override
	public TemplateModel get(String key) throws TemplateModelException {
		if (_restrictedMethodNames == null) {
			throw new InvalidPropertyException(
				StringBundler.concat(
					"Denied access to method or field ", key, " of ",
					object.getClass().getName()));
		}

		String methodOrFieldName = StringUtil.toLowerCase(key);

		for (String restrictedMethodName : _restrictedMethodNames) {
			if (restrictedMethodName.endsWith(methodOrFieldName)) {
				Class<?> clazz = object.getClass();

				throw new InvalidPropertyException(
					StringBundler.concat(
						"Denied access to method or field ", key, " of ",
						clazz.getName()));
			}
		}

		return super.get(key);
	}

	public void setRestrictedMethodNames(Set<String> restrictedMethodNames) {
		_restrictedMethodNames = restrictedMethodNames;
	}

	private Set<String> _restrictedMethodNames;

}