Search in sources :

Example 31 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class BeanModel method invokeThroughDescriptor.

private TemplateModel invokeThroughDescriptor(Object desc, Map<Object, Object> classInfo) throws IllegalAccessException, InvocationTargetException, TemplateModelException {
    // See if this particular instance has a cached implementation for the requested feature descriptor
    TemplateModel cachedModel;
    synchronized (this) {
        cachedModel = memberCache != null ? memberCache.get(desc) : null;
    }
    if (cachedModel != null) {
        return cachedModel;
    }
    TemplateModel resultModel = UNKNOWN;
    if (desc instanceof FastPropertyDescriptor) {
        FastPropertyDescriptor pd = (FastPropertyDescriptor) desc;
        Method indexedReadMethod = pd.getIndexedReadMethod();
        if (indexedReadMethod != null) {
            if (!wrapper.getPreferIndexedReadMethod() && (pd.getReadMethod()) != null) {
                resultModel = wrapper.invokeMethod(object, pd.getReadMethod(), null);
            // cachedModel remains null, as we don't cache these
            } else {
                resultModel = cachedModel = new SimpleMethodModel(object, indexedReadMethod, ClassIntrospector.getArgTypes(classInfo, indexedReadMethod), wrapper);
            }
        } else {
            resultModel = wrapper.invokeMethod(object, pd.getReadMethod(), null);
        // cachedModel remains null, as we don't cache these
        }
    } else if (desc instanceof Field) {
        resultModel = wrapper.wrap(((Field) desc).get(object));
    // cachedModel remains null, as we don't cache these
    } else if (desc instanceof Method) {
        Method method = (Method) desc;
        resultModel = cachedModel = new SimpleMethodModel(object, method, ClassIntrospector.getArgTypes(classInfo, method), wrapper);
    } else if (desc instanceof OverloadedMethods) {
        resultModel = cachedModel = new OverloadedMethodsModel(object, (OverloadedMethods) desc, wrapper);
    }
    // If new cachedModel was created, cache it
    if (cachedModel != null) {
        synchronized (this) {
            if (memberCache == null) {
                memberCache = new HashMap<Object, TemplateModel>();
            }
            memberCache.put(desc, cachedModel);
        }
    }
    return resultModel;
}
Also used : Field(java.lang.reflect.Field) AdapterTemplateModel(freemarker.template.AdapterTemplateModel) WrapperTemplateModel(freemarker.ext.util.WrapperTemplateModel) TemplateModel(freemarker.template.TemplateModel) Method(java.lang.reflect.Method)

Example 32 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class ModelCache method getInstance.

public TemplateModel getInstance(Object object) {
    if (object instanceof TemplateModel) {
        return (TemplateModel) object;
    }
    if (object instanceof TemplateModelAdapter) {
        return ((TemplateModelAdapter) object).getTemplateModel();
    }
    if (useCache && isCacheable(object)) {
        TemplateModel model = lookup(object);
        if (model == null) {
            model = create(object);
            register(model, object);
        }
        return model;
    } else {
        return create(object);
    }
}
Also used : TemplateModel(freemarker.template.TemplateModel) TemplateModelAdapter(freemarker.template.TemplateModelAdapter)

Example 33 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class JythonModelCache method create.

@Override
protected TemplateModel create(Object obj) {
    boolean asHash = false;
    boolean asSequence = false;
    JythonVersionAdapter versionAdapter = JythonVersionAdapterHolder.INSTANCE;
    if (versionAdapter.isPyInstance(obj)) {
        Object jobj = versionAdapter.pyInstanceToJava(obj);
        // FreeMarker-aware, Jython-wrapped Java objects are left intact
        if (jobj instanceof TemplateModel) {
            return (TemplateModel) jobj;
        }
        if (jobj instanceof Map) {
            asHash = true;
        }
        if (jobj instanceof Date) {
            return new DateModel((Date) jobj, BeansWrapper.getDefaultInstance());
        } else if (jobj instanceof Collection) {
            asSequence = true;
            // doesn't support sets.
            if (!(jobj instanceof List)) {
                obj = new ArrayList((Collection) jobj);
            }
        }
    }
    // If it's not a PyObject, first make a PyObject out of it.
    if (!(obj instanceof PyObject)) {
        obj = Py.java2py(obj);
    }
    if (asHash || obj instanceof PyDictionary || obj instanceof PyStringMap) {
        return JythonHashModel.FACTORY.create(obj, wrapper);
    }
    if (asSequence || obj instanceof PySequence) {
        return JythonSequenceModel.FACTORY.create(obj, wrapper);
    }
    if (obj instanceof PyInteger || obj instanceof PyLong || obj instanceof PyFloat) {
        return JythonNumberModel.FACTORY.create(obj, wrapper);
    }
    if (obj instanceof PyNone) {
        return null;
    }
    return JythonModel.FACTORY.create(obj, wrapper);
}
Also used : DateModel(freemarker.ext.beans.DateModel) ArrayList(java.util.ArrayList) PyFloat(org.python.core.PyFloat) TemplateModel(freemarker.template.TemplateModel) PyInteger(org.python.core.PyInteger) PyDictionary(org.python.core.PyDictionary) Date(java.util.Date) PyNone(org.python.core.PyNone) PyLong(org.python.core.PyLong) PyStringMap(org.python.core.PyStringMap) Collection(java.util.Collection) PyObject(org.python.core.PyObject) ArrayList(java.util.ArrayList) List(java.util.List) PySequence(org.python.core.PySequence) PyStringMap(org.python.core.PyStringMap) Map(java.util.Map) PyObject(org.python.core.PyObject)

Example 34 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class RhinoFunctionModel method exec.

public Object exec(List arguments) throws TemplateModelException {
    Context cx = Context.getCurrentContext();
    Object[] args = arguments.toArray();
    BeansWrapper wrapper = getWrapper();
    for (int i = 0; i < args.length; i++) {
        args[i] = wrapper.unwrap((TemplateModel) args[i]);
    }
    return wrapper.wrap(((Function) getScriptable()).call(cx, ScriptableObject.getTopLevelScope(fnThis), fnThis, args));
}
Also used : Context(org.mozilla.javascript.Context) ScriptableObject(org.mozilla.javascript.ScriptableObject) BeansWrapper(freemarker.ext.beans.BeansWrapper) TemplateModel(freemarker.template.TemplateModel)

Example 35 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class AssertFailsDirective method execute.

public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    String message = null;
    Pattern messageRegexp = null;
    String exception = null;
    int causeNestingLevel = 0;
    for (Object paramEnt : params.entrySet()) {
        Map.Entry<String, TemplateModel> param = (Map.Entry) paramEnt;
        String paramName = param.getKey();
        if (paramName.equals(MESSAGE_PARAM)) {
            message = getAsString(param.getValue(), MESSAGE_PARAM, env);
        } else if (paramName.equals(MESSAGE_REGEXP_PARAM)) {
            messageRegexp = Pattern.compile(getAsString(param.getValue(), MESSAGE_REGEXP_PARAM, env), Pattern.CASE_INSENSITIVE);
        } else if (paramName.equals(EXCEPTION_PARAM)) {
            exception = getAsString(param.getValue(), EXCEPTION_PARAM, env);
        } else if (paramName.equals(CAUSE_NESTING_LEVEL_PARAM)) {
            causeNestingLevel = getAsInt(param.getValue(), CAUSE_NESTING_LEVEL_PARAM, env);
        } else {
            throw new UnsupportedParameterException(paramName, env);
        }
    }
    if (body != null) {
        boolean blockFailed;
        try {
            body.render(NullWriter.INSTANCE);
            blockFailed = false;
        } catch (Throwable e) {
            blockFailed = true;
            int causeNestingLevelCountDown = causeNestingLevel;
            while (causeNestingLevelCountDown != 0) {
                e = e.getCause();
                if (e == null) {
                    throw new AssertationFailedInTemplateException("Failure is not like expected: The cause exception nesting dept was lower than " + causeNestingLevel + ".", env);
                }
                causeNestingLevelCountDown--;
            }
            if (message != null || messageRegexp != null) {
                if (e.getMessage() == null) {
                    throw new AssertationFailedInTemplateException("Failure is not like expected. The exception message was null, " + "and thus it doesn't contain:\n" + StringUtil.jQuote(message) + ".", env);
                }
                if (message != null) {
                    String actualMessage = e instanceof TemplateException ? ((TemplateException) e).getMessageWithoutStackTop() : e.getMessage();
                    if (actualMessage.toLowerCase().indexOf(message.toLowerCase()) == -1) {
                        throw new AssertationFailedInTemplateException("Failure is not like expected. The exception message:\n" + StringUtil.jQuote(actualMessage) + "\ndoesn't contain:\n" + StringUtil.jQuote(message) + ".", env);
                    }
                }
                if (messageRegexp != null) {
                    if (!messageRegexp.matcher(e.getMessage()).find()) {
                        throw new AssertationFailedInTemplateException("Failure is not like expected. The exception message:\n" + StringUtil.jQuote(e.getMessage()) + "\ndoesn't match this regexp:\n" + StringUtil.jQuote(messageRegexp.toString()) + ".", env);
                    }
                }
            }
            if (exception != null && e.getClass().getName().indexOf(exception) == -1) {
                throw new AssertationFailedInTemplateException("Failure is not like expected. The exception class name " + StringUtil.jQuote(e.getClass().getName()) + " doesn't contain " + StringUtil.jQuote(message) + ".", env);
            }
        }
        if (!blockFailed) {
            throw new AssertationFailedInTemplateException("Block was expected to fail, but it didn't.", env);
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) TemplateException(freemarker.template.TemplateException) TemplateModel(freemarker.template.TemplateModel) Map(java.util.Map)

Aggregations

TemplateModel (freemarker.template.TemplateModel)108 TemplateModelException (freemarker.template.TemplateModelException)26 Map (java.util.Map)23 TemplateScalarModel (freemarker.template.TemplateScalarModel)18 Test (org.junit.Test)17 ArrayList (java.util.ArrayList)15 TemplateException (freemarker.template.TemplateException)13 HashMap (java.util.HashMap)13 SimpleScalar (freemarker.template.SimpleScalar)11 IOException (java.io.IOException)11 List (java.util.List)11 Template (freemarker.template.Template)9 TemplateSequenceModel (freemarker.template.TemplateSequenceModel)8 TemplateTransformModel (freemarker.template.TemplateTransformModel)8 SimpleHash (freemarker.template.SimpleHash)7 SimpleSequence (freemarker.template.SimpleSequence)7 Writer (java.io.Writer)7 Iterator (java.util.Iterator)7 Environment (freemarker.core.Environment)6 TemplateHashModel (freemarker.template.TemplateHashModel)6