Search in sources :

Example 11 with TemplateModelException

use of freemarker.template.TemplateModelException in project ofbiz-framework by apache.

the class OfbizContentTransform method getWriter.

public Writer getWriter(final Writer out, Map args) {
    final StringBuilder buf = new StringBuilder();
    final String imgSize = OfbizContentTransform.getArg(args, "variant");
    return new Writer(out) {

        @Override
        public void write(char[] cbuf, int off, int len) {
            buf.append(cbuf, off, len);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            try {
                Environment env = Environment.getCurrentEnvironment();
                BeanModel req = (BeanModel) env.getVariable("request");
                HttpServletRequest request = req == null ? null : (HttpServletRequest) req.getWrappedObject();
                String requestUrl = buf.toString();
                // If the URL starts with http(s) then there is nothing for us to do here
                if (requestUrl.startsWith("http")) {
                    out.write(requestUrl);
                    return;
                }
                requestUrl = UtilCodec.getDecoder("url").decode(requestUrl);
                // make the link
                StringBuilder newURL = new StringBuilder();
                ContentUrlTag.appendContentPrefix(request, newURL);
                if ((newURL.length() > 0 && newURL.charAt(newURL.length() - 1) != '/') && (requestUrl.length() > 0 && requestUrl.charAt(0) != '/')) {
                    newURL.append('/');
                }
                if (UtilValidate.isNotEmpty(imgSize)) {
                    if (!"/images/defaultImage.jpg".equals(requestUrl)) {
                        int index = requestUrl.lastIndexOf(".");
                        if (index > 0) {
                            String suffix = requestUrl.substring(index);
                            String imgName = requestUrl.substring(0, index);
                            requestUrl = imgName + "-" + imgSize + suffix;
                        }
                    }
                }
                newURL.append(requestUrl);
                out.write(newURL.toString());
            } catch (TemplateModelException e) {
                throw new IOException(e.getMessage());
            }
        }
    };
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) TemplateModelException(freemarker.template.TemplateModelException) BeanModel(freemarker.ext.beans.BeanModel) Environment(freemarker.core.Environment) IOException(java.io.IOException) Writer(java.io.Writer)

Example 12 with TemplateModelException

use of freemarker.template.TemplateModelException in project ofbiz-framework by apache.

the class FreeMarkerWorker method makeConfiguration.

public static Configuration makeConfiguration(BeansWrapper wrapper) {
    Configuration newConfig = newConfiguration();
    newConfig.setObjectWrapper(wrapper);
    TemplateHashModel staticModels = wrapper.getStaticModels();
    newConfig.setSharedVariable("Static", staticModels);
    try {
        newConfig.setSharedVariable("EntityQuery", staticModels.get("org.apache.ofbiz.entity.util.EntityQuery"));
    } catch (TemplateModelException e) {
        Debug.logError(e, module);
    }
    newConfig.setLocalizedLookup(false);
    newConfig.setSharedVariable("StringUtil", new BeanModel(StringUtil.INSTANCE, wrapper));
    TemplateLoader[] templateLoaders = { new FlexibleTemplateLoader(), new StringTemplateLoader() };
    MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(templateLoaders);
    newConfig.setTemplateLoader(multiTemplateLoader);
    Map<?, ?> freemarkerImports = UtilProperties.getProperties("freemarkerImports");
    if (freemarkerImports != null) {
        newConfig.setAutoImports(freemarkerImports);
    }
    newConfig.setLogTemplateExceptions(false);
    newConfig.setTemplateExceptionHandler(new FreeMarkerWorker.OFBizTemplateExceptionHandler());
    try {
        newConfig.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
        newConfig.setSetting("number_format", "0.##########");
    } catch (TemplateException e) {
        Debug.logError("Unable to set date/time and number formats in FreeMarker: " + e, module);
    }
    // Transforms properties file set up as key=transform name, property=transform class name
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> resources;
    try {
        resources = loader.getResources("freemarkerTransforms.properties");
    } catch (IOException e) {
        Debug.logError(e, "Could not load list of freemarkerTransforms.properties", module);
        throw UtilMisc.initCause(new InternalError(e.getMessage()), e);
    }
    while (resources.hasMoreElements()) {
        URL propertyURL = resources.nextElement();
        Debug.logInfo("loading properties: " + propertyURL, module);
        Properties props = UtilProperties.getProperties(propertyURL);
        if (UtilValidate.isEmpty(props)) {
            Debug.logError("Unable to locate properties file " + propertyURL, module);
        } else {
            loadTransforms(loader, props, newConfig);
        }
    }
    return newConfig;
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) Configuration(freemarker.template.Configuration) BeanModel(freemarker.ext.beans.BeanModel) TemplateException(freemarker.template.TemplateException) StringTemplateLoader(freemarker.cache.StringTemplateLoader) URLTemplateLoader(freemarker.cache.URLTemplateLoader) TemplateLoader(freemarker.cache.TemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) IOException(java.io.IOException) UtilProperties(org.apache.ofbiz.base.util.UtilProperties) Properties(java.util.Properties) URL(java.net.URL) StringTemplateLoader(freemarker.cache.StringTemplateLoader) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) TemplateHashModel(freemarker.template.TemplateHashModel)

Example 13 with TemplateModelException

use of freemarker.template.TemplateModelException in project ofbiz-framework by apache.

the class CatalogAltUrlSeoTransform method getWriter.

@Override
public Writer getWriter(final Writer out, final Map args) throws TemplateModelException, IOException {
    final StringBuilder buf = new StringBuilder();
    final boolean fullPath = checkArg(args, "fullPath", false);
    final boolean secure = checkArg(args, "secure", false);
    return new Writer(out) {

        public void write(char[] cbuf, int off, int len) throws IOException {
            buf.append(cbuf, off, len);
        }

        public void flush() throws IOException {
            out.flush();
        }

        public void close() throws IOException {
            try {
                Environment env = Environment.getCurrentEnvironment();
                BeanModel req = (BeanModel) env.getVariable("request");
                String previousCategoryId = getStringArg(args, "previousCategoryId");
                String productCategoryId = getStringArg(args, "productCategoryId");
                String productId = getStringArg(args, "productId");
                String url = "";
                Object prefix = env.getVariable("urlPrefix");
                String viewSize = getStringArg(args, "viewSize");
                String viewIndex = getStringArg(args, "viewIndex");
                String viewSort = getStringArg(args, "viewSort");
                String searchString = getStringArg(args, "searchString");
                if (req != null) {
                    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
                    StringBuilder newURL = new StringBuilder();
                    if (UtilValidate.isNotEmpty(productId)) {
                        if (SeoConfigUtil.isCategoryUrlEnabled(request.getContextPath())) {
                            url = CatalogUrlSeoTransform.makeProductUrl(request, productId, productCategoryId, previousCategoryId);
                        } else {
                            url = CatalogUrlFilter.makeProductUrl(request, previousCategoryId, productCategoryId, productId);
                        }
                    } else {
                        if (SeoConfigUtil.isCategoryUrlEnabled(request.getContextPath())) {
                            url = CatalogUrlSeoTransform.makeCategoryUrl(request, productCategoryId, previousCategoryId, viewSize, viewIndex, viewSort, searchString);
                        } else {
                            url = CatalogUrlFilter.makeCategoryUrl(request, previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                        }
                    }
                    // make the link
                    if (fullPath) {
                        try {
                            OfbizUrlBuilder builder = OfbizUrlBuilder.from(request);
                            builder.buildHostPart(newURL, "", secure);
                        } catch (WebAppConfigurationException e) {
                            Debug.logError(e.getMessage(), module);
                        }
                    }
                    newURL.append(url);
                    out.write(newURL.toString());
                } else if (prefix != null) {
                    Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
                    LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
                    Locale locale = (Locale) args.get("locale");
                    String prefixString = ((StringModel) prefix).getAsString();
                    prefixString = prefixString.replaceAll("&#47;", "/");
                    String contextPath = prefixString;
                    int lastSlashIndex = prefixString.lastIndexOf('/');
                    if (lastSlashIndex > -1 && lastSlashIndex < prefixString.length()) {
                        contextPath = prefixString.substring(prefixString.lastIndexOf('/'));
                    }
                    if (UtilValidate.isNotEmpty(productId)) {
                        GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
                        ProductContentWrapper wrapper = new ProductContentWrapper(dispatcher, product, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
                        if (SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
                            url = CatalogUrlSeoTransform.makeProductUrl(delegator, wrapper, prefixString, contextPath, productCategoryId, previousCategoryId, productId);
                        } else {
                            url = CatalogUrlFilter.makeProductUrl(wrapper, null, prefixString, previousCategoryId, productCategoryId, productId);
                        }
                    } else {
                        GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId).queryOne();
                        CategoryContentWrapper wrapper = new CategoryContentWrapper(dispatcher, productCategory, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
                        if (SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
                            url = CatalogUrlSeoTransform.makeCategoryUrl(delegator, wrapper, prefixString, productCategoryId, previousCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                        } else {
                            url = CatalogUrlFilter.makeCategoryUrl(delegator, wrapper, null, prefixString, previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                        }
                    }
                    out.write(url);
                } else {
                    out.write(buf.toString());
                }
            } catch (TemplateModelException | GenericEntityException e) {
                throw new IOException(e.getMessage());
            }
        }
    };
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) TemplateModelException(freemarker.template.TemplateModelException) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) BeanModel(freemarker.ext.beans.BeanModel) OfbizUrlBuilder(org.apache.ofbiz.webapp.OfbizUrlBuilder) CategoryContentWrapper(org.apache.ofbiz.product.category.CategoryContentWrapper) IOException(java.io.IOException) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Delegator(org.apache.ofbiz.entity.Delegator) ProductContentWrapper(org.apache.ofbiz.product.product.ProductContentWrapper) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Environment(freemarker.core.Environment) Writer(java.io.Writer)

Example 14 with TemplateModelException

use of freemarker.template.TemplateModelException in project ofbiz-framework by apache.

the class OfbizCatalogUrlTransform method getWriter.

@Override
public Writer getWriter(final Writer out, final Map args) throws TemplateModelException, IOException {
    final StringBuilder buf = new StringBuilder();
    return new Writer(out) {

        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            buf.append(cbuf, off, len);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            try {
                Environment env = Environment.getCurrentEnvironment();
                BeanModel req = (BeanModel) env.getVariable("request");
                if (req != null) {
                    String productId = getStringArg(args, "productId");
                    String currentCategoryId = getStringArg(args, "currentCategoryId");
                    String previousCategoryId = getStringArg(args, "previousCategoryId");
                    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
                    String catalogUrl = CatalogUrlServlet.makeCatalogUrl(request, productId, currentCategoryId, previousCategoryId);
                    out.write(catalogUrl);
                }
            } catch (TemplateModelException e) {
                throw new IOException(e.getMessage());
            }
        }
    };
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) TemplateModelException(freemarker.template.TemplateModelException) BeanModel(freemarker.ext.beans.BeanModel) Environment(freemarker.core.Environment) IOException(java.io.IOException) Writer(java.io.Writer)

Example 15 with TemplateModelException

use of freemarker.template.TemplateModelException in project ofbiz-framework by apache.

the class UrlRegexpTransform method getWriter.

public Writer getWriter(final Writer out, Map args) {
    final StringBuffer buf = new StringBuffer();
    final boolean fullPath = checkArg(args, "fullPath", false);
    final boolean secure = checkArg(args, "secure", false);
    final boolean encode = checkArg(args, "encode", true);
    return new Writer(out) {

        public void write(char[] cbuf, int off, int len) {
            buf.append(cbuf, off, len);
        }

        public void flush() throws IOException {
            out.flush();
        }

        public void close() throws IOException {
            try {
                Environment env = Environment.getCurrentEnvironment();
                BeanModel req = (BeanModel) env.getVariable("request");
                BeanModel res = (BeanModel) env.getVariable("response");
                Object prefix = env.getVariable("urlPrefix");
                if (req != null) {
                    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
                    ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
                    HttpServletResponse response = null;
                    if (res != null) {
                        response = (HttpServletResponse) res.getWrappedObject();
                    }
                    HttpSession session = request.getSession();
                    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
                    // anonymous shoppers are not logged in
                    if (userLogin != null && "anonymous".equals(userLogin.getString("userLoginId"))) {
                        userLogin = null;
                    }
                    RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
                    out.write(seoUrl(rh.makeLink(request, response, buf.toString(), fullPath, secure || request.isSecure(), encode), userLogin == null));
                } else if (prefix != null) {
                    if (prefix instanceof TemplateScalarModel) {
                        TemplateScalarModel s = (TemplateScalarModel) prefix;
                        String prefixString = s.getAsString();
                        String bufString = buf.toString();
                        boolean prefixSlash = prefixString.endsWith("/");
                        boolean bufSlash = bufString.startsWith("/");
                        if (prefixSlash && bufSlash) {
                            bufString = bufString.substring(1);
                        } else if (!prefixSlash && !bufSlash) {
                            bufString = "/" + bufString;
                        }
                        out.write(prefixString + bufString);
                    }
                } else {
                    out.write(buf.toString());
                }
            } catch (IOException | TemplateModelException e) {
                throw new IOException(e.getMessage());
            }
        }
    };
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) TemplateModelException(freemarker.template.TemplateModelException) BeanModel(freemarker.ext.beans.BeanModel) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) Environment(freemarker.core.Environment) ServletContext(javax.servlet.ServletContext) TemplateScalarModel(freemarker.template.TemplateScalarModel) Writer(java.io.Writer)

Aggregations

TemplateModelException (freemarker.template.TemplateModelException)87 TemplateModel (freemarker.template.TemplateModel)24 IOException (java.io.IOException)21 TemplateScalarModel (freemarker.template.TemplateScalarModel)18 SimpleScalar (freemarker.template.SimpleScalar)17 BeanModel (freemarker.ext.beans.BeanModel)14 Environment (freemarker.core.Environment)13 Writer (java.io.Writer)13 ArrayList (java.util.ArrayList)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 Map (java.util.Map)10 List (java.util.List)9 SimpleNumber (freemarker.template.SimpleNumber)7 TemplateHashModel (freemarker.template.TemplateHashModel)7 Iterator (java.util.Iterator)6 freemarker.core._TemplateModelException (freemarker.core._TemplateModelException)5 TemplateHashModelEx (freemarker.template.TemplateHashModelEx)5 TemplateMethodModelEx (freemarker.template.TemplateMethodModelEx)5 TemplateModelIterator (freemarker.template.TemplateModelIterator)5 UMAException (com.ibm.uma.UMAException)4