Search in sources :

Example 1 with HttpResponse

use of com.baidu.brpc.protocol.HttpResponse in project brpc-java by baidu.

the class HttpRpcServlet method doPost.

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    long startTime = System.nanoTime();
    String requestUri = req.getRequestURI();
    if (requestUri == null) {
        LOG.warn("invalid request");
        resp.setStatus(404);
        return;
    }
    String encoding = req.getCharacterEncoding();
    String contentType = req.getContentType().split(";")[0];
    if (contentType == null) {
        contentType = "application/baidu.json-rpc";
    } else {
        contentType = contentType.toLowerCase();
    }
    byte[] bytes = this.readStream(req.getInputStream(), req.getContentLength());
    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestUri);
    httpRequest.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    httpRequest.content().writeBytes(bytes);
    int protocolType = HttpRpcProtocol.parseProtocolType(contentType);
    CommunicationSpiManager.getInstance().loadAllExtensions(encoding);
    Protocol protocol = ProtocolManager.getInstance().getProtocol(protocolType);
    Request request = null;
    Response response = new HttpResponse();
    String errorMsg = null;
    try {
        request = protocol.decodeRequest(httpRequest);
        Object result = request.getTargetMethod().invoke(request.getTarget(), request.getArgs());
        response.setResult(result);
        response.setRpcMethodInfo(request.getRpcMethodInfo());
        response.setLogId(request.getLogId());
        response.setCorrelationId(request.getCorrelationId());
        protocol.encodeResponse(request, response);
    } catch (Exception ex) {
        errorMsg = String.format("invoke method failed, msg=%s", ex.getMessage());
        LOG.error(errorMsg);
        response.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errorMsg));
    }
    resp.setContentType(contentType);
    resp.setCharacterEncoding(encoding);
    if (errorMsg == null) {
        byte[] content = ((HttpRpcProtocol) protocol).encodeResponseBody(protocolType, request, response);
        resp.setContentLength(content.length);
        resp.getOutputStream().write(content);
    } else {
        byte[] content = errorMsg.getBytes();
        resp.setContentLength(content.length);
        resp.getOutputStream().write(content);
    }
    if (request != null) {
        long endTime = System.nanoTime();
        LOG.debug("uri={} logId={} service={} method={} elapseNs={}", requestUri, request.getLogId(), request.getTarget().getClass().getSimpleName(), request.getTargetMethod().getName(), endTime - startTime);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpResponse(com.baidu.brpc.protocol.HttpResponse) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) RpcException(com.baidu.brpc.exceptions.RpcException) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpResponse(com.baidu.brpc.protocol.HttpResponse) RpcException(com.baidu.brpc.exceptions.RpcException)

Example 2 with HttpResponse

use of com.baidu.brpc.protocol.HttpResponse in project brpc-java by baidu.

the class HttpRpcProtocol method decodeResponse.

@Override
public Response decodeResponse(Object msg, ChannelHandlerContext ctx) {
    FullHttpResponse httpResponse = (FullHttpResponse) msg;
    try {
        ChannelInfo channelInfo = ChannelInfo.getClientChannelInfo(ctx.channel());
        Long correlationId = parseCorrelationId(httpResponse.headers().get(CORRELATION_ID), channelInfo.getCorrelationId());
        HttpResponse response = new HttpResponse();
        response.setCorrelationId(correlationId);
        RpcFuture future = channelInfo.removeRpcFuture(response.getCorrelationId());
        if (future == null) {
            return response;
        }
        response.setRpcFuture(future);
        int bodyLen = httpResponse.content().readableBytes();
        byte[] bytes = new byte[bodyLen];
        httpResponse.content().readBytes(bytes);
        if (!httpResponse.status().equals(HttpResponseStatus.OK)) {
            String body = new String(bytes);
            String message = String.format("http status=%d, message=%s", httpResponse.status().code(), body);
            LOG.warn("{}", message);
            response.setException(new RpcException(RpcException.SERVICE_EXCEPTION, message));
            return response;
        }
        String contentTypeAndEncoding = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE).toLowerCase();
        String[] splits = StringUtils.split(contentTypeAndEncoding, ";");
        int protocolType = HttpRpcProtocol.parseProtocolType(splits[0]);
        String encoding = this.encoding;
        // 由于uc服务返回的encoding是错误的,所以这里以client端设置的encoding为准。
        // for (String split : splits) {
        // split = split.trim();
        // if (split.startsWith("charset=")) {
        // encoding = split.substring("charset=".length());
        // }
        // }
        Object body = null;
        if (bodyLen != 0) {
            try {
                body = decodeBody(protocolType, encoding, bytes);
            } catch (Exception ex) {
                LOG.error("decode response body failed");
                response.setException(ex);
                return response;
            }
        }
        if (body != null) {
            try {
                response.setResult(parseHttpResponse(body, future.getRpcMethodInfo()));
            } catch (Exception ex) {
                LOG.error("failed to parse result from HTTP body");
                response.setException(ex);
            }
        } else {
            response.setResult(null);
        }
        // set response attachment
        if (response.getKvAttachment() == null) {
            response.setKvAttachment(new HashMap<String, Object>());
        }
        for (Map.Entry<String, String> entry : httpResponse.headers()) {
            response.getKvAttachment().put(entry.getKey(), entry.getValue());
        }
        return response;
    } finally {
        httpResponse.release();
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(com.baidu.brpc.protocol.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) ChannelInfo(com.baidu.brpc.ChannelInfo) RpcException(com.baidu.brpc.exceptions.RpcException) NotEnoughDataException(com.baidu.brpc.exceptions.NotEnoughDataException) TooBigDataException(com.baidu.brpc.exceptions.TooBigDataException) BadSchemaException(com.baidu.brpc.exceptions.BadSchemaException) RpcException(com.baidu.brpc.exceptions.RpcException) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) RpcFuture(com.baidu.brpc.client.RpcFuture) JsonObject(com.google.gson.JsonObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with HttpResponse

use of com.baidu.brpc.protocol.HttpResponse in project brpc-java by baidu.

the class HttpJsonProtocolTest method testEncodeHttpResponse.

@Test
public void testEncodeHttpResponse() throws Exception {
    HttpRequest request = new HttpRequest();
    String contentType = "application/json; charset=utf-8";
    request.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
    request.headers().set(HttpHeaderNames.CONTENT_ENCODING, "utf-8");
    request.headers().set("protocol-type", "30");
    Response response = new HttpResponse();
    response.setResult("hello world");
    protocol.encodeResponse(request, response);
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpRequest(com.baidu.brpc.protocol.HttpRequest) HttpResponse(com.baidu.brpc.protocol.HttpResponse) Response(com.baidu.brpc.protocol.Response) HttpResponse(com.baidu.brpc.protocol.HttpResponse) BaseMockitoTest(com.baidu.brpc.test.BaseMockitoTest) Test(org.junit.Test)

Aggregations

HttpResponse (com.baidu.brpc.protocol.HttpResponse)3 RpcException (com.baidu.brpc.exceptions.RpcException)2 ChannelInfo (com.baidu.brpc.ChannelInfo)1 RpcFuture (com.baidu.brpc.client.RpcFuture)1 BadSchemaException (com.baidu.brpc.exceptions.BadSchemaException)1 NotEnoughDataException (com.baidu.brpc.exceptions.NotEnoughDataException)1 TooBigDataException (com.baidu.brpc.exceptions.TooBigDataException)1 HttpRequest (com.baidu.brpc.protocol.HttpRequest)1 Response (com.baidu.brpc.protocol.Response)1 BaseMockitoTest (com.baidu.brpc.test.BaseMockitoTest)1 JsonObject (com.google.gson.JsonObject)1 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)1 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)1 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)1 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1