Search in sources :

Example 1 with MalformedTemplateNameException

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

the class TemplateCache method getTemplate.

/**
 * Retrieves the template with the given name (and according the specified further parameters) from the template
 * cache, loading it into the cache first if it's missing/staled.
 *
 * <p>
 * All parameters must be non-{@code null}, except {@code customLookupCondition}. For the meaning of the parameters
 * see {@link Configuration#getTemplate(String, Locale, String, boolean)}.
 *
 * @return A {@link MaybeMissingTemplate} object that contains the {@link Template}, or a
 *         {@link MaybeMissingTemplate} object that contains {@code null} as the {@link Template} and information
 *         about the missing template. The return value itself is never {@code null}. Note that exceptions occurring
 *         during template loading will not be classified as a missing template, so they will cause an exception to
 *         be thrown by this method instead of returning a {@link MaybeMissingTemplate}. The idea is that having a
 *         missing template is normal (not exceptional), providing that the backing storage mechanism could indeed
 *         check that it's missing.
 *
 * @throws MalformedTemplateNameException
 *             If the {@code name} was malformed according the current {@link TemplateNameFormat}. However, if the
 *             {@link TemplateNameFormat} is {@link TemplateNameFormat#DEFAULT_2_3_0} and
 *             {@link Configuration#getIncompatibleImprovements()} is less than 2.4.0, then instead of throwing this
 *             exception, a {@link MaybeMissingTemplate} will be returned, similarly as if the template were missing
 *             (the {@link MaybeMissingTemplate#getMissingTemplateReason()} will describe the real error).
 *
 * @throws IOException
 *             If reading the template has failed from a reason other than the template is missing. This method
 *             should never be a {@link TemplateNotFoundException}, as that condition is indicated in the return
 *             value.
 *
 * @since 2.3.22
 */
public MaybeMissingTemplate getTemplate(String name, Locale locale, Object customLookupCondition, String encoding, boolean parseAsFTL) throws IOException {
    NullArgumentException.check("name", name);
    NullArgumentException.check("locale", locale);
    NullArgumentException.check("encoding", encoding);
    try {
        name = templateNameFormat.normalizeRootBasedName(name);
    } catch (MalformedTemplateNameException e) {
        // If we don't have to emulate backward compatible behavior, then just rethrow it:
        if (templateNameFormat != TemplateNameFormat.DEFAULT_2_3_0 || config.getIncompatibleImprovements().intValue() >= _TemplateAPI.VERSION_INT_2_4_0) {
            throw e;
        }
        return new MaybeMissingTemplate(null, e);
    }
    if (templateLoader == null) {
        return new MaybeMissingTemplate(name, "The TemplateLoader was null.");
    }
    Template template = getTemplateInternal(name, locale, customLookupCondition, encoding, parseAsFTL);
    return template != null ? new MaybeMissingTemplate(template) : new MaybeMissingTemplate(name, (String) null);
}
Also used : MalformedTemplateNameException(freemarker.template.MalformedTemplateNameException) Template(freemarker.template.Template)

Example 2 with MalformedTemplateNameException

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

the class GetOptionalTemplateMethod method exec.

public Object exec(List args) throws TemplateModelException {
    final int argCnt = args.size();
    if (argCnt < 1 || argCnt > 2) {
        throw _MessageUtil.newArgCntError(methodName, argCnt, 1, 2);
    }
    final Environment env = Environment.getCurrentEnvironment();
    if (env == null) {
        throw new IllegalStateException("No freemarer.core.Environment is associated to the current thread.");
    }
    final String absTemplateName;
    {
        TemplateModel arg = (TemplateModel) args.get(0);
        if (!(arg instanceof TemplateScalarModel)) {
            throw _MessageUtil.newMethodArgMustBeStringException(methodName, 0, arg);
        }
        String templateName = EvalUtil.modelToString((TemplateScalarModel) arg, null, env);
        try {
            absTemplateName = env.toFullTemplateName(env.getCurrentTemplate().getName(), templateName);
        } catch (MalformedTemplateNameException e) {
            throw new _TemplateModelException(e, "Failed to convert template path to full path; see cause exception.");
        }
    }
    final TemplateHashModelEx options;
    if (argCnt > 1) {
        TemplateModel arg = (TemplateModel) args.get(1);
        if (!(arg instanceof TemplateHashModelEx)) {
            throw _MessageUtil.newMethodArgMustBeExtendedHashException(methodName, 1, arg);
        }
        options = (TemplateHashModelEx) arg;
    } else {
        options = null;
    }
    String encoding = null;
    boolean parse = true;
    if (options != null) {
        final KeyValuePairIterator kvpi = TemplateModelUtils.getKeyValuePairIterator(options);
        while (kvpi.hasNext()) {
            final KeyValuePair kvp = kvpi.next();
            final String optName;
            {
                TemplateModel optNameTM = kvp.getKey();
                if (!(optNameTM instanceof TemplateScalarModel)) {
                    throw _MessageUtil.newMethodArgInvalidValueException(methodName, 1, "All keys in the options hash must be strings, but found ", new _DelayedAOrAn(new _DelayedFTLTypeDescription(optNameTM)));
                }
                optName = ((TemplateScalarModel) optNameTM).getAsString();
            }
            final TemplateModel optValue = kvp.getValue();
            if (OPTION_ENCODING.equals(optName)) {
                encoding = getStringOption(OPTION_ENCODING, optValue);
            } else if (OPTION_PARSE.equals(optName)) {
                parse = getBooleanOption(OPTION_PARSE, optValue);
            } else {
                throw _MessageUtil.newMethodArgInvalidValueException(methodName, 1, "Unsupported option ", new _DelayedJQuote(optName), "; valid names are: ", new _DelayedJQuote(OPTION_ENCODING), ", ", new _DelayedJQuote(OPTION_PARSE), ".");
            }
        }
    }
    final Template template;
    try {
        template = env.getTemplateForInclusion(absTemplateName, encoding, parse, true);
    } catch (IOException e) {
        throw new _TemplateModelException(e, "I/O error when trying to load optional template ", new _DelayedJQuote(absTemplateName), "; see cause exception");
    }
    SimpleHash result = new SimpleHash(env.getObjectWrapper());
    result.put(RESULT_EXISTS, template != null);
    // conveniently provided like in <@optTemp.include!myDefaultMacro />.
    if (template != null) {
        result.put(RESULT_INCLUDE, new TemplateDirectiveModel() {

            public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
                if (!params.isEmpty()) {
                    throw new TemplateException("This directive supports no parameters.", env);
                }
                if (loopVars.length != 0) {
                    throw new TemplateException("This directive supports no loop variables.", env);
                }
                if (body != null) {
                    throw new TemplateException("This directive supports no nested content.", env);
                }
                env.include(template);
            }
        });
        result.put(RESULT_IMPORT, new TemplateMethodModelEx() {

            public Object exec(List args) throws TemplateModelException {
                if (!args.isEmpty()) {
                    throw new TemplateModelException("This method supports no parameters.");
                }
                try {
                    return env.importLib(template, null);
                } catch (IOException e) {
                    throw new _TemplateModelException(e, "Failed to import loaded template; see cause exception");
                } catch (TemplateException e) {
                    throw new _TemplateModelException(e, "Failed to import loaded template; see cause exception");
                }
            }
        });
    }
    return result;
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateModel(freemarker.template.TemplateModel) MalformedTemplateNameException(freemarker.template.MalformedTemplateNameException) Template(freemarker.template.Template) TemplateMethodModelEx(freemarker.template.TemplateMethodModelEx) List(java.util.List) KeyValuePairIterator(freemarker.template.TemplateHashModelEx2.KeyValuePairIterator) KeyValuePair(freemarker.template.TemplateHashModelEx2.KeyValuePair) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) TemplateDirectiveBody(freemarker.template.TemplateDirectiveBody) TemplateHashModelEx(freemarker.template.TemplateHashModelEx) SimpleHash(freemarker.template.SimpleHash) TemplateScalarModel(freemarker.template.TemplateScalarModel) Map(java.util.Map) TemplateDirectiveModel(freemarker.template.TemplateDirectiveModel)

Example 3 with MalformedTemplateNameException

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

the class Include method accept.

@Override
TemplateElement[] accept(Environment env) throws TemplateException, IOException {
    final String includedTemplateName = includedTemplateNameExp.evalAndCoerceToPlainText(env);
    final String fullIncludedTemplateName;
    try {
        fullIncludedTemplateName = env.toFullTemplateName(getTemplate().getName(), includedTemplateName);
    } catch (MalformedTemplateNameException e) {
        throw new _MiscTemplateException(e, env, "Malformed template name ", new _DelayedJQuote(e.getTemplateName()), ":\n", e.getMalformednessDescription());
    }
    final String encoding = this.encoding != null ? this.encoding : (encodingExp != null ? encodingExp.evalAndCoerceToPlainText(env) : null);
    final boolean parse;
    if (this.parse != null) {
        parse = this.parse.booleanValue();
    } else {
        TemplateModel tm = parseExp.eval(env);
        if (tm instanceof TemplateScalarModel) {
            // Legacy
            parse = getYesNo(parseExp, EvalUtil.modelToString((TemplateScalarModel) tm, parseExp, env));
        } else {
            parse = parseExp.modelToBoolean(tm, env);
        }
    }
    final boolean ignoreMissing;
    if (this.ignoreMissingExpPrecalcedValue != null) {
        ignoreMissing = this.ignoreMissingExpPrecalcedValue.booleanValue();
    } else if (ignoreMissingExp != null) {
        ignoreMissing = ignoreMissingExp.evalToBoolean(env);
    } else {
        ignoreMissing = false;
    }
    final Template includedTemplate;
    try {
        includedTemplate = env.getTemplateForInclusion(fullIncludedTemplateName, encoding, parse, ignoreMissing);
    } catch (IOException e) {
        throw new _MiscTemplateException(e, env, "Template inclusion failed (for parameter value ", new _DelayedJQuote(includedTemplateName), "):\n", new _DelayedGetMessage(e));
    }
    if (includedTemplate != null) {
        env.include(includedTemplate);
    }
    return null;
}
Also used : TemplateScalarModel(freemarker.template.TemplateScalarModel) TemplateModel(freemarker.template.TemplateModel) IOException(java.io.IOException) MalformedTemplateNameException(freemarker.template.MalformedTemplateNameException) Template(freemarker.template.Template)

Example 4 with MalformedTemplateNameException

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

the class TemplateCacheTest method testTemplateNameFormatExceptionAndBackwardCompatibility.

@Test
public void testTemplateNameFormatExceptionAndBackwardCompatibility() throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
    assertNull(cfg.getTemplate("../x", null, null, null, true, true));
    try {
        cfg.getTemplate("../x");
        fail();
    } catch (TemplateNotFoundException e) {
    // expected
    }
    // [2.4] Test it with IcI 2.4
    cfg.setTemplateNameFormat(TemplateNameFormat.DEFAULT_2_4_0);
    try {
        cfg.getTemplate("../x", null, null, null, true, true);
        fail();
    } catch (MalformedTemplateNameException e) {
    // expected
    }
    try {
        cfg.getTemplate("../x");
        fail();
    } catch (MalformedTemplateNameException e) {
    // expected
    }
}
Also used : Configuration(freemarker.template.Configuration) TemplateNotFoundException(freemarker.template.TemplateNotFoundException) MalformedTemplateNameException(freemarker.template.MalformedTemplateNameException) Test(org.junit.Test)

Example 5 with MalformedTemplateNameException

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

the class TemplateNameFormatTest method testBackslashNotAllowedWith24.

@Test
public void testBackslashNotAllowedWith24() throws MalformedTemplateNameException, ParseException, IOException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
    cfg.setTemplateNameFormat(TemplateNameFormat.DEFAULT_2_4_0);
    try {
        cfg.getTemplate("././foo\\bar.ftl", Locale.US);
        fail();
    } catch (MalformedTemplateNameException e) {
        assertThat(e.getMessage(), containsStringIgnoringCase("backslash"));
    }
}
Also used : Configuration(freemarker.template.Configuration) MalformedTemplateNameException(freemarker.template.MalformedTemplateNameException) Test(org.junit.Test)

Aggregations

MalformedTemplateNameException (freemarker.template.MalformedTemplateNameException)5 Template (freemarker.template.Template)3 Configuration (freemarker.template.Configuration)2 TemplateModel (freemarker.template.TemplateModel)2 TemplateScalarModel (freemarker.template.TemplateScalarModel)2 IOException (java.io.IOException)2 Test (org.junit.Test)2 SimpleHash (freemarker.template.SimpleHash)1 TemplateDirectiveBody (freemarker.template.TemplateDirectiveBody)1 TemplateDirectiveModel (freemarker.template.TemplateDirectiveModel)1 TemplateException (freemarker.template.TemplateException)1 TemplateHashModelEx (freemarker.template.TemplateHashModelEx)1 KeyValuePair (freemarker.template.TemplateHashModelEx2.KeyValuePair)1 KeyValuePairIterator (freemarker.template.TemplateHashModelEx2.KeyValuePairIterator)1 TemplateMethodModelEx (freemarker.template.TemplateMethodModelEx)1 TemplateModelException (freemarker.template.TemplateModelException)1 TemplateNotFoundException (freemarker.template.TemplateNotFoundException)1 List (java.util.List)1 Map (java.util.Map)1