Search in sources :

Example 6 with WriteListener

use of javax.servlet.WriteListener in project groovity by disney.

the class GroovityServlet method service.

/**
 * Primary request entry method for this servlet
 *
 * see {@link HttpServlet#service(HttpServletRequest, HttpServletResponse)}
 */
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    GroovityError error = null;
    try {
        Processor processor = groovityScriptViewFactory.createProcessor(req);
        if (processor != null) {
            if (req.getMethod().equals("HEAD")) {
                // prevent any body from being written, but we'll capture
                // the length
                final AtomicLong length = new AtomicLong(0);
                final AtomicBoolean scriptSetLength = new AtomicBoolean(false);
                final AtomicReference<PrintWriter> respWriter = new AtomicReference<PrintWriter>(null);
                final ServletOutputStream nullStream = new ServletOutputStream() {

                    @Override
                    public void write(int b) throws IOException {
                        length.incrementAndGet();
                    }

                    @Override
                    public void write(byte[] buf, int offset, int len) throws IOException {
                        length.addAndGet(len);
                    }

                    public void setWriteListener(WriteListener arg0) {
                    }

                    public boolean isReady() {
                        return true;
                    }
                };
                processor.process(req, new HttpServletResponseWrapper(res) {

                    PrintWriter writer;

                    @Override
                    public ServletOutputStream getOutputStream() throws IOException {
                        return nullStream;
                    }

                    @Override
                    public PrintWriter getWriter() throws UnsupportedEncodingException {
                        if (writer == null) {
                            writer = new PrintWriter(new OutputStreamWriter(nullStream, getCharacterEncoding()));
                            respWriter.set(writer);
                        }
                        return writer;
                    }

                    @Override
                    public void setContentLength(int len) {
                        res.setContentLength(len);
                        scriptSetLength.set(true);
                    }
                });
                if (!scriptSetLength.get()) {
                    if (respWriter.get() != null) {
                        respWriter.get().flush();
                    }
                    res.setContentLength((int) length.get());
                }
            } else {
                processor.process(req, res);
            }
        } else {
            error = new GroovityError();
            Object acceptMethods = req.getAttribute(REQUEST_ATTRIBUTE_ALLOW_METHODS);
            if (acceptMethods != null && acceptMethods instanceof Collection) {
                @SuppressWarnings("unchecked") Collection<String> am = (Collection<String>) acceptMethods;
                String sep = "";
                StringBuilder sb = new StringBuilder();
                for (Object m : am) {
                    String method = m.toString();
                    sb.append(sep).append(method);
                    sep = ", ";
                }
                res.setHeader("Allow", sb.toString());
                error.setStatus(405);
                error.setMessage("Allowed methods for " + req.getRequestURI() + " are " + sb.toString());
            } else {
                error.setStatus(404);
            }
        }
    } catch (Throwable e) {
        error = new GroovityError();
        error.setCause(e);
        error.setStatus(500);
    }
    if (error != null) {
        error.setReason(EnglishReasonPhraseCatalog.INSTANCE.getReason(error.getStatus(), res.getLocale()));
        String uri = req.getRequestURI();
        if (req.getQueryString() != null) {
            uri = uri.concat("?").concat(req.getQueryString());
        }
        error.setUri(uri);
        req.setAttribute(GroovityScriptView.GROOVITY_ERROR, error);
        boolean handled = false;
        GroovityErrorHandlerChain handlers = groovityScriptViewFactory.getErrorHandlers();
        if (handlers != null) {
            handled = handlers.handleError(req, res, error);
        }
        if (!handled) {
            Throwable cause = error.getCause();
            if (cause != null) {
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                }
                throw new ServletException(cause);
            } else {
                res.sendError(error.getStatus(), error.getMessage());
            }
        }
    }
}
Also used : Processor(com.disney.groovity.servlet.GroovityScriptView.Processor) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) GroovityError(com.disney.groovity.servlet.error.GroovityError) ServletException(javax.servlet.ServletException) WriteListener(javax.servlet.WriteListener) PrintWriter(java.io.PrintWriter) GroovityErrorHandlerChain(com.disney.groovity.servlet.error.GroovityErrorHandlerChain) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) Collection(java.util.Collection) OutputStreamWriter(java.io.OutputStreamWriter)

Example 7 with WriteListener

use of javax.servlet.WriteListener in project wicket by apache.

the class MockHttpServletResponse method initialize.

/**
 * Reset the response ready for reuse.
 */
public void initialize() {
    cookies.clear();
    headers.clear();
    errorMessage = null;
    redirectLocation = null;
    status = HttpServletResponse.SC_OK;
    characterEncoding = "UTF-8";
    locale = null;
    byteStream = new ByteArrayOutputStream();
    servletStream = new ServletOutputStream() {

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) {
            byteStream.write(b);
        }
    };
    stringWriter = new StringWriter();
    printWriter = new PrintWriter(stringWriter) {

        @Override
        public void close() {
        // Do nothing
        }

        @Override
        public void flush() {
        // Do nothing
        }
    };
    mode = MODE_NONE;
}
Also used : StringWriter(java.io.StringWriter) ServletOutputStream(javax.servlet.ServletOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) WriteListener(javax.servlet.WriteListener) PrintWriter(java.io.PrintWriter)

Example 8 with WriteListener

use of javax.servlet.WriteListener in project teiid by teiid.

the class TestODataSQLBuilder method setup.

private BaseState setup(String ddl, String url, String method, ServletInputStream stream, BaseState state) throws Exception {
    Client client = Mockito.mock(Client.class);
    DDLHolder model = new DDLHolder("PM1", ddl);
    TransformationMetadata metadata = RealMetadataFactory.fromDDL("vdb", model);
    MetadataStore store = metadata.getMetadataStore();
    // TranslationUtility utility = new TranslationUtility(metadata);
    OData odata = OData4Impl.newInstance();
    org.teiid.metadata.Schema teiidSchema = store.getSchema("PM1");
    CsdlSchema schema = ODataSchemaBuilder.buildMetadata("vdb", teiidSchema);
    TeiidEdmProvider edmProvider = new TeiidEdmProvider("baseuri", schema, "x");
    ServiceMetadata serviceMetadata = odata.createServiceMetadata(edmProvider, Collections.<EdmxReference>emptyList());
    ODataHttpHandler handler = odata.createHandler(serviceMetadata);
    Hashtable<String, String> headers = new Hashtable<String, String>();
    headers.put("Content-Type", "application/json");
    Mockito.stub(client.getMetadataStore()).toReturn(store);
    Mockito.stub(client.executeCount(Mockito.any(Query.class), Mockito.anyListOf(SQLParameter.class))).toReturn(new CountResponse() {

        @Override
        public int getCount() {
            return 10;
        }
    });
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.stub(request.getHeaderNames()).toReturn(headers.keys());
    Mockito.stub(request.getHeaders("Content-Type")).toReturn(headers.elements());
    Mockito.stub(request.getMethod()).toReturn(method);
    String requestURL = url;
    String queryString = "";
    int idx = url.indexOf("?");
    if (idx != -1) {
        requestURL = url.substring(0, idx);
        queryString = url.substring(idx + 1);
    }
    Mockito.stub(request.getRequestURL()).toReturn(new StringBuffer(requestURL));
    Mockito.stub(request.getQueryString()).toReturn(queryString);
    Mockito.stub(request.getServletPath()).toReturn("");
    Mockito.stub(request.getContextPath()).toReturn("/odata4/vdb/PM1");
    Mockito.stub(request.getInputStream()).toReturn(stream);
    final StringBuffer sb = new StringBuffer();
    ServletOutputStream out = new ServletOutputStream() {

        @Override
        public void write(int b) throws IOException {
            sb.append((char) b);
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }
    };
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Mockito.stub(response.getOutputStream()).toReturn(out);
    try {
        TeiidServiceHandler tsh = new TeiidServiceHandler("PM1");
        tsh.setPrepared(false);
        TeiidServiceHandler.setClient(client);
        handler.register(tsh);
        handler.process(request, response);
    } finally {
        TeiidServiceHandler.setClient(null);
    }
    ArgumentCaptor<Integer> statusCapture = ArgumentCaptor.forClass(Integer.class);
    Mockito.verify(response).setStatus(statusCapture.capture());
    state.client = client;
    state.response = sb.toString();
    state.status = statusCapture.getValue();
    return state;
}
Also used : Query(org.teiid.query.sql.lang.Query) ServletOutputStream(javax.servlet.ServletOutputStream) CsdlSchema(org.apache.olingo.commons.api.edm.provider.CsdlSchema) HttpServletRequest(javax.servlet.http.HttpServletRequest) TeiidEdmProvider(org.teiid.olingo.service.TeiidEdmProvider) DDLHolder(org.teiid.query.unittest.RealMetadataFactory.DDLHolder) Client(org.teiid.odata.api.Client) WriteListener(javax.servlet.WriteListener) OData(org.apache.olingo.server.api.OData) TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) Hashtable(java.util.Hashtable) SQLParameter(org.teiid.odata.api.SQLParameter) CountResponse(org.teiid.odata.api.CountResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ODataHttpHandler(org.apache.olingo.server.api.ODataHttpHandler) MetadataStore(org.teiid.metadata.MetadataStore) TeiidServiceHandler(org.teiid.olingo.service.TeiidServiceHandler) ServiceMetadata(org.apache.olingo.server.api.ServiceMetadata)

Example 9 with WriteListener

use of javax.servlet.WriteListener in project structr by structr.

the class HtmlServlet method doGet.

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {
    final Authenticator auth = getConfig().getAuthenticator();
    List<Page> pages = null;
    boolean requestUriContainsUuids = false;
    SecurityContext securityContext;
    final App app;
    try {
        assertInitialized();
        final String path = request.getPathInfo() != null ? request.getPathInfo() : "/";
        // check for registration (has its own tx because of write access
        if (checkRegistration(auth, request, response, path)) {
            return;
        }
        // check for registration (has its own tx because of write access
        if (checkResetPassword(auth, request, response, path)) {
            return;
        }
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            securityContext = auth.initializeAndExamineRequest(request, response);
            tx.success();
        } catch (AuthenticationException aex) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        app = StructrApp.getInstance(securityContext);
        try (final Tx tx = app.tx()) {
            // Ensure access mode is frontend
            securityContext.setAccessMode(AccessMode.Frontend);
            request.setCharacterEncoding("UTF-8");
            // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
            response.setCharacterEncoding("UTF-8");
            boolean dontCache = false;
            logger.debug("Path info {}", path);
            // don't continue on redirects
            if (response.getStatus() == 302) {
                tx.success();
                return;
            }
            final Principal user = securityContext.getUser(false);
            if (user != null) {
                // Don't cache if a user is logged in
                dontCache = true;
            }
            final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response);
            renderContext.setResourceProvider(config.getResourceProvider());
            final EditMode edit = renderContext.getEditMode(user);
            DOMNode rootElement = null;
            AbstractNode dataNode = null;
            final String[] uriParts = PathHelper.getParts(path);
            if ((uriParts == null) || (uriParts.length == 0)) {
                // find a visible page
                rootElement = findIndexPage(securityContext, pages, edit);
                logger.debug("No path supplied, trying to find index page");
            } else {
                if (rootElement == null) {
                    rootElement = findPage(securityContext, pages, path, edit);
                } else {
                    dontCache = true;
                }
            }
            if (rootElement == null) {
                // No page found
                // In case of a file, try to find a file with the query string in the filename
                final String queryString = request.getQueryString();
                // Look for a file, first include the query string
                File file = findFile(securityContext, request, path + (queryString != null ? "?" + queryString : ""));
                // If no file with query string in the file name found, try without query string
                if (file == null) {
                    file = findFile(securityContext, request, path);
                }
                if (file != null) {
                    streamFile(securityContext, file, request, response, edit);
                    tx.success();
                    return;
                }
                if (uriParts != null) {
                    // store remaining path parts in request
                    final Matcher matcher = threadLocalUUIDMatcher.get();
                    for (int i = 0; i < uriParts.length; i++) {
                        request.setAttribute(uriParts[i], i);
                        matcher.reset(uriParts[i]);
                        // set to "true" if part matches UUID pattern
                        requestUriContainsUuids |= matcher.matches();
                    }
                }
                if (!requestUriContainsUuids) {
                    // Try to find a data node by name
                    dataNode = findFirstNodeByName(securityContext, request, path);
                } else {
                    dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));
                }
                // if (dataNode != null && !(dataNode instanceof Linkable)) {
                if (dataNode != null) {
                    // Last path part matches a data node
                    // Remove last path part and try again searching for a page
                    // clear possible entry points
                    request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY);
                    rootElement = findPage(securityContext, pages, StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit);
                    renderContext.setDetailsDataObject(dataNode);
                    // Start rendering on data node
                    if (rootElement == null && dataNode instanceof DOMNode) {
                        // check visibleForSite here as well
                        if (!(dataNode instanceof Page) || isVisibleForSite(request, (Page) dataNode)) {
                            rootElement = ((DOMNode) dataNode);
                        }
                    }
                }
            }
            // look for pages with HTTP Basic Authentication (must be done as superuser)
            if (rootElement == null) {
                final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path);
                switch(authResult.authState()) {
                    // Element with Basic Auth found and authentication succeeded
                    case Authenticated:
                        final Linkable result = authResult.getRootElement();
                        if (result instanceof Page) {
                            rootElement = (DOMNode) result;
                            securityContext = authResult.getSecurityContext();
                            renderContext.pushSecurityContext(securityContext);
                        } else if (result instanceof File) {
                            streamFile(authResult.getSecurityContext(), (File) result, request, response, EditMode.NONE);
                            tx.success();
                            return;
                        }
                        break;
                    // Page with Basic Auth found but not yet authenticated
                    case MustAuthenticate:
                        final Page errorPage = StructrApp.getInstance().nodeQuery(Page.class).and(StructrApp.key(Page.class, "showOnErrorCodes"), "401", false).getFirst();
                        if (errorPage != null && isVisibleForSite(request, errorPage)) {
                            // set error page
                            rootElement = errorPage;
                            // don't cache the error page
                            dontCache = true;
                        } else {
                            // send error
                            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                            tx.success();
                            return;
                        }
                        break;
                    // no Basic Auth for given path, go on
                    case NoBasicAuth:
                        break;
                }
            }
            // Still nothing found, do error handling
            if (rootElement == null) {
                rootElement = notFound(response, securityContext);
            }
            if (rootElement == null) {
                tx.success();
                return;
            }
            // check dont cache flag on page (if root element is a page)
            // but don't modify true to false
            dontCache |= rootElement.dontCache();
            if (EditMode.WIDGET.equals(edit) || dontCache) {
                setNoCacheHeaders(response);
            }
            if (!securityContext.isVisible(rootElement)) {
                rootElement = notFound(response, securityContext);
                if (rootElement == null) {
                    tx.success();
                    return;
                }
            } else {
                if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) {
                    ServletOutputStream out = response.getOutputStream();
                    out.flush();
                    // response.flushBuffer();
                    out.close();
                } else {
                    // prepare response
                    response.setCharacterEncoding("UTF-8");
                    String contentType = rootElement.getProperty(StructrApp.key(Page.class, "contentType"));
                    if (contentType == null) {
                        // Default
                        contentType = "text/html;charset=UTF-8";
                    }
                    if (contentType.equals("text/html")) {
                        contentType = contentType.concat(";charset=UTF-8");
                    }
                    response.setContentType(contentType);
                    setCustomResponseHeaders(response);
                    final boolean createsRawData = rootElement.getProperty(StructrApp.key(Page.class, "pageCreatesRawData"));
                    // async or not?
                    if (isAsync && !createsRawData) {
                        final AsyncContext async = request.startAsync();
                        final ServletOutputStream out = async.getResponse().getOutputStream();
                        final AtomicBoolean finished = new AtomicBoolean(false);
                        final DOMNode rootNode = rootElement;
                        threadPool.submit(new Runnable() {

                            @Override
                            public void run() {
                                try (final Tx tx = app.tx()) {
                                    // render
                                    rootNode.render(renderContext, 0);
                                    finished.set(true);
                                    tx.success();
                                } catch (Throwable t) {
                                    t.printStackTrace();
                                    logger.warn("Error while rendering page {}: {}", rootNode.getName(), t.getMessage());
                                    try {
                                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                        finished.set(true);
                                    } catch (IOException ex) {
                                        logger.warn("", ex);
                                    }
                                }
                            }
                        });
                        // start output write listener
                        out.setWriteListener(new WriteListener() {

                            @Override
                            public void onWritePossible() throws IOException {
                                try {
                                    final Queue<String> queue = renderContext.getBuffer().getQueue();
                                    while (out.isReady()) {
                                        String buffer = null;
                                        synchronized (queue) {
                                            buffer = queue.poll();
                                        }
                                        if (buffer != null) {
                                            out.print(buffer);
                                        } else {
                                            if (finished.get()) {
                                                async.complete();
                                                // prevent this block from being called again
                                                break;
                                            }
                                            Thread.sleep(1);
                                        }
                                    }
                                } catch (Throwable t) {
                                    logger.warn("", t);
                                }
                            }

                            @Override
                            public void onError(Throwable t) {
                                logger.warn("", t);
                            }
                        });
                    } else {
                        final StringRenderBuffer buffer = new StringRenderBuffer();
                        renderContext.setBuffer(buffer);
                        // render
                        rootElement.render(renderContext, 0);
                        try {
                            response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8"));
                            response.getOutputStream().flush();
                            response.getOutputStream().close();
                        } catch (IOException ioex) {
                            logger.warn("", ioex);
                        }
                    }
                }
            }
            tx.success();
        } catch (FrameworkException fex) {
            logger.error("Exception while processing request: {}", fex.getMessage());
        }
    } catch (FrameworkException fex) {
        logger.error("Exception while processing request: {}", fex.getMessage());
        UiAuthenticator.writeFrameworkException(response, fex);
    } catch (IOException ioex) {
        logger.error("Exception while processing request: {}", ioex.getMessage());
        UiAuthenticator.writeInternalServerError(response);
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) StringRenderBuffer(org.structr.web.common.StringRenderBuffer) AuthenticationException(org.structr.core.auth.exception.AuthenticationException) AbstractNode(org.structr.core.entity.AbstractNode) Matcher(java.util.regex.Matcher) ThreadLocalMatcher(org.structr.common.ThreadLocalMatcher) ServletOutputStream(javax.servlet.ServletOutputStream) Page(org.structr.web.entity.dom.Page) AsyncContext(javax.servlet.AsyncContext) DOMNode(org.structr.web.entity.dom.DOMNode) WriteListener(javax.servlet.WriteListener) Queue(java.util.Queue) UiAuthenticator(org.structr.web.auth.UiAuthenticator) Authenticator(org.structr.core.auth.Authenticator) RenderContext(org.structr.web.common.RenderContext) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SecurityContext(org.structr.common.SecurityContext) EditMode(org.structr.web.common.RenderContext.EditMode) Linkable(org.structr.web.entity.Linkable) AbstractFile(org.structr.web.entity.AbstractFile) File(org.structr.web.entity.File) Principal(org.structr.core.entity.Principal)

Example 10 with WriteListener

use of javax.servlet.WriteListener in project instrumentation-java by census-instrumentation.

the class WriteListenerWrapperTest method testWriteOnPossibleWithContext.

@Test
public void testWriteOnPossibleWithContext() throws IOException, ServletException {
    Key<String> key = Context.<String>key("test-key");
    Context curr = Context.current();
    assertThat(curr).isNotNull();
    final Context parentContext = curr.withValue(key, "parent");
    assertThat(parentContext).isNotNull();
    Context prev = parentContext.attach();
    try {
        WriteListenerWrapper writeListener = new WriteListenerWrapper(new WriteListener() {

            @Override
            public void onWritePossible() throws IOException {
                Context curr = Context.current();
                assertThat(curr).isNotNull();
                assertThat(curr).isEqualTo(parentContext);
            }

            @Override
            public void onError(Throwable t) {
            }
        });
        Context childContext = parentContext.withValue(key, "child");
        assertThat(childContext).isNotNull();
        assertThat(childContext.attach()).isNotNull();
        try {
            writeListener.onWritePossible();
        } finally {
            childContext.detach(parentContext);
        }
    } finally {
        parentContext.detach(prev);
    }
}
Also used : Context(io.grpc.Context) IOException(java.io.IOException) WriteListener(javax.servlet.WriteListener) Test(org.junit.Test)

Aggregations

WriteListener (javax.servlet.WriteListener)31 ServletOutputStream (javax.servlet.ServletOutputStream)27 IOException (java.io.IOException)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 AsyncContext (javax.servlet.AsyncContext)12 Test (org.junit.Test)11 ServletException (javax.servlet.ServletException)10 CountDownLatch (java.util.concurrent.CountDownLatch)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 HttpServlet (javax.servlet.http.HttpServlet)6 InterruptedIOException (java.io.InterruptedIOException)5 ByteBuffer (java.nio.ByteBuffer)5 ReadListener (javax.servlet.ReadListener)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Request (org.eclipse.jetty.server.Request)4 Before (org.junit.Before)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 UncheckedIOException (java.io.UncheckedIOException)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3