Search in sources :

Example 11 with ResponseEntity

use of com.tvd12.ezyhttp.core.response.ResponseEntity in project ezyhttp by youngmonkeys.

the class BlockingServletTest method requestHandlerEmptyAndHasErrorHandler.

@Test
public void requestHandlerEmptyAndHasErrorHandler() throws Exception {
    // given
    ComponentManager componentManager = ComponentManager.getInstance();
    componentManager.setServerPort(PORT);
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    UnhandledErrorHandler unhandledErrorHandler = mock(UnhandledErrorHandler.class);
    ResponseEntity responseEntity = ResponseEntity.ok();
    when(unhandledErrorHandler.handleError(HttpMethod.GET, request, response, HttpServletResponse.SC_METHOD_NOT_ALLOWED, null)).thenReturn(responseEntity);
    componentManager.setUnhandledErrorHandler(Collections.singletonList(unhandledErrorHandler));
    BlockingServlet sut = new BlockingServlet();
    sut.init();
    String requestURI = "/get";
    when(request.getMethod()).thenReturn(HttpMethod.GET.toString());
    when(request.getRequestURI()).thenReturn(requestURI);
    when(request.getServerPort()).thenReturn(PORT);
    when(response.getContentType()).thenReturn(ContentTypes.APPLICATION_JSON);
    ServletOutputStream outputStream = mock(ServletOutputStream.class);
    when(response.getOutputStream()).thenReturn(outputStream);
    RequestHandlerManager requestHandlerManager = componentManager.getRequestHandlerManager();
    GetRequestHandler requestHandler = new GetRequestHandler();
    requestHandlerManager.addHandler(new RequestURI(HttpMethod.POST, requestURI, false), requestHandler);
    // when
    sut.service(request, response);
    // then
    verify(request, times(1)).getMethod();
    verify(request, times(1)).getRequestURI();
    verify(response, times(1)).setStatus(StatusCodes.OK);
    componentManager.destroy();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ResponseEntity(com.tvd12.ezyhttp.core.response.ResponseEntity) ServletOutputStream(javax.servlet.ServletOutputStream) RequestHandlerManager(com.tvd12.ezyhttp.server.core.manager.RequestHandlerManager) ComponentManager(com.tvd12.ezyhttp.server.core.manager.ComponentManager) UnhandledErrorHandler(com.tvd12.ezyhttp.server.core.handler.UnhandledErrorHandler) BlockingServlet(com.tvd12.ezyhttp.server.core.servlet.BlockingServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestURI(com.tvd12.ezyhttp.server.core.request.RequestURI) ToString(lombok.ToString) Test(org.testng.annotations.Test)

Example 12 with ResponseEntity

use of com.tvd12.ezyhttp.core.response.ResponseEntity in project ezyhttp by youngmonkeys.

the class UnhandledErrorHandlerTest method returnResponseEntity.

@Test
public void returnResponseEntity() {
    // given
    ResponseEntity result = ResponseEntity.ok();
    UnhandledErrorHandler sut = new UnhandledErrorHandler() {

        @Override
        public Object processError(HttpMethod method, HttpServletRequest request, HttpServletResponse response, int errorStatusCode, Exception exception) {
            return result;
        }
    };
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    // when
    Object actual = sut.handleError(HttpMethod.GET, request, response, StatusCodes.BAD_REQUEST, null);
    // then
    Asserts.assertEquals(result, actual);
    verify(response, times(1)).setContentType(null);
    verify(response, times(1)).setContentType(ContentTypes.APPLICATION_JSON);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ResponseEntity(com.tvd12.ezyhttp.core.response.ResponseEntity) UnhandledErrorHandler(com.tvd12.ezyhttp.server.core.handler.UnhandledErrorHandler) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpMethod(com.tvd12.ezyhttp.core.constant.HttpMethod) Test(org.testng.annotations.Test)

Example 13 with ResponseEntity

use of com.tvd12.ezyhttp.core.response.ResponseEntity in project ezyhttp by youngmonkeys.

the class BlockingServlet method handleResponseData.

protected void handleResponseData(HttpServletRequest request, HttpServletResponse response, Object data) throws Exception {
    Object body = data;
    if (data instanceof ResponseEntity) {
        ResponseEntity entity = (ResponseEntity) body;
        body = entity.getBody();
        response.setStatus(entity.getStatus());
        MultiValueMap headers = entity.getHeaders();
        if (headers != null) {
            Map<String, String> encodedHeaders = headers.toMap();
            for (Entry<String, String> entry : encodedHeaders.entrySet()) {
                response.addHeader(entry.getKey(), entry.getValue());
            }
        }
    } else if (data instanceof Redirect) {
        Redirect redirect = (Redirect) data;
        for (Cookie cookie : redirect.getCookies()) {
            response.addCookie(cookie);
        }
        for (Entry<String, String> e : redirect.getHeaders().entrySet()) {
            response.addHeader(e.getKey(), e.getValue());
        }
        Map<String, Object> attributes = redirect.getAttributes();
        if (attributes != null) {
            String attributesValue = objectMapper.writeValueAsString(attributes);
            Cookie attributesCookie = new Cookie(CoreConstants.COOKIE_REDIRECT_ATTRIBUTES_NAME, EzyBase64.encodeUtf(attributesValue));
            attributesCookie.setMaxAge(CoreConstants.COOKIE_REDIRECT_ATTRIBUTES_MAX_AGE);
            response.addCookie(attributesCookie);
        }
        response.sendRedirect(redirect.getUri() + redirect.getQueryString());
        return;
    } else if (data instanceof View) {
        if (viewContext == null) {
            throw new IllegalStateException("viewContext is null, " + "you must add ezyhttp-server-thymeleaf to your dependencies" + " or create viewContext by yourself");
        }
        View view = (View) data;
        for (Cookie cookie : view.getCookies()) {
            response.addCookie(cookie);
        }
        for (Entry<String, String> e : view.getHeaders().entrySet()) {
            response.addHeader(e.getKey(), e.getValue());
        }
        response.setContentType(view.getContentType());
        viewContext.render(getServletContext(), request, response, view);
        return;
    } else {
        response.setStatus(HttpServletResponse.SC_OK);
    }
    if (body != null) {
        responseBody(response, body);
    }
}
Also used : Cookie(javax.servlet.http.Cookie) ResponseEntity(com.tvd12.ezyhttp.core.response.ResponseEntity) Entry(java.util.Map.Entry) Redirect(com.tvd12.ezyhttp.server.core.view.Redirect) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(com.tvd12.ezyhttp.core.data.MultiValueMap) View(com.tvd12.ezyhttp.server.core.view.View) MultiValueMap(com.tvd12.ezyhttp.core.data.MultiValueMap)

Example 14 with ResponseEntity

use of com.tvd12.ezyhttp.core.response.ResponseEntity in project ezyhttp by youngmonkeys.

the class HttpClientProxyTest method clientWasNotActiveAtExecute.

@Test
public void clientWasNotActiveAtExecute() {
    // given
    HttpClientProxy sut = HttpClientProxy.builder().build();
    PostRequest request = new PostRequest().setConnectTimeout(15000).setEntity(String.class).setResponseType(TestResponse.class).setResponseType(StatusCodes.OK, TestResponse.class).setURL("http://127.0.0.1:18081/greet");
    // when
    Throwable e = Asserts.assertThrows(() -> sut.execute(request, new RequestCallback<ResponseEntity>() {

        public void onException(Exception e) {
        }

        public void onResponse(ResponseEntity response) {
        }
    }));
    // then
    Asserts.assertThat(e).isEqualsType(ClientNotActiveException.class);
    sut.close();
    sut.stop();
}
Also used : ResponseEntity(com.tvd12.ezyhttp.core.response.ResponseEntity) RequestCallback(com.tvd12.ezyhttp.client.callback.RequestCallback) HttpClientProxy(com.tvd12.ezyhttp.client.HttpClientProxy) DownloadCancelledException(com.tvd12.ezyhttp.client.exception.DownloadCancelledException) RequestQueueFullException(com.tvd12.ezyhttp.client.exception.RequestQueueFullException) UnknownHostException(java.net.UnknownHostException) BadRequestException(com.tvd12.ezyfox.exception.BadRequestException) ClientNotActiveException(com.tvd12.ezyhttp.client.exception.ClientNotActiveException) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) BaseTest(com.tvd12.test.base.BaseTest)

Example 15 with ResponseEntity

use of com.tvd12.ezyhttp.core.response.ResponseEntity in project ezyhttp by youngmonkeys.

the class HttpClient method request.

@SuppressWarnings("MethodLength")
public ResponseEntity request(HttpMethod method, String url, RequestEntity entity, Map<Integer, Class<?>> responseTypes, int connectTimeout, int readTimeout) throws Exception {
    if (url == null) {
        throw new IllegalArgumentException("url can not be null");
    }
    logger.debug("start: {} - {} - {}", method, url, entity != null ? entity.getHeaders() : null);
    HttpURLConnection connection = connect(url);
    try {
        connection.setConnectTimeout(connectTimeout > 0 ? connectTimeout : defaultConnectTimeout);
        connection.setReadTimeout(readTimeout > 0 ? readTimeout : defaultReadTimeout);
        connection.setRequestMethod(method.toString());
        connection.setDoInput(true);
        connection.setDoOutput(method.hasOutput());
        connection.setInstanceFollowRedirects(method == HttpMethod.GET);
        MultiValueMap requestHeaders = entity != null ? entity.getHeaders() : null;
        if (requestHeaders != null) {
            Map<String, String> encodedHeaders = requestHeaders.toMap();
            for (Entry<String, String> requestHeader : encodedHeaders.entrySet()) {
                connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue());
            }
        }
        Object requestBody = null;
        if (method != HttpMethod.GET && entity != null) {
            requestBody = entity.getBody();
        }
        byte[] requestBodyBytes = null;
        if (requestBody != null) {
            String requestContentType = connection.getRequestProperty(Headers.CONTENT_TYPE);
            if (requestContentType == null) {
                requestContentType = ContentTypes.APPLICATION_JSON;
                connection.setRequestProperty(Headers.CONTENT_TYPE, ContentTypes.APPLICATION_JSON);
            }
            requestBodyBytes = serializeRequestBody(requestContentType, requestBody);
            int requestContentLength = requestBodyBytes.length;
            connection.setFixedLengthStreamingMode(requestContentLength);
        }
        connection.connect();
        if (requestBodyBytes != null) {
            if (method.hasOutput()) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(requestBodyBytes);
                outputStream.flush();
                outputStream.close();
            } else {
                throw new IllegalArgumentException(method + " method can not have a payload body");
            }
        }
        int responseCode = connection.getResponseCode();
        Map<String, List<String>> headerFields = connection.getHeaderFields();
        MultiValueMap responseHeaders = MultiValueMap.of(headerFields);
        String responseContentType = responseHeaders.getValue(Headers.CONTENT_TYPE);
        if (responseContentType == null) {
            responseContentType = ContentTypes.APPLICATION_JSON;
        }
        InputStream inputStream = responseCode >= 400 ? connection.getErrorStream() : connection.getInputStream();
        Object responseBody = null;
        if (inputStream != null) {
            try {
                int responseContentLength = connection.getContentLength();
                Class<?> responseType = responseTypes.get(responseCode);
                responseBody = deserializeResponseBody(responseContentType, responseContentLength, inputStream, responseType);
            } finally {
                inputStream.close();
            }
        }
        logger.debug("end: {} - {} - {} - {}", method, url, responseCode, responseHeaders);
        return new ResponseEntity(responseCode, responseHeaders, responseBody);
    } finally {
        connection.disconnect();
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ResponseEntity(com.tvd12.ezyhttp.core.response.ResponseEntity) HttpURLConnection(java.net.HttpURLConnection) ArrayList(java.util.ArrayList) List(java.util.List) MultiValueMap(com.tvd12.ezyhttp.core.data.MultiValueMap)

Aggregations

ResponseEntity (com.tvd12.ezyhttp.core.response.ResponseEntity)24 Test (org.testng.annotations.Test)21 ClientNotActiveException (com.tvd12.ezyhttp.client.exception.ClientNotActiveException)6 RequestQueueFullException (com.tvd12.ezyhttp.client.exception.RequestQueueFullException)6 UnhandledErrorHandler (com.tvd12.ezyhttp.server.core.handler.UnhandledErrorHandler)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 EzyFuture (com.tvd12.ezyfox.concurrent.EzyFuture)3 BadRequestException (com.tvd12.ezyfox.exception.BadRequestException)3 EzyProcessor.processWithException (com.tvd12.ezyfox.util.EzyProcessor.processWithException)3 HttpClientProxy (com.tvd12.ezyhttp.client.HttpClientProxy)3 DownloadCancelledException (com.tvd12.ezyhttp.client.exception.DownloadCancelledException)3 MultiValueMap (com.tvd12.ezyhttp.core.data.MultiValueMap)3 ComponentManager (com.tvd12.ezyhttp.server.core.manager.ComponentManager)3 BlockingServlet (com.tvd12.ezyhttp.server.core.servlet.BlockingServlet)3 BaseTest (com.tvd12.test.base.BaseTest)3 IOException (java.io.IOException)3 UnknownHostException (java.net.UnknownHostException)3 ServletOutputStream (javax.servlet.ServletOutputStream)3 ToString (lombok.ToString)3