Search in sources :

Example 6 with ResponseStreams

use of ninja.utils.ResponseStreams in project ninja by ninjaframework.

the class TemplateEngineJsonPTest method setUp.

@Before
public void setUp() throws IOException {
    logger = mock(Logger.class);
    properties = mock(NinjaProperties.class);
    context = mock(Context.class);
    responseStreams = mock(ResponseStreams.class);
    result = Results.jsonp().render(Collections.singletonList(123));
    objectMapper = new ObjectMapper();
    outputStream = new ByteArrayOutputStream();
    when(properties.getWithDefault("ninja.jsonp.callbackParameter", TemplateEngineJsonP.DEFAULT_CALLBACK_PARAMETER_NAME)).thenReturn("callback");
    when(context.finalizeHeaders(result)).thenReturn(responseStreams);
    when(responseStreams.getOutputStream()).thenReturn(outputStream);
}
Also used : Context(ninja.Context) ResponseStreams(ninja.utils.ResponseStreams) NinjaProperties(ninja.utils.NinjaProperties) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Before(org.junit.Before)

Example 7 with ResponseStreams

use of ninja.utils.ResponseStreams in project ninja by ninjaframework.

the class TemplateEngineJsonTest method setUp.

@Before
public void setUp() throws IOException {
    context = mock(Context.class);
    responseStreams = mock(ResponseStreams.class);
    result = mock(Result.class);
    objectMapper = new ObjectMapper();
    outputStream = new ByteArrayOutputStream();
    TestObject testObj = new TestObject();
    testObj.field1 = "field_one";
    testObj.field2 = "field_two";
    when(result.getRenderable()).thenReturn(testObj);
    when(context.finalizeHeaders(result)).thenReturn(responseStreams);
    when(responseStreams.getOutputStream()).thenReturn(outputStream);
}
Also used : Context(ninja.Context) ResponseStreams(ninja.utils.ResponseStreams) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Result(ninja.Result) Before(org.junit.Before)

Example 8 with ResponseStreams

use of ninja.utils.ResponseStreams in project ninja by ninjaframework.

the class TemplateEngineTextTest method setUp.

@Before
public void setUp() throws IOException {
    context = mock(Context.class);
    responseStreams = mock(ResponseStreams.class);
    result = mock(Result.class);
    Map<String, String> map = new TreeMap<String, String>() {

        {
            put("apples", "oranges");
            put("cars", "trucks");
        }
    };
    when(result.getRenderable()).thenReturn(map);
    writer = new StringWriter();
    when(context.finalizeHeaders(result)).thenReturn(responseStreams);
    when(responseStreams.getWriter()).thenReturn(writer);
}
Also used : Context(ninja.Context) ResponseStreams(ninja.utils.ResponseStreams) StringWriter(java.io.StringWriter) TreeMap(java.util.TreeMap) Result(ninja.Result) Before(org.junit.Before)

Example 9 with ResponseStreams

use of ninja.utils.ResponseStreams in project ninja by ninjaframework.

the class TemplateEngineFreemarker method invoke.

@Override
public void invoke(Context context, Result result) {
    Object object = result.getRenderable();
    Map map;
    // if the object is null we simply render an empty map...
    if (object == null) {
        map = Maps.newHashMap();
    } else if (object instanceof Map) {
        map = (Map) object;
    } else {
        // We are getting an arbitrary Object and put that into
        // the root of freemarker
        // If you are rendering something like Results.ok().render(new MyObject())
        // Assume MyObject has a public String name field.            
        // You can then access the fields in the template like that:
        // ${myObject.publicField}            
        String realClassNameLowerCamelCase = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, object.getClass().getSimpleName());
        map = Maps.newHashMap();
        map.put(realClassNameLowerCamelCase, object);
    }
    // set language from framework. You can access
    // it in the templates as ${lang}
    Optional<String> language = lang.getLanguage(context, Optional.of(result));
    if (language.isPresent()) {
        map.put("lang", language.get());
    }
    // You can access the values by their key in the cookie
    if (!context.getSession().isEmpty()) {
        map.put("session", context.getSession().getData());
    }
    map.put("contextPath", context.getContextPath());
    map.put("validation", context.getValidation());
    //////////////////////////////////////////////////////////////////////
    // A method that renders i18n messages and can also render messages with 
    // placeholders directly in your template:
    // E.g.: ${i18n("mykey", myPlaceholderVariable)}
    //////////////////////////////////////////////////////////////////////
    map.put("i18n", new TemplateEngineFreemarkerI18nMethod(messages, context, result));
    Optional<String> requestLang = lang.getLanguage(context, Optional.of(result));
    Locale locale = lang.getLocaleFromStringOrDefault(requestLang);
    map.put("prettyTime", new TemplateEngineFreemarkerPrettyTimeMethod(locale));
    map.put("reverseRoute", templateEngineFreemarkerReverseRouteMethod);
    map.put("assetsAt", templateEngineFreemarkerAssetsAtMethod);
    map.put("webJarsAt", templateEngineFreemarkerWebJarsAtMethod);
    map.put("authenticityToken", new TemplateEngineFreemarkerAuthenticityTokenDirective(context));
    map.put("authenticityForm", new TemplateEngineFreemarkerAuthenticityFormDirective(context));
    ///////////////////////////////////////////////////////////////////////
    // Convenience method to translate possible flash scope keys.
    // !!! If you want to set messages with placeholders please do that
    // !!! in your controller. We only can set simple messages.
    // Eg. A message like "errorMessage=my name is: {0}" => translate in controller and pass directly.
    //     A message like " errorMessage=An error occurred" => use that as errorMessage.  
    //
    // get keys via ${flash.KEYNAME}
    //////////////////////////////////////////////////////////////////////
    Map<String, String> translatedFlashCookieMap = Maps.newHashMap();
    for (Entry<String, String> entry : context.getFlashScope().getCurrentFlashCookieData().entrySet()) {
        String messageValue = null;
        Optional<String> messageValueOptional = messages.get(entry.getValue(), context, Optional.of(result));
        if (!messageValueOptional.isPresent()) {
            messageValue = entry.getValue();
        } else {
            messageValue = messageValueOptional.get();
        }
        // new way
        translatedFlashCookieMap.put(entry.getKey(), messageValue);
    }
    // now we can retrieve flash cookie messages via ${flash.MESSAGE_KEY}
    map.put("flash", translatedFlashCookieMap);
    // Specify the data source where the template files come from.
    // Here I set a file directory for it:
    String templateName = templateEngineHelper.getTemplateForResult(context.getRoute(), result, this.fileSuffix);
    Template freemarkerTemplate = null;
    try {
        freemarkerTemplate = cfg.getTemplate(templateName);
        // Fully buffer the response so in the case of a template error we can 
        // return the applications 500 error message. Without fully buffering 
        // we can't guarantee we haven't flushed part of the response to the
        // client.
        StringWriter buffer = new StringWriter(64 * 1024);
        freemarkerTemplate.process(map, buffer);
        ResponseStreams responseStreams = context.finalizeHeaders(result);
        try (Writer writer = responseStreams.getWriter()) {
            writer.write(buffer.toString());
        }
    } catch (Exception cause) {
        // delegate rendering exception handling back to Ninja
        throwRenderingException(context, result, cause, templateName);
    }
}
Also used : Locale(java.util.Locale) TemplateEngineFreemarkerAuthenticityTokenDirective(ninja.template.directives.TemplateEngineFreemarkerAuthenticityTokenDirective) ResponseStreams(ninja.utils.ResponseStreams) TemplateEngineFreemarkerAuthenticityFormDirective(ninja.template.directives.TemplateEngineFreemarkerAuthenticityFormDirective) RenderingException(ninja.exceptions.RenderingException) TemplateException(freemarker.template.TemplateException) TemplateNotFoundException(freemarker.template.TemplateNotFoundException) IOException(java.io.IOException) ParseException(freemarker.core.ParseException) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) Map(java.util.Map) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 10 with ResponseStreams

use of ninja.utils.ResponseStreams in project ninja by ninjaframework.

the class Result method renderRaw.

/**
     * This method directly renders the String to the output. It completely
     * bypasses any rendering engine.
     *
     * Thus you can render anything you want.
     *
     * Chaining of resultRaw().resultRaw()... is NOT supported. Mixing with
     * render() is NOT supported.
     *
     * It is always recommended to implement your own RenderingEngine OR use
     * existing rendering engines.
     *
     * Example: <code>
     * public Result controllerMethod() {
     *    String customJson = "{\"user\" : \"john@woo.com\"}";
     *
     *    return Results.json().renderRaw(customJson);
     * }
     * </code>
     *
     * @param string
     *            The string to render.
     * @return A result that will render the string directly to the output
     *         stream.
     * @deprecated => use text().render(string), html().render(string),
     *             json().render(string), xml().render(string), or
     *             contentType(type).render(string).
     */
@Deprecated
public Result renderRaw(final String string) {
    Renderable renderable = new Renderable() {

        @Override
        public void render(Context context, Result result) {
            if (result.getContentType() == null) {
                result.contentType(Result.TEXT_PLAIN);
            }
            ResponseStreams resultJsonCustom = context.finalizeHeaders(result);
            try (Writer writer = resultJsonCustom.getWriter()) {
                writer.write(string);
            } catch (IOException ioException) {
                logger.error("Error rendering raw String via renderRaw(...)", ioException);
            }
        }
    };
    render(renderable);
    return this;
}
Also used : ResponseStreams(ninja.utils.ResponseStreams) IOException(java.io.IOException) Writer(java.io.Writer)

Aggregations

ResponseStreams (ninja.utils.ResponseStreams)10 IOException (java.io.IOException)5 Context (ninja.Context)5 StringWriter (java.io.StringWriter)4 Result (ninja.Result)4 Before (org.junit.Before)4 Writer (java.io.Writer)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 OutputStream (java.io.OutputStream)2 InternalServerErrorException (ninja.exceptions.InternalServerErrorException)2 JSONPObject (com.fasterxml.jackson.databind.util.JSONPObject)1 ParseException (freemarker.core.ParseException)1 Template (freemarker.template.Template)1 TemplateException (freemarker.template.TemplateException)1 TemplateNotFoundException (freemarker.template.TemplateNotFoundException)1 InputStream (java.io.InputStream)1 PrintWriter (java.io.PrintWriter)1 HashMap (java.util.HashMap)1 Locale (java.util.Locale)1