Search in sources :

Example 1 with WebContext

use of org.thymeleaf.context.WebContext in project ratpack by ratpack.

the class Template method thymeleafTemplate.

public static Template thymeleafTemplate(Map<String, ?> model, String name, String contentType, IFragmentSpec fragmentSpec) {
    HttpServletRequest request = new ThymeleafHttpServletRequestAdapter();
    HttpServletResponse response = new ThymeleafHttpServletResponseAdapter();
    ServletContext servletContext = new ThymeleafServletContextAdapter();
    WebContext context = new WebContext(request, response, servletContext);
    if (model != null) {
        context.setVariables(model);
    }
    return new Template(name, context, contentType, fragmentSpec);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ThymeleafServletContextAdapter(ratpack.thymeleaf.internal.ThymeleafServletContextAdapter) ThymeleafHttpServletResponseAdapter(ratpack.thymeleaf.internal.ThymeleafHttpServletResponseAdapter) WebContext(org.thymeleaf.context.WebContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletContext(javax.servlet.ServletContext) ThymeleafHttpServletRequestAdapter(ratpack.thymeleaf.internal.ThymeleafHttpServletRequestAdapter)

Example 2 with WebContext

use of org.thymeleaf.context.WebContext in project thymeleaf-tests by thymeleaf.

the class DecoupledSTSMTest method test.

private static void test(final String templateName, final String expectedResultLocation, final Map<String, Object> vars) throws Exception {
    final Map<String, Object> requestAttributes = new LinkedHashMap<String, Object>();
    final Map<String, Object[]> requestParameters = new LinkedHashMap<String, Object[]>();
    final HttpServletRequest mockRequest = TestMockServletUtil.createHttpServletRequest("WebVariablesMap", null, requestAttributes, requestParameters, Locale.US);
    final HttpServletResponse mockResponse = TestMockServletUtil.createHttpServletResponse();
    final Map<String, Object> servletContextAttributes = new LinkedHashMap<String, Object>();
    final ServletContext mockServletContext = TestMockServletUtil.createServletContext(servletContextAttributes);
    final XmlWebApplicationContext appCtx = new XmlWebApplicationContext();
    appCtx.setServletContext(mockServletContext);
    appCtx.setConfigLocation("classpath:templateparser/decoupled/stsm/applicationContext.xml");
    appCtx.refresh();
    mockServletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx);
    // can be null!
    final ConversionService conversionService = getConversionService(appCtx);
    mockRequest.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx);
    final ServletWebRequest servletWebRequest = new ServletWebRequest(mockRequest, mockResponse);
    RequestContextHolder.setRequestAttributes(servletWebRequest);
    final RequestContext requestContext = new RequestContext(mockRequest, mockResponse, mockServletContext, vars);
    vars.put(AbstractTemplateView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, requestContext);
    vars.put(SpringContextVariableNames.SPRING_REQUEST_CONTEXT, requestContext);
    vars.put(SpringContextVariableNames.THYMELEAF_REQUEST_CONTEXT, new SpringWebMvcThymeleafRequestContext(requestContext, mockRequest));
    final List<String> variableNames = new ArrayList<String>(vars.keySet());
    for (final String variableName : variableNames) {
        final Object bindingObject = vars.get(variableName);
        if (isBindingCandidate(variableName, bindingObject)) {
            final String bindingVariableName = BindingResult.MODEL_KEY_PREFIX + variableName;
            if (!vars.containsKey(bindingVariableName)) {
                final WebDataBinder dataBinder = new WebDataBinder(bindingObject, bindingVariableName);
                dataBinder.setConversionService(conversionService);
                vars.put(bindingVariableName, dataBinder.getBindingResult());
            }
        }
    }
    final WebContext ctx = new WebContext(mockRequest, mockResponse, mockServletContext, Locale.US);
    for (final Map.Entry<String, Object> entry : vars.entrySet()) {
        ctx.setVariable(entry.getKey(), entry.getValue());
    }
    final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setTemplateMode("HTML");
    templateResolver.setPrefix("templateparser/decoupled/stsm/templates/");
    templateResolver.setSuffix(".html");
    templateResolver.setUseDecoupledLogic(true);
    final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    templateEngine.setLinkBuilder(new StandardLinkBuilder() {

        @Override
        protected String computeContextPath(final IExpressionContext context, final String base, final Map<String, Object> parameters) {
            return "";
        }
    });
    appCtx.getAutowireCapableBeanFactory().initializeBean(templateEngine, "templateEngine");
    final String result = templateEngine.process(templateName, ctx);
    final String expected = ResourceUtils.read(ClassLoaderUtils.getClassLoader(DecoupledSTSMTest.class).getResourceAsStream(expectedResultLocation), "ISO-8859-1", true);
    Assert.assertEquals(ResourceUtils.normalize(expected), ResourceUtils.normalize(result));
}
Also used : SpringTemplateEngine(org.thymeleaf.spring5.SpringTemplateEngine) StandardLinkBuilder(org.thymeleaf.linkbuilder.StandardLinkBuilder) WebContext(org.thymeleaf.context.WebContext) SpringWebMvcThymeleafRequestContext(org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) WebDataBinder(org.springframework.web.bind.WebDataBinder) ClassLoaderTemplateResolver(org.thymeleaf.templateresolver.ClassLoaderTemplateResolver) XmlWebApplicationContext(org.springframework.web.context.support.XmlWebApplicationContext) IExpressionContext(org.thymeleaf.context.IExpressionContext) ConversionService(org.springframework.core.convert.ConversionService) ServletContext(javax.servlet.ServletContext) RequestContext(org.springframework.web.servlet.support.RequestContext) SpringWebMvcThymeleafRequestContext(org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 3 with WebContext

use of org.thymeleaf.context.WebContext in project java-docs-samples by GoogleCloudPlatform.

the class GaeInfoServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String key = "";
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    WebContext ctx = new WebContext(req, resp, getServletContext(), req.getLocale());
    resp.setContentType("text/html");
    ctx.setVariable("production", SystemProperty.environment.value().name());
    ctx.setVariable("ServiceAccountName", appIdentity.getServiceAccountName());
    ctx.setVariable("gcs", appIdentity.getDefaultGcsBucketName());
    ctx.setVariable("appId", SystemProperty.applicationId.get());
    ctx.setVariable("appVer", SystemProperty.applicationVersion.get());
    ctx.setVariable("version", SystemProperty.version.get());
    ctx.setVariable("environment", SystemProperty.environment.get());
    // Environment Atributes
    ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
    Map<String, Object> attr = env.getAttributes();
    TreeMap<String, String> m = new TreeMap<>();
    for (String k : attr.keySet()) {
        Object o = attr.get(k);
        if (o.getClass().getCanonicalName().equals("java.lang.String")) {
            m.put(k, (String) o);
        } else if (o.getClass().getCanonicalName().equals("java.lang.Boolean")) {
            m.put(k, ((Boolean) o).toString());
        } else {
            m.put(k, "a " + o.getClass().getCanonicalName());
        }
    }
    ctx.setVariable("attribs", m);
    m = new TreeMap<>();
    for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements(); ) {
        key = e.nextElement();
        m.put(key, req.getHeader(key));
    }
    ctx.setVariable("headers", m);
    Cookie[] cookies = req.getCookies();
    m = new TreeMap<>();
    if (cookies != null && cookies.length != 0) {
        for (Cookie co : cookies) {
            m.put(co.getName(), co.getValue());
        }
    }
    ctx.setVariable("cookies", m);
    Properties properties = System.getProperties();
    m = new TreeMap<>();
    for (Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) {
        key = (String) e.nextElement();
        m.put(key, (String) properties.get(key));
    }
    ctx.setVariable("systemprops", m);
    Map<String, String> envVar = System.getenv();
    m = new TreeMap<>(envVar);
    ctx.setVariable("envvar", m);
    // The metadata server is only on a production system
    if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
        m = new TreeMap<>();
        for (String k : metaPath) {
            m.put(k, fetchMetadata(k));
        }
        ctx.setVariable("Metadata", m.descendingMap());
        m = new TreeMap<>();
        for (String k : metaServiceAcct) {
            // substitute a service account for {account}
            k = k.replace("{account}", appIdentity.getServiceAccountName());
            m.put(k, fetchMetadata(k));
        }
        ctx.setVariable("sam", m.descendingMap());
        // Recursivly get all info about service accounts -- Note tokens are leftout by default.
        ctx.setVariable("rsa", fetchJsonMetadata("/computeMetadata/v1/instance/service-accounts/?recursive=true"));
        // Recursivly get all data on Metadata server.
        ctx.setVariable("ram", fetchJsonMetadata("/?recursive=true"));
    }
    templateEngine.process("index", ctx, resp.getWriter());
}
Also used : Cookie(javax.servlet.http.Cookie) AppIdentityService(com.google.appengine.api.appidentity.AppIdentityService) WebContext(org.thymeleaf.context.WebContext) Enumeration(java.util.Enumeration) ApiProxy(com.google.apphosting.api.ApiProxy) TreeMap(java.util.TreeMap) Properties(java.util.Properties)

Example 4 with WebContext

use of org.thymeleaf.context.WebContext in project java-docs-samples by GoogleCloudPlatform.

the class GaeInfoServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String key = "";
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    WebContext ctx = new WebContext(req, resp, getServletContext(), req.getLocale());
    resp.setContentType("text/html");
    ctx.setVariable("production", SystemProperty.environment.value().name());
    ctx.setVariable("ServiceAccountName", appIdentity.getServiceAccountName());
    ctx.setVariable("gcs", appIdentity.getDefaultGcsBucketName());
    ctx.setVariable("appId", SystemProperty.applicationId.get());
    ctx.setVariable("appVer", SystemProperty.applicationVersion.get());
    ctx.setVariable("version", SystemProperty.version.get());
    ctx.setVariable("environment", SystemProperty.environment.get());
    // Environment Atributes
    ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
    Map<String, Object> attr = env.getAttributes();
    TreeMap<String, String> m = new TreeMap<>();
    for (String k : attr.keySet()) {
        Object o = attr.get(k);
        if (o.getClass().getCanonicalName().equals("java.lang.String")) {
            m.put(k, (String) o);
        } else if (o.getClass().getCanonicalName().equals("java.lang.Boolean")) {
            m.put(k, ((Boolean) o).toString());
        } else {
            m.put(k, "a " + o.getClass().getCanonicalName());
        }
    }
    ctx.setVariable("attribs", m);
    m = new TreeMap<>();
    for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements(); ) {
        key = e.nextElement();
        m.put(key, req.getHeader(key));
    }
    ctx.setVariable("headers", m);
    Cookie[] cookies = req.getCookies();
    m = new TreeMap<>();
    if (cookies != null && cookies.length != 0) {
        for (Cookie co : cookies) {
            m.put(co.getName(), co.getValue());
        }
    }
    ctx.setVariable("cookies", m);
    Properties properties = System.getProperties();
    m = new TreeMap<>();
    for (Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) {
        key = (String) e.nextElement();
        m.put(key, (String) properties.get(key));
    }
    ctx.setVariable("systemprops", m);
    Map<String, String> envVar = System.getenv();
    m = new TreeMap<>(envVar);
    ctx.setVariable("envvar", m);
    // The metadata server is only on a production system
    if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
        m = new TreeMap<>();
        for (String k : metaPath) {
            m.put(k, fetchMetadata(k));
        }
        ctx.setVariable("Metadata", m.descendingMap());
        m = new TreeMap<>();
        for (String k : metaServiceAcct) {
            // substitute a service account for {account}
            k = k.replace("{account}", appIdentity.getServiceAccountName());
            m.put(k, fetchMetadata(k));
        }
        ctx.setVariable("sam", m.descendingMap());
        // Recursivly get all info about service accounts -- Note tokens are leftout by default.
        ctx.setVariable("rsa", fetchJsonMetadata("/computeMetadata/v1/instance/service-accounts/?recursive=true"));
        // Recursivly get all data on Metadata server.
        ctx.setVariable("ram", fetchJsonMetadata("/?recursive=true"));
    }
    templateEngine.process("index", ctx, resp.getWriter());
}
Also used : Cookie(javax.servlet.http.Cookie) AppIdentityService(com.google.appengine.api.appidentity.AppIdentityService) WebContext(org.thymeleaf.context.WebContext) Enumeration(java.util.Enumeration) ApiProxy(com.google.apphosting.api.ApiProxy) TreeMap(java.util.TreeMap) Properties(java.util.Properties)

Example 5 with WebContext

use of org.thymeleaf.context.WebContext in project java-docs-samples by GoogleCloudPlatform.

the class MetadataServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String defaultServiceAccount = "";
    WebContext ctx = new WebContext(req, resp, getServletContext(), req.getLocale());
    resp.setContentType("text/html");
    String environment = (String) System.getProperties().get("com.google.appengine.runtime.environment");
    ctx.setVariable("production", environment);
    // The metadata server is only on a production system
    if (environment.equals("Production")) {
        TreeMap<String, String> m = new TreeMap<>();
        for (String key : metaPath) {
            m.put(key, fetchMetadata(key));
            if (key.contains("default/email")) {
                defaultServiceAccount = m.get(key);
            }
        }
        ctx.setVariable("Metadata", m.descendingMap());
        m = new TreeMap<>();
        for (String key : metaServiceAcct) {
            // substitute a service account for {account}
            key = key.replace("{account}", defaultServiceAccount);
            m.put(key, fetchMetadata(key));
        }
        ctx.setVariable("sam", m.descendingMap());
        // Recursivly get all info about service accounts -- Note tokens are leftout by default.
        ctx.setVariable("rsa", fetchJsonMetadata("/computeMetadata/v1/instance/service-accounts/?recursive=true"));
        // Recursivly get all data on Metadata server.
        ctx.setVariable("ram", fetchJsonMetadata("/?recursive=true"));
    }
    templateEngine.process("index", ctx, resp.getWriter());
}
Also used : WebContext(org.thymeleaf.context.WebContext) TreeMap(java.util.TreeMap)

Aggregations

WebContext (org.thymeleaf.context.WebContext)9 TreeMap (java.util.TreeMap)3 AppIdentityService (com.google.appengine.api.appidentity.AppIdentityService)2 ApiProxy (com.google.apphosting.api.ApiProxy)2 Enumeration (java.util.Enumeration)2 Properties (java.util.Properties)2 ServletContext (javax.servlet.ServletContext)2 Cookie (javax.servlet.http.Cookie)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 Context (org.nutz.lang.util.Context)1 ConversionService (org.springframework.core.convert.ConversionService)1 WebDataBinder (org.springframework.web.bind.WebDataBinder)1 ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)1 XmlWebApplicationContext (org.springframework.web.context.support.XmlWebApplicationContext)1