Search in sources :

Example 1 with RequestHandler

use of com.tvd12.ezyhttp.server.core.handler.RequestHandler 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 2 with RequestHandler

use of com.tvd12.ezyhttp.server.core.handler.RequestHandler in project ezyhttp by youngmonkeys.

the class ApplicationContextBuilder method addResourceRequestHandlers.

protected void addResourceRequestHandlers(EzyBeanContext beanContext) {
    ResourceResolver resourceResolver = getResourceResolver(beanContext);
    if (resourceResolver == null) {
        return;
    }
    ResourceDownloadManager downloadManager = beanContext.getSingleton(ResourceDownloadManager.class);
    Map<String, Resource> resources = resourceResolver.getResources();
    for (String resourceURI : resources.keySet()) {
        Resource resource = resources.get(resourceURI);
        RequestURI requestURI = new RequestURI(HttpMethod.GET, resourceURI, false, true, true, resource.getFullPath());
        RequestHandler requestHandler = new ResourceRequestHandler(resource.getPath(), resource.getUri(), resource.getExtension(), downloadManager);
        requestHandlerManager.addHandler(requestURI, requestHandler);
    }
}
Also used : ResourceDownloadManager(com.tvd12.ezyhttp.core.resources.ResourceDownloadManager) ResourceRequestHandler(com.tvd12.ezyhttp.server.core.handler.ResourceRequestHandler) RequestHandler(com.tvd12.ezyhttp.server.core.handler.RequestHandler) ResourceRequestHandler(com.tvd12.ezyhttp.server.core.handler.ResourceRequestHandler) ResourceResolver(com.tvd12.ezyhttp.server.core.resources.ResourceResolver) Resource(com.tvd12.ezyhttp.server.core.resources.Resource) RequestURI(com.tvd12.ezyhttp.server.core.request.RequestURI)

Example 3 with RequestHandler

use of com.tvd12.ezyhttp.server.core.handler.RequestHandler in project ezyhttp by youngmonkeys.

the class RequestHandlerManager method addHandler.

public void addHandler(RequestURI uri, RequestHandler handler) {
    RequestHandler old = this.handlers.put(uri, handler);
    if (old != null && !allowOverrideURI) {
        throw new DuplicateURIMappingHandlerException(uri, old, handler);
    }
    this.handledURIs.add(uri.getUri());
    this.logger.info("add mapping uri: {}", uri);
    this.handlerListByURI.computeIfAbsent(uri, k -> new ArrayList<>()).add(handler);
    this.requestURIManager.addHandledURI(uri.getMethod(), uri.getUri());
    if (uri.isApi()) {
        this.requestURIManager.addApiURI(uri.getMethod(), uri.getUri());
        this.requestURIManager.addApiURI(uri.getMethod(), uri.getSameURI());
    }
    if (uri.isAuthenticated()) {
        this.requestURIManager.addAuthenticatedURI(uri.getMethod(), uri.getUri());
        this.requestURIManager.addAuthenticatedURI(uri.getMethod(), uri.getSameURI());
    }
    if (uri.isManagement()) {
        this.requestURIManager.addManagementURI(uri.getMethod(), uri.getUri());
        this.requestURIManager.addManagementURI(uri.getMethod(), uri.getSameURI());
    }
    if (uri.isPayment()) {
        this.requestURIManager.addPaymentURI(uri.getMethod(), uri.getUri());
        this.requestURIManager.addPaymentURI(uri.getMethod(), uri.getSameURI());
    }
    if (EzyStrings.isNotBlank(uri.getFeature())) {
        this.featureURIManager.addFeatureURI(uri.getFeature(), uri.getMethod(), uri.getUri());
        this.featureURIManager.addFeatureURI(uri.getFeature(), uri.getMethod(), uri.getSameURI());
    }
    URITree uriTree = uriTreeByMethod.get(uri.getMethod());
    uriTree.addURI(uri.getUri());
}
Also used : Setter(lombok.Setter) Getter(lombok.Getter) DuplicateURIMappingHandlerException(com.tvd12.ezyhttp.server.core.exception.DuplicateURIMappingHandlerException) EzyLoggable(com.tvd12.ezyfox.util.EzyLoggable) Set(java.util.Set) HashMap(java.util.HashMap) EzyStrings(com.tvd12.ezyfox.io.EzyStrings) EzyDestroyable(com.tvd12.ezyfox.util.EzyDestroyable) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) Map(java.util.Map) HttpMethod(com.tvd12.ezyhttp.core.constant.HttpMethod) Collections(java.util.Collections) URITree(com.tvd12.ezyhttp.core.net.URITree) RequestHandler(com.tvd12.ezyhttp.server.core.handler.RequestHandler) RequestURI(com.tvd12.ezyhttp.server.core.request.RequestURI) URITree(com.tvd12.ezyhttp.core.net.URITree) DuplicateURIMappingHandlerException(com.tvd12.ezyhttp.server.core.exception.DuplicateURIMappingHandlerException) RequestHandler(com.tvd12.ezyhttp.server.core.handler.RequestHandler) ArrayList(java.util.ArrayList)

Example 4 with RequestHandler

use of com.tvd12.ezyhttp.server.core.handler.RequestHandler in project ezyhttp by youngmonkeys.

the class RequestHandlerManager method getHandler.

public RequestHandler getHandler(HttpMethod method, String matchedURI, boolean isManagement) {
    RequestURI requestURI = new RequestURI(method, matchedURI, isManagement);
    RequestHandler handler = handlers.get(requestURI);
    return handler != null ? handler : RequestHandler.EMPTY;
}
Also used : RequestHandler(com.tvd12.ezyhttp.server.core.handler.RequestHandler) RequestURI(com.tvd12.ezyhttp.server.core.request.RequestURI)

Example 5 with RequestHandler

use of com.tvd12.ezyhttp.server.core.handler.RequestHandler in project ezyhttp by youngmonkeys.

the class BlockingServletTest method doGetResponseContentTypeNull.

@Test
public void doGetResponseContentTypeNull() throws Exception {
    // given
    ComponentManager componentManager = ComponentManager.getInstance();
    componentManager.setServerPort(PORT);
    BlockingServlet sut = new BlockingServlet();
    sut.init();
    String requestURI = "/get";
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getMethod()).thenReturn(HttpMethod.GET.toString());
    when(request.getRequestURI()).thenReturn(requestURI);
    when(request.getServerPort()).thenReturn(PORT);
    when(request.getParameterNames()).thenReturn(Collections.enumeration(Collections.singletonList("param")));
    when(request.getParameter("param")).thenReturn("ParameterValue");
    when(request.getParameterValues("param")).thenReturn(new String[] { "ParameterValue" });
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(Collections.singletonList("header")));
    when(request.getHeader("header")).thenReturn("HeaderValue");
    when(request.getCookies()).thenReturn(new Cookie[] { new Cookie("cookie", "CookieValue") });
    HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getContentType()).thenReturn(ContentTypes.APPLICATION_JSON);
    ServletOutputStream outputStream = mock(ServletOutputStream.class);
    when(response.getOutputStream()).thenReturn(outputStream);
    AsyncContext asyncContext = mock(AsyncContext.class);
    when(request.startAsync(request, response)).thenReturn(asyncContext);
    when(request.isAsyncStarted()).thenReturn(true);
    EzyWrap<AsyncListener> asyncListener = new EzyWrap<>();
    doAnswer(it -> {
        asyncListener.setValue(it.getArgumentAt(0, AsyncListener.class));
        return null;
    }).when(asyncContext).addListener(any(AsyncListener.class));
    RequestHandlerManager requestHandlerManager = componentManager.getRequestHandlerManager();
    GetRequestHandlerContentTypeNull requestHandler = new GetRequestHandlerContentTypeNull();
    requestHandlerManager.addHandler(new RequestURI(HttpMethod.GET, requestURI, false), requestHandler);
    // when
    sut.service(request, response);
    asyncListener.getValue().onComplete(new AsyncEvent(asyncContext));
    // then
    verify(request, times(1)).getMethod();
    verify(request, times(1)).getRequestURI();
    verify(asyncContext, times(1)).addListener(any(AsyncListener.class));
    componentManager.destroy();
}
Also used : Cookie(javax.servlet.http.Cookie) RequestCookie(com.tvd12.ezyhttp.server.core.annotation.RequestCookie) EzyWrap(com.tvd12.ezyfox.util.EzyWrap) ServletOutputStream(javax.servlet.ServletOutputStream) BlockingServlet(com.tvd12.ezyhttp.server.core.servlet.BlockingServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) ToString(lombok.ToString) AsyncEvent(javax.servlet.AsyncEvent) HttpServletRequest(javax.servlet.http.HttpServletRequest) AsyncListener(javax.servlet.AsyncListener) RequestHandlerManager(com.tvd12.ezyhttp.server.core.manager.RequestHandlerManager) ComponentManager(com.tvd12.ezyhttp.server.core.manager.ComponentManager) RequestURI(com.tvd12.ezyhttp.server.core.request.RequestURI) Test(org.testng.annotations.Test)

Aggregations

RequestURI (com.tvd12.ezyhttp.server.core.request.RequestURI)30 RequestHandlerManager (com.tvd12.ezyhttp.server.core.manager.RequestHandlerManager)25 Test (org.testng.annotations.Test)25 ComponentManager (com.tvd12.ezyhttp.server.core.manager.ComponentManager)24 BlockingServlet (com.tvd12.ezyhttp.server.core.servlet.BlockingServlet)24 HttpServletRequest (javax.servlet.http.HttpServletRequest)24 HttpServletResponse (javax.servlet.http.HttpServletResponse)24 ToString (lombok.ToString)24 ServletOutputStream (javax.servlet.ServletOutputStream)22 RequestCookie (com.tvd12.ezyhttp.server.core.annotation.RequestCookie)20 Cookie (javax.servlet.http.Cookie)20 RequestInterceptor (com.tvd12.ezyhttp.server.core.interceptor.RequestInterceptor)10 RequestHandler (com.tvd12.ezyhttp.server.core.handler.RequestHandler)7 BodySerializer (com.tvd12.ezyhttp.core.codec.BodySerializer)4 DataConverters (com.tvd12.ezyhttp.core.codec.DataConverters)4 ExceptionHandlerManager (com.tvd12.ezyhttp.server.core.manager.ExceptionHandlerManager)4 UnhandledErrorHandler (com.tvd12.ezyhttp.server.core.handler.UnhandledErrorHandler)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 AsyncContext (javax.servlet.AsyncContext)3