Search in sources :

Example 1 with freemarker.core._MiscTemplateException

use of freemarker.core._MiscTemplateException in project freemarker by apache.

the class Configuration method setSetting.

@Override
public void setSetting(String name, String value) throws TemplateException {
    boolean unknown = false;
    try {
        if ("TemplateUpdateInterval".equalsIgnoreCase(name)) {
            name = TEMPLATE_UPDATE_DELAY_KEY;
        } else if ("DefaultEncoding".equalsIgnoreCase(name)) {
            name = DEFAULT_ENCODING_KEY;
        }
        if (DEFAULT_ENCODING_KEY_SNAKE_CASE.equals(name) || DEFAULT_ENCODING_KEY_CAMEL_CASE.equals(name)) {
            if (JVM_DEFAULT.equalsIgnoreCase(value)) {
                setDefaultEncoding(getJVMDefaultEncoding());
            } else {
                setDefaultEncoding(value);
            }
        } else if (LOCALIZED_LOOKUP_KEY_SNAKE_CASE.equals(name) || LOCALIZED_LOOKUP_KEY_CAMEL_CASE.equals(name)) {
            setLocalizedLookup(StringUtil.getYesNo(value));
        } else if (STRICT_SYNTAX_KEY_SNAKE_CASE.equals(name) || STRICT_SYNTAX_KEY_CAMEL_CASE.equals(name)) {
            setStrictSyntaxMode(StringUtil.getYesNo(value));
        } else if (WHITESPACE_STRIPPING_KEY_SNAKE_CASE.equals(name) || WHITESPACE_STRIPPING_KEY_CAMEL_CASE.equals(name)) {
            setWhitespaceStripping(StringUtil.getYesNo(value));
        } else if (AUTO_ESCAPING_POLICY_KEY_SNAKE_CASE.equals(name) || AUTO_ESCAPING_POLICY_KEY_CAMEL_CASE.equals(name)) {
            if ("enable_if_default".equals(value) || "enableIfDefault".equals(value)) {
                setAutoEscapingPolicy(ENABLE_IF_DEFAULT_AUTO_ESCAPING_POLICY);
            } else if ("enable_if_supported".equals(value) || "enableIfSupported".equals(value)) {
                setAutoEscapingPolicy(ENABLE_IF_SUPPORTED_AUTO_ESCAPING_POLICY);
            } else if ("disable".equals(value)) {
                setAutoEscapingPolicy(DISABLE_AUTO_ESCAPING_POLICY);
            } else {
                throw invalidSettingValueException(name, value);
            }
        } else if (OUTPUT_FORMAT_KEY_SNAKE_CASE.equals(name) || OUTPUT_FORMAT_KEY_CAMEL_CASE.equals(name)) {
            if (value.equalsIgnoreCase(DEFAULT)) {
                unsetOutputFormat();
            } else {
                OutputFormat stdOF = STANDARD_OUTPUT_FORMATS.get(value);
                setOutputFormat(stdOF != null ? stdOF : (OutputFormat) _ObjectBuilderSettingEvaluator.eval(value, OutputFormat.class, true, _SettingEvaluationEnvironment.getCurrent()));
            }
        } else if (REGISTERED_CUSTOM_OUTPUT_FORMATS_KEY_SNAKE_CASE.equals(name) || REGISTERED_CUSTOM_OUTPUT_FORMATS_KEY_CAMEL_CASE.equals(name)) {
            List list = (List) _ObjectBuilderSettingEvaluator.eval(value, List.class, true, _SettingEvaluationEnvironment.getCurrent());
            for (Object item : list) {
                if (!(item instanceof OutputFormat)) {
                    throw new _MiscTemplateException(getEnvironment(), "Invalid value for setting ", new _DelayedJQuote(name), ": List items must be " + OutputFormat.class.getName() + " instances, in: ", value);
                }
            }
            setRegisteredCustomOutputFormats(list);
        } else if (RECOGNIZE_STANDARD_FILE_EXTENSIONS_KEY_SNAKE_CASE.equals(name) || RECOGNIZE_STANDARD_FILE_EXTENSIONS_KEY_CAMEL_CASE.equals(name)) {
            if (value.equalsIgnoreCase(DEFAULT)) {
                unsetRecognizeStandardFileExtensions();
            } else {
                setRecognizeStandardFileExtensions(StringUtil.getYesNo(value));
            }
        } else if (CACHE_STORAGE_KEY_SNAKE_CASE.equals(name) || CACHE_STORAGE_KEY_CAMEL_CASE.equals(name)) {
            if (value.equalsIgnoreCase(DEFAULT)) {
                unsetCacheStorage();
            }
            if (value.indexOf('.') == -1) {
                int strongSize = 0;
                int softSize = 0;
                Map map = StringUtil.parseNameValuePairList(value, String.valueOf(Integer.MAX_VALUE));
                Iterator it = map.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry ent = (Map.Entry) it.next();
                    String pname = (String) ent.getKey();
                    int pvalue;
                    try {
                        pvalue = Integer.parseInt((String) ent.getValue());
                    } catch (NumberFormatException e) {
                        throw invalidSettingValueException(name, value);
                    }
                    if ("soft".equalsIgnoreCase(pname)) {
                        softSize = pvalue;
                    } else if ("strong".equalsIgnoreCase(pname)) {
                        strongSize = pvalue;
                    } else {
                        throw invalidSettingValueException(name, value);
                    }
                }
                if (softSize == 0 && strongSize == 0) {
                    throw invalidSettingValueException(name, value);
                }
                setCacheStorage(new MruCacheStorage(strongSize, softSize));
            } else {
                setCacheStorage((CacheStorage) _ObjectBuilderSettingEvaluator.eval(value, CacheStorage.class, false, _SettingEvaluationEnvironment.getCurrent()));
            }
        } else if (TEMPLATE_UPDATE_DELAY_KEY_SNAKE_CASE.equals(name) || TEMPLATE_UPDATE_DELAY_KEY_CAMEL_CASE.equals(name)) {
            long multipier;
            String valueWithoutUnit;
            if (value.endsWith("ms")) {
                multipier = 1;
                valueWithoutUnit = rightTrim(value.substring(0, value.length() - 2));
            } else if (value.endsWith("s")) {
                multipier = 1000;
                valueWithoutUnit = rightTrim(value.substring(0, value.length() - 1));
            } else if (value.endsWith("m")) {
                multipier = 1000 * 60;
                valueWithoutUnit = rightTrim(value.substring(0, value.length() - 1));
            } else if (value.endsWith("h")) {
                multipier = 1000 * 60 * 60;
                valueWithoutUnit = rightTrim(value.substring(0, value.length() - 1));
            } else {
                // Default is seconds for backward compatibility
                multipier = 1000;
                valueWithoutUnit = value;
            }
            setTemplateUpdateDelayMilliseconds(Integer.parseInt(valueWithoutUnit) * multipier);
        } else if (TAG_SYNTAX_KEY_SNAKE_CASE.equals(name) || TAG_SYNTAX_KEY_CAMEL_CASE.equals(name)) {
            if ("auto_detect".equals(value) || "autoDetect".equals(value)) {
                setTagSyntax(AUTO_DETECT_TAG_SYNTAX);
            } else if ("angle_bracket".equals(value) || "angleBracket".equals(value)) {
                setTagSyntax(ANGLE_BRACKET_TAG_SYNTAX);
            } else if ("square_bracket".equals(value) || "squareBracket".equals(value)) {
                setTagSyntax(SQUARE_BRACKET_TAG_SYNTAX);
            } else {
                throw invalidSettingValueException(name, value);
            }
        } else if (INTERPOLATION_SYNTAX_KEY_SNAKE_CASE.equals(name) || INTERPOLATION_SYNTAX_KEY_CAMEL_CASE.equals(name)) {
            if ("legacy".equals(value)) {
                setInterpolationSyntax(LEGACY_INTERPOLATION_SYNTAX);
            } else if ("dollar".equals(value)) {
                setInterpolationSyntax(DOLLAR_INTERPOLATION_SYNTAX);
            } else if ("square_bracket".equals(value) || "squareBracket".equals(value)) {
                setInterpolationSyntax(SQUARE_BRACKET_INTERPOLATION_SYNTAX);
            } else {
                throw invalidSettingValueException(name, value);
            }
        } else if (NAMING_CONVENTION_KEY_SNAKE_CASE.equals(name) || NAMING_CONVENTION_KEY_CAMEL_CASE.equals(name)) {
            if ("auto_detect".equals(value) || "autoDetect".equals(value)) {
                setNamingConvention(AUTO_DETECT_NAMING_CONVENTION);
            } else if ("legacy".equals(value)) {
                setNamingConvention(LEGACY_NAMING_CONVENTION);
            } else if ("camel_case".equals(value) || "camelCase".equals(value)) {
                setNamingConvention(CAMEL_CASE_NAMING_CONVENTION);
            } else {
                throw invalidSettingValueException(name, value);
            }
        } else if (TAB_SIZE_KEY_SNAKE_CASE.equals(name) || TAB_SIZE_KEY_CAMEL_CASE.equals(name)) {
            setTabSize(Integer.parseInt(value));
        } else if (INCOMPATIBLE_IMPROVEMENTS_KEY_SNAKE_CASE.equals(name) || INCOMPATIBLE_IMPROVEMENTS_KEY_CAMEL_CASE.equals(name)) {
            setIncompatibleImprovements(new Version(value));
        } else if (INCOMPATIBLE_ENHANCEMENTS.equals(name)) {
            setIncompatibleEnhancements(value);
        } else if (TEMPLATE_LOADER_KEY_SNAKE_CASE.equals(name) || TEMPLATE_LOADER_KEY_CAMEL_CASE.equals(name)) {
            if (value.equalsIgnoreCase(DEFAULT)) {
                unsetTemplateLoader();
            } else {
                setTemplateLoader((TemplateLoader) _ObjectBuilderSettingEvaluator.eval(value, TemplateLoader.class, true, _SettingEvaluationEnvironment.getCurrent()));
            }
        } else if (TEMPLATE_LOOKUP_STRATEGY_KEY_SNAKE_CASE.equals(name) || TEMPLATE_LOOKUP_STRATEGY_KEY_CAMEL_CASE.equals(name)) {
            if (value.equalsIgnoreCase(DEFAULT)) {
                unsetTemplateLookupStrategy();
            } else {
                setTemplateLookupStrategy((TemplateLookupStrategy) _ObjectBuilderSettingEvaluator.eval(value, TemplateLookupStrategy.class, false, _SettingEvaluationEnvironment.getCurrent()));
            }
        } else if (TEMPLATE_NAME_FORMAT_KEY_SNAKE_CASE.equals(name) || TEMPLATE_NAME_FORMAT_KEY_CAMEL_CASE.equals(name)) {
            if (value.equalsIgnoreCase(DEFAULT)) {
                unsetTemplateNameFormat();
            } else if (value.equalsIgnoreCase("default_2_3_0")) {
                setTemplateNameFormat(TemplateNameFormat.DEFAULT_2_3_0);
            } else if (value.equalsIgnoreCase("default_2_4_0")) {
                setTemplateNameFormat(TemplateNameFormat.DEFAULT_2_4_0);
            } else {
                throw invalidSettingValueException(name, value);
            }
        } else if (TEMPLATE_CONFIGURATIONS_KEY_SNAKE_CASE.equals(name) || TEMPLATE_CONFIGURATIONS_KEY_CAMEL_CASE.equals(name)) {
            if (value.equals(NULL)) {
                setTemplateConfigurations(null);
            } else {
                setTemplateConfigurations((TemplateConfigurationFactory) _ObjectBuilderSettingEvaluator.eval(value, TemplateConfigurationFactory.class, false, _SettingEvaluationEnvironment.getCurrent()));
            }
        } else {
            unknown = true;
        }
    } catch (Exception e) {
        throw settingValueAssignmentException(name, value, e);
    }
    if (unknown) {
        super.setSetting(name, value);
    }
}
Also used : Entry(java.util.Map.Entry) freemarker.core._MiscTemplateException(freemarker.core._MiscTemplateException) TemplateConfigurationFactory(freemarker.cache.TemplateConfigurationFactory) freemarker.core._DelayedJQuote(freemarker.core._DelayedJQuote) UndefinedOutputFormat(freemarker.core.UndefinedOutputFormat) CSSOutputFormat(freemarker.core.CSSOutputFormat) HTMLOutputFormat(freemarker.core.HTMLOutputFormat) CombinedMarkupOutputFormat(freemarker.core.CombinedMarkupOutputFormat) JavaScriptOutputFormat(freemarker.core.JavaScriptOutputFormat) OutputFormat(freemarker.core.OutputFormat) XMLOutputFormat(freemarker.core.XMLOutputFormat) MarkupOutputFormat(freemarker.core.MarkupOutputFormat) PlainTextOutputFormat(freemarker.core.PlainTextOutputFormat) XHTMLOutputFormat(freemarker.core.XHTMLOutputFormat) RTFOutputFormat(freemarker.core.RTFOutputFormat) JSONOutputFormat(freemarker.core.JSONOutputFormat) TemplateLookupStrategy(freemarker.cache.TemplateLookupStrategy) freemarker.core._MiscTemplateException(freemarker.core._MiscTemplateException) NullArgumentException(freemarker.template.utility.NullArgumentException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParseException(freemarker.core.ParseException) UnregisteredOutputFormatException(freemarker.core.UnregisteredOutputFormatException) BugException(freemarker.core.BugException) IOException(java.io.IOException) Entry(java.util.Map.Entry) MruCacheStorage(freemarker.cache.MruCacheStorage) Iterator(java.util.Iterator) List(java.util.List) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with freemarker.core._MiscTemplateException

use of freemarker.core._MiscTemplateException in project freemarker by apache.

the class IncludePage method execute.

public void execute(final Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    // Determine the path
    final TemplateModel path = (TemplateModel) params.get("path");
    if (path == null) {
        throw new _MiscTemplateException(env, "Missing required parameter \"path\"");
    }
    if (!(path instanceof TemplateScalarModel)) {
        throw new _MiscTemplateException(env, "Expected a scalar model. \"path\" is instead ", new _DelayedFTLTypeDescription(path));
    }
    final String strPath = ((TemplateScalarModel) path).getAsString();
    if (strPath == null) {
        throw new _MiscTemplateException(env, "String value of \"path\" parameter is null");
    }
    // See whether we need to use a custom response (if we're inside a TTM
    // or TDM or macro nested body, we'll need to as then the current
    // FM environment writer is not identical to HTTP servlet response
    // writer.
    final Writer envOut = env.getOut();
    final HttpServletResponse wrappedResponse;
    if (envOut == response.getWriter()) {
        // Don't bother wrapping if environment's writer is same as
        // response writer
        wrappedResponse = response;
    } else {
        final PrintWriter printWriter = (envOut instanceof PrintWriter) ? (PrintWriter) envOut : new PrintWriter(envOut);
        // Otherwise, create a response wrapper that will pass the
        // env writer, potentially first wrapping it in a print
        // writer when it ain't one already.
        wrappedResponse = new HttpServletResponseWrapper(response) {

            @Override
            public PrintWriter getWriter() {
                return printWriter;
            }
        };
    }
    // Determine inherit_params value
    final boolean inheritParams;
    final TemplateModel inheritParamsModel = (TemplateModel) params.get("inherit_params");
    if (inheritParamsModel == null) {
        // defaults to true when not specified
        inheritParams = true;
    } else {
        if (!(inheritParamsModel instanceof TemplateBooleanModel)) {
            throw new _MiscTemplateException(env, "\"inherit_params\" should be a boolean but it's a(n) ", inheritParamsModel.getClass().getName(), " instead");
        }
        inheritParams = ((TemplateBooleanModel) inheritParamsModel).getAsBoolean();
    }
    // Get explicit params, if any
    final TemplateModel paramsModel = (TemplateModel) params.get("params");
    // Determine whether we need to wrap the request
    final HttpServletRequest wrappedRequest;
    if (paramsModel == null && inheritParams) {
        // Inherit original request params & no params explicitly
        // specified, so use the original request
        wrappedRequest = request;
    } else {
        // In any other case, use a custom request wrapper
        final Map paramsMap;
        if (paramsModel != null) {
            // Convert params to a Map
            final Object unwrapped = DeepUnwrap.unwrap(paramsModel);
            if (!(unwrapped instanceof Map)) {
                throw new _MiscTemplateException(env, "Expected \"params\" to unwrap into a java.util.Map. It unwrapped into ", unwrapped.getClass().getName(), " instead.");
            }
            paramsMap = (Map) unwrapped;
        } else {
            paramsMap = Collections.EMPTY_MAP;
        }
        wrappedRequest = new CustomParamsRequest(request, paramsMap, inheritParams);
    }
    // Finally, do the include
    try {
        request.getRequestDispatcher(strPath).include(wrappedRequest, wrappedResponse);
    } catch (ServletException e) {
        throw new _MiscTemplateException(e, env);
    }
}
Also used : freemarker.core._MiscTemplateException(freemarker.core._MiscTemplateException) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) freemarker.core._DelayedFTLTypeDescription(freemarker.core._DelayedFTLTypeDescription) TemplateModel(freemarker.template.TemplateModel) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) TemplateScalarModel(freemarker.template.TemplateScalarModel) HashMap(java.util.HashMap) Map(java.util.Map) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) TemplateBooleanModel(freemarker.template.TemplateBooleanModel) PrintWriter(java.io.PrintWriter)

Aggregations

freemarker.core._MiscTemplateException (freemarker.core._MiscTemplateException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 MruCacheStorage (freemarker.cache.MruCacheStorage)1 TemplateConfigurationFactory (freemarker.cache.TemplateConfigurationFactory)1 TemplateLookupStrategy (freemarker.cache.TemplateLookupStrategy)1 BugException (freemarker.core.BugException)1 CSSOutputFormat (freemarker.core.CSSOutputFormat)1 CombinedMarkupOutputFormat (freemarker.core.CombinedMarkupOutputFormat)1 HTMLOutputFormat (freemarker.core.HTMLOutputFormat)1 JSONOutputFormat (freemarker.core.JSONOutputFormat)1 JavaScriptOutputFormat (freemarker.core.JavaScriptOutputFormat)1 MarkupOutputFormat (freemarker.core.MarkupOutputFormat)1 OutputFormat (freemarker.core.OutputFormat)1 ParseException (freemarker.core.ParseException)1 PlainTextOutputFormat (freemarker.core.PlainTextOutputFormat)1 RTFOutputFormat (freemarker.core.RTFOutputFormat)1 UndefinedOutputFormat (freemarker.core.UndefinedOutputFormat)1 UnregisteredOutputFormatException (freemarker.core.UnregisteredOutputFormatException)1 XHTMLOutputFormat (freemarker.core.XHTMLOutputFormat)1