Search in sources :

Example 1 with ResponseStreams

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

the class DiagnosticErrorRenderer method renderResult.

public void renderResult(Context context, Result result) throws IOException {
    String out = render();
    // set context response content type
    result.contentType("text/html");
    result.charset("utf-8");
    ResponseStreams responseStreams = context.finalizeHeaders(result);
    try (Writer w = responseStreams.getWriter()) {
        w.write(out);
        w.flush();
        w.close();
    }
}
Also used : ResponseStreams(ninja.utils.ResponseStreams) PrintWriter(java.io.PrintWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 2 with ResponseStreams

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

the class Result method renderRaw.

/**
     * This method directly renders the byte array 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.
     * 
     * @param bytes The bytes to render.
     * @return A result that will render the string directly to the output stream.
     */
public Result renderRaw(final byte[] bytes) {
    Renderable renderable = new Renderable() {

        @Override
        public void render(Context context, Result result) {
            if (result.getContentType() == null) {
                result.contentType(Result.APPLICATION_OCTET_STREAM);
            }
            ResponseStreams responseStreams = context.finalizeHeaders(result);
            try (OutputStream outputStream = responseStreams.getOutputStream()) {
                outputStream.write(bytes);
            } catch (IOException ioException) {
                throw new InternalServerErrorException(ioException);
            }
        }
    };
    render(renderable);
    return this;
}
Also used : ResponseStreams(ninja.utils.ResponseStreams) OutputStream(java.io.OutputStream) InternalServerErrorException(ninja.exceptions.InternalServerErrorException) IOException(java.io.IOException)

Example 3 with ResponseStreams

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

the class UploadController method uploadFinish.

/**
     * 
     * This upload method expects a file and simply displays the file in the
     * multipart upload again to the user (in the correct mime encoding).
     * 
     * @param context
     * @return
     * @throws Exception
     */
public Result uploadFinish(Context context) throws Exception {
    // we are using a renderable inner class to stream the input again to
    // the user
    Renderable renderable = new Renderable() {

        @Override
        public void render(Context context, Result result) {
            try {
                // make sure the context really is a multipart context...
                if (context.isMultipart()) {
                    // This is the iterator we can use to iterate over the
                    // contents
                    // of the request.
                    FileItemIterator fileItemIterator = context.getFileItemIterator();
                    while (fileItemIterator.hasNext()) {
                        FileItemStream item = fileItemIterator.next();
                        String name = item.getFieldName();
                        InputStream stream = item.openStream();
                        String contentType = item.getContentType();
                        if (contentType != null) {
                            result.contentType(contentType);
                        } else {
                            contentType = mimeTypes.getMimeType(name);
                        }
                        ResponseStreams responseStreams = context.finalizeHeaders(result);
                        if (item.isFormField()) {
                            System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
                        } else {
                            System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
                            // Process the input stream
                            ByteStreams.copy(stream, responseStreams.getOutputStream());
                        }
                    }
                }
            } catch (IOException | FileUploadException exception) {
                throw new InternalServerErrorException(exception);
            }
        }
    };
    return new Result(200).render(renderable);
}
Also used : Context(ninja.Context) Renderable(ninja.Renderable) ResponseStreams(ninja.utils.ResponseStreams) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) InternalServerErrorException(ninja.exceptions.InternalServerErrorException) IOException(java.io.IOException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException) Result(ninja.Result)

Example 4 with ResponseStreams

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

the class TemplateEngineFreemarkerTest method before.

@Before
public void before() throws Exception {
    //Setup that allows to to execute invoke(...) in a very minimal version.
    when(ninjaProperties.getWithDefault(FREEMARKER_CONFIGURATION_FILE_SUFFIX, ".ftl.html")).thenReturn(".ftl.html");
    templateEngineFreemarker = new TemplateEngineFreemarker(messages, lang, logger, templateEngineHelper, templateEngineManager, templateEngineFreemarkerReverseRouteMethod, templateEngineFreemarkerAssetsAtMethod, templateEngineFreemarkerWebJarsAtMethod, ninjaProperties);
    when(lang.getLanguage(any(Context.class), any(Optional.class))).thenReturn(Optional.<String>empty());
    Session session = Mockito.mock(Session.class);
    when(session.isEmpty()).thenReturn(true);
    when(context.getSession()).thenReturn(session);
    when(context.getRoute()).thenReturn(route);
    when(lang.getLocaleFromStringOrDefault(any(Optional.class))).thenReturn(Locale.ENGLISH);
    FlashScope flashScope = Mockito.mock(FlashScope.class);
    Map<String, String> flashScopeData = new HashMap<>();
    when(flashScope.getCurrentFlashCookieData()).thenReturn(flashScopeData);
    when(context.getFlashScope()).thenReturn(flashScope);
    when(templateEngineHelper.getTemplateForResult(any(Route.class), any(Result.class), Mockito.anyString())).thenReturn("views/template.ftl.html");
    writer = new StringWriter();
    ResponseStreams responseStreams = mock(ResponseStreams.class);
    when(context.finalizeHeaders(any(Result.class))).thenReturn(responseStreams);
    when(responseStreams.getWriter()).thenReturn(writer);
}
Also used : Context(ninja.Context) Optional(java.util.Optional) StringWriter(java.io.StringWriter) ResponseStreams(ninja.utils.ResponseStreams) HashMap(java.util.HashMap) FlashScope(ninja.session.FlashScope) Route(ninja.Route) Session(ninja.session.Session) Result(ninja.Result) Before(org.junit.Before)

Example 5 with ResponseStreams

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

the class TemplateEngineJsonP method invoke.

@Override
public void invoke(Context context, Result result) {
    ResponseStreams responseStreams = context.finalizeHeaders(result);
    String callback = getCallbackName(context);
    try (OutputStream outputStream = responseStreams.getOutputStream()) {
        objectMapper.writeValue(outputStream, new JSONPObject(callback, result.getRenderable()));
    } catch (IOException e) {
        logger.error("Error while rendering jsonp.", e);
    }
}
Also used : ResponseStreams(ninja.utils.ResponseStreams) OutputStream(java.io.OutputStream) JSONPObject(com.fasterxml.jackson.databind.util.JSONPObject) IOException(java.io.IOException)

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