Search in sources :

Example 1 with RequestArguments

use of com.tvd12.ezyhttp.server.core.request.RequestArguments in project ezyhttp by youngmonkeys.

the class BlockingServlet method newRequestArguments.

protected RequestArguments newRequestArguments(HttpMethod method, String uriTemplate, HttpServletRequest request, HttpServletResponse response) {
    SimpleRequestArguments arguments = new SimpleRequestArguments();
    arguments.setDebug(debug);
    arguments.setMethod(method);
    arguments.setRequest(request);
    arguments.setResponse(response);
    arguments.setUriTemplate(uriTemplate);
    arguments.setCookies(request.getCookies());
    arguments.setObjectMapper(objectMapper);
    arguments.setRedirectionAttributesFromCookie();
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        String[] paramValues = request.getParameterValues(paramName);
        arguments.setParameter(paramName, paramValues);
    }
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        arguments.setHeader(headerName, headerValue);
    }
    return arguments;
}
Also used : SimpleRequestArguments(com.tvd12.ezyhttp.server.core.request.SimpleRequestArguments)

Example 2 with RequestArguments

use of com.tvd12.ezyhttp.server.core.request.RequestArguments in project ezyhttp by youngmonkeys.

the class BlockingServlet method handleRequest.

@SuppressWarnings("MethodLength")
protected void handleRequest(HttpMethod method, HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestURI = request.getRequestURI();
    String matchedURI = requestHandlerManager.getMatchedURI(method, requestURI);
    if (matchedURI == null) {
        if (!handleError(method, request, response, HttpServletResponse.SC_NOT_FOUND)) {
            responseString(response, "uri " + requestURI + " not found");
        }
        return;
    }
    request.setAttribute(CoreConstants.ATTRIBUTE_MATCHED_URI, matchedURI);
    boolean isManagementURI = requestURIManager.isManagementURI(method, matchedURI);
    if (isManagementURI && !exposeManagementURIs && request.getServerPort() != managementPort) {
        handleError(method, request, response, HttpServletResponse.SC_NOT_FOUND);
        logger.warn("a normal client's not allowed call to: {}, " + "please check your proxy configuration", requestURI);
        return;
    }
    RequestHandler requestHandler = requestHandlerManager.getHandler(method, matchedURI, isManagementURI);
    if (requestHandler == RequestHandler.EMPTY) {
        if (!handleError(method, request, response, HttpServletResponse.SC_METHOD_NOT_ALLOWED)) {
            responseString(response, "method " + method + " not allowed");
        }
        return;
    }
    boolean acceptableRequest = false;
    boolean syncResponse = true;
    String uriTemplate = requestHandler.getRequestURI();
    RequestArguments arguments = newRequestArguments(method, uriTemplate, request, response);
    try {
        acceptableRequest = preHandleRequest(arguments, requestHandler);
        if (acceptableRequest) {
            if (requestHandler.isAsync()) {
                syncResponse = false;
                AsyncContext asyncContext = request.startAsync(request, response);
                if (asyncDefaultTimeout > 0) {
                    asyncContext.setTimeout(asyncDefaultTimeout);
                }
                asyncContext.addListener(newAsyncListener(arguments, requestHandler));
                requestHandler.handle(arguments);
            } else {
                Object responseData = requestHandler.handle(arguments);
                String responseContentType = requestHandler.getResponseContentType();
                if (responseContentType != null) {
                    response.setContentType(responseContentType);
                }
                if (responseData != null) {
                    handleResponseData(request, response, responseData);
                } else {
                    response.setStatus(HttpServletResponse.SC_OK);
                }
            }
        } else {
            handleError(method, request, response, HttpServletResponse.SC_NOT_ACCEPTABLE);
        }
    } catch (Exception e) {
        handleException(method, arguments, e);
    } finally {
        if (syncResponse) {
            if (acceptableRequest) {
                postHandleRequest(arguments, requestHandler);
            }
            arguments.release();
        }
    }
}
Also used : RequestHandler(com.tvd12.ezyhttp.server.core.handler.RequestHandler) AsyncContext(javax.servlet.AsyncContext) RequestArguments(com.tvd12.ezyhttp.server.core.request.RequestArguments) SimpleRequestArguments(com.tvd12.ezyhttp.server.core.request.SimpleRequestArguments) ServletException(javax.servlet.ServletException) DeserializeValueException(com.tvd12.ezyhttp.core.exception.DeserializeValueException) IOException(java.io.IOException) HttpRequestException(com.tvd12.ezyhttp.core.exception.HttpRequestException)

Example 3 with RequestArguments

use of com.tvd12.ezyhttp.server.core.request.RequestArguments in project ezyhttp by youngmonkeys.

the class ResourceRequestHandler method handle.

@Override
public Object handle(RequestArguments arguments) throws Exception {
    AsyncContext asyncContext = arguments.getAsyncContext();
    if (defaultTimeout > 0) {
        asyncContext.setTimeout(defaultTimeout);
    }
    HttpServletResponse servletResponse = (HttpServletResponse) asyncContext.getResponse();
    InputStream inputStream = inputStreamLoader.load(resourcePath);
    OutputStream outputStream = servletResponse.getOutputStream();
    try {
        downloadManager.drainAsync(inputStream, outputStream, new EzyResultCallback<Boolean>() {

            @Override
            public void onResponse(Boolean response) {
                processWithLogException(inputStream::close);
                servletResponse.setContentType(getResponseContentType());
                servletResponse.setStatus(StatusCodes.OK);
                asyncContext.complete();
            }

            @Override
            public void onException(Exception e) {
                processWithLogException(inputStream::close);
                servletResponse.setStatus(StatusCodes.INTERNAL_SERVER_ERROR);
                asyncContext.complete();
            }
        });
    } catch (Exception e) {
        processWithLogException(inputStream::close);
        servletResponse.setStatus(StatusCodes.INTERNAL_SERVER_ERROR);
        asyncContext.complete();
    }
    return ResponseEntity.ASYNC;
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) EzyProcessor.processWithLogException(com.tvd12.ezyfox.util.EzyProcessor.processWithLogException)

Example 4 with RequestArguments

use of com.tvd12.ezyhttp.server.core.request.RequestArguments in project ezyhttp by youngmonkeys.

the class AbstractRequestHandlerTest method handleExceptionAndAsync.

@Test
public void handleExceptionAndAsync() throws Exception {
    // given
    ExResponse response = new ExResponse("Hello World");
    ExRequestHandler sut = new ExRequestHandler() {

        @Override
        public Object handleRequest(RequestArguments arguments) throws Exception {
            throw new Exception("just test");
        }

        @Override
        protected Object handleException(RequestArguments arguments, Exception e) {
            return response;
        }
    };
    RequestArguments requestArguments = mock(RequestArguments.class);
    when(requestArguments.isAsyncStarted()).thenReturn(true);
    AsyncContext asyncContext = mock(AsyncContext.class);
    when(requestArguments.getAsyncContext()).thenReturn(asyncContext);
    // when
    Object actual = sut.handle(requestArguments);
    // then
    Asserts.assertEquals(response, actual);
    verify(asyncContext, times(1)).complete();
}
Also used : AsyncContext(javax.servlet.AsyncContext) RequestArguments(com.tvd12.ezyhttp.server.core.request.RequestArguments) DeserializeHeaderException(com.tvd12.ezyhttp.core.exception.DeserializeHeaderException) DeserializePathVariableException(com.tvd12.ezyhttp.core.exception.DeserializePathVariableException) DeserializeBodyException(com.tvd12.ezyhttp.core.exception.DeserializeBodyException) DeserializeCookieException(com.tvd12.ezyhttp.core.exception.DeserializeCookieException) DeserializeParameterException(com.tvd12.ezyhttp.core.exception.DeserializeParameterException) HttpBadRequestException(com.tvd12.ezyhttp.core.exception.HttpBadRequestException) Test(org.testng.annotations.Test)

Example 5 with RequestArguments

use of com.tvd12.ezyhttp.server.core.request.RequestArguments in project ezyhttp by youngmonkeys.

the class ResourceRequestHandlerTest method handleWithDrainExceptionTest.

@Test
public void handleWithDrainExceptionTest() throws Exception {
    // given
    String resourcePath = "static/index.html";
    String resourceURI = "/index.html";
    String resourceExtension = "html";
    ResourceDownloadManager downloadManager = new ResourceDownloadManager();
    ResourceRequestHandler sut = new ResourceRequestHandler(resourcePath, resourceURI, resourceExtension, new EzyAnywayInputStreamLoader(), downloadManager);
    RequestArguments arguments = mock(RequestArguments.class);
    AsyncContext asyncContext = mock(AsyncContext.class);
    when(arguments.getAsyncContext()).thenReturn(asyncContext);
    HttpServletResponse response = mock(HttpServletResponse.class);
    when(asyncContext.getResponse()).thenReturn(response);
    ServletOutputStream outputStream = mock(ServletOutputStream.class);
    when(response.getOutputStream()).thenReturn(outputStream);
    doThrow(IOException.class).when(outputStream).write(any(byte[].class), anyInt(), anyInt());
    when(asyncContext.getResponse()).thenReturn(response);
    // when
    sut.handle(arguments);
    // then
    Asserts.assertEquals(HttpMethod.GET, sut.getMethod());
    Asserts.assertEquals("/index.html", sut.getRequestURI());
    Asserts.assertEquals(ContentTypes.TEXT_HTML_UTF8, sut.getResponseContentType());
    Thread.sleep(300);
    downloadManager.stop();
    verify(arguments, times(1)).getAsyncContext();
    verify(response, times(1)).getOutputStream();
    verify(response, times(1)).setStatus(StatusCodes.INTERNAL_SERVER_ERROR);
    verify(asyncContext, times(1)).getResponse();
    verify(asyncContext, times(1)).complete();
}
Also used : EzyAnywayInputStreamLoader(com.tvd12.ezyfox.stream.EzyAnywayInputStreamLoader) ResourceDownloadManager(com.tvd12.ezyhttp.core.resources.ResourceDownloadManager) ResourceRequestHandler(com.tvd12.ezyhttp.server.core.handler.ResourceRequestHandler) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) RequestArguments(com.tvd12.ezyhttp.server.core.request.RequestArguments) Test(org.testng.annotations.Test)

Aggregations

RequestArguments (com.tvd12.ezyhttp.server.core.request.RequestArguments)7 AsyncContext (javax.servlet.AsyncContext)6 Test (org.testng.annotations.Test)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 ResourceRequestHandler (com.tvd12.ezyhttp.server.core.handler.ResourceRequestHandler)4 HttpBadRequestException (com.tvd12.ezyhttp.core.exception.HttpBadRequestException)3 ResourceDownloadManager (com.tvd12.ezyhttp.core.resources.ResourceDownloadManager)3 ServletOutputStream (javax.servlet.ServletOutputStream)3 DeserializeBodyException (com.tvd12.ezyhttp.core.exception.DeserializeBodyException)2 DeserializeCookieException (com.tvd12.ezyhttp.core.exception.DeserializeCookieException)2 DeserializeHeaderException (com.tvd12.ezyhttp.core.exception.DeserializeHeaderException)2 DeserializeParameterException (com.tvd12.ezyhttp.core.exception.DeserializeParameterException)2 DeserializePathVariableException (com.tvd12.ezyhttp.core.exception.DeserializePathVariableException)2 DeserializeValueException (com.tvd12.ezyhttp.core.exception.DeserializeValueException)2 HttpRequestException (com.tvd12.ezyhttp.core.exception.HttpRequestException)2 SimpleRequestArguments (com.tvd12.ezyhttp.server.core.request.SimpleRequestArguments)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2 ServletException (javax.servlet.ServletException)2