Search in sources :

Example 1 with HttpRequest

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

the class HttpRpcProtocol method decodeRequest.

@Override
public Request decodeRequest(Object packet) {
    try {
        HttpRequest httpRequest = (HttpRequest) this.createRequest();
        httpRequest.setMsg(packet);
        long correlationId = parseCorrelationId(httpRequest.headers().get(CORRELATION_ID), null);
        httpRequest.setCorrelationId(correlationId);
        String contentTypeAndEncoding = httpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (StringUtils.isBlank(contentTypeAndEncoding)) {
            String errMsg = String.format("content-type is null, uri:%s", httpRequest.uri());
            LOG.warn(errMsg);
            httpRequest.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errMsg));
            return httpRequest;
        }
        contentTypeAndEncoding = contentTypeAndEncoding.toLowerCase();
        String[] splits = StringUtils.split(contentTypeAndEncoding, ";");
        int protocolType = HttpRpcProtocol.parseProtocolType(splits[0]);
        String encoding = this.encoding;
        for (String split : splits) {
            split = split.trim();
            if (split.startsWith("charset=")) {
                encoding = split.substring("charset=".length());
            }
        }
        httpRequest.headers().set(PROTOCOL_TYPE, protocolType);
        httpRequest.headers().set(HttpHeaderNames.CONTENT_ENCODING, encoding);
        // set http headers to attachment
        if (httpRequest.getKvAttachment() == null) {
            httpRequest.setKvAttachment(new HashMap<String, Object>());
        }
        for (Map.Entry<String, String> entry : httpRequest.headers()) {
            httpRequest.getKvAttachment().put(entry.getKey(), entry.getValue());
        }
        ByteBuf byteBuf = httpRequest.content();
        int bodyLen = byteBuf.readableBytes();
        if (bodyLen == 0) {
            String errMsg = String.format("body should not be null, uri:%s", httpRequest.uri());
            LOG.warn(errMsg);
            httpRequest.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errMsg));
            return httpRequest;
        }
        byte[] requestBytes = new byte[bodyLen];
        byteBuf.readBytes(requestBytes, 0, bodyLen);
        Object body = decodeBody(protocolType, encoding, requestBytes);
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.uri());
        String path = queryStringDecoder.path();
        String serviceName = null;
        String methodName = null;
        if (protocolType == Options.ProtocolType.PROTOCOL_HTTP_PROTOBUF_VALUE || protocolType == Options.ProtocolType.PROTOCOL_HTTP_JSON_VALUE) {
            boolean pathError;
            try {
                serviceName = path.substring(1, path.lastIndexOf("/"));
                methodName = path.substring(path.lastIndexOf("/") + 1);
                pathError = serviceName == null || serviceName.isEmpty() || methodName == null || methodName.isEmpty();
            } catch (Exception e) {
                LOG.warn("url format is error", e);
                pathError = true;
            }
            if (pathError) {
                String errMsg = String.format("url format is error, path:%s", path);
                httpRequest.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errMsg));
                return httpRequest;
            }
        } else {
            JsonObject bodyObject = (JsonObject) body;
            methodName = bodyObject.get("method").getAsString();
            serviceName = path;
        }
        ServiceManager serviceManager = ServiceManager.getInstance();
        RpcMethodInfo rpcMethodInfo = serviceManager.getService(serviceName, methodName);
        if (rpcMethodInfo == null) {
            String errMsg = String.format("Fail to find path=%s", path);
            LOG.warn(errMsg);
            httpRequest.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errMsg));
            return httpRequest;
        }
        httpRequest.setServiceName(rpcMethodInfo.getServiceName());
        httpRequest.setMethodName(rpcMethodInfo.getMethodName());
        httpRequest.setRpcMethodInfo(rpcMethodInfo);
        httpRequest.setTargetMethod(rpcMethodInfo.getMethod());
        httpRequest.setTarget(rpcMethodInfo.getTarget());
        try {
            httpRequest.setArgs(parseRequestParam(protocolType, body, rpcMethodInfo));
        } catch (RpcException e) {
            LOG.error("parse request param error", e);
            httpRequest.setException(e);
            return httpRequest;
        }
        return httpRequest;
    } finally {
        ((FullHttpRequest) packet).release();
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpRequest(com.baidu.brpc.protocol.HttpRequest) ProtobufRpcMethodInfo(com.baidu.brpc.ProtobufRpcMethodInfo) RpcMethodInfo(com.baidu.brpc.RpcMethodInfo) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) JsonObject(com.google.gson.JsonObject) ByteBuf(io.netty.buffer.ByteBuf) DynamicCompositeByteBuf(com.baidu.brpc.buffer.DynamicCompositeByteBuf) RpcException(com.baidu.brpc.exceptions.RpcException) NotEnoughDataException(com.baidu.brpc.exceptions.NotEnoughDataException) TooBigDataException(com.baidu.brpc.exceptions.TooBigDataException) BadSchemaException(com.baidu.brpc.exceptions.BadSchemaException) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) ServiceManager(com.baidu.brpc.server.ServiceManager) RpcException(com.baidu.brpc.exceptions.RpcException) JsonObject(com.google.gson.JsonObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with HttpRequest

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

the class HttpRpcProtocol method encodeRequest.

@Override
public ByteBuf encodeRequest(Request request) throws Exception {
    addHostHeader(request);
    HttpRequest httpRequest = (HttpRequest) request;
    String serviceName = httpRequest.getTargetMethod().getDeclaringClass().getName();
    String methodName = httpRequest.getTargetMethod().getName();
    BrpcMeta rpcMeta = httpRequest.getTargetMethod().getAnnotation(BrpcMeta.class);
    if (rpcMeta != null) {
        serviceName = rpcMeta.serviceName();
        methodName = rpcMeta.methodName();
    }
    LOG.debug("serviceName={}, methodName={}", serviceName, methodName);
    Object httpRequestBody = makeRequest((int) httpRequest.getLogId(), methodName, httpRequest.getArgs());
    byte[] httpRequestBodyBytes = encodeBody(protocolType, encoding, httpRequestBody, httpRequest.getRpcMethodInfo());
    FullHttpRequest nettyHttpRequest = null;
    try {
        nettyHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "");
        nettyHttpRequest.setUri(buildHttpUri(serviceName, methodName));
        if (httpRequestBodyBytes != null) {
            nettyHttpRequest.content().writeBytes(httpRequestBodyBytes);
        }
        String contentType = getContentType(protocolType);
        nettyHttpRequest.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=" + encoding);
        nettyHttpRequest.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpRequestBodyBytes == null ? 0 : httpRequestBodyBytes.length);
        nettyHttpRequest.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        nettyHttpRequest.headers().set(CORRELATION_ID, httpRequest.getCorrelationId());
        for (Map.Entry<String, String> header : httpRequest.headers()) {
            if (prohibitedHeaders.contains(header.getKey().toLowerCase())) {
                continue;
            }
            nettyHttpRequest.headers().set(header.getKey(), header.getValue());
        }
        if (request.getKvAttachment() != null) {
            for (Map.Entry<String, Object> kv : request.getKvAttachment().entrySet()) {
                if (!prohibitedHeaders.contains(kv.getKey().toLowerCase())) {
                    nettyHttpRequest.headers().set(kv.getKey(), kv.getValue());
                }
            }
        }
        BrpcHttpRequestEncoder encoder = new BrpcHttpRequestEncoder();
        return encoder.encode(nettyHttpRequest);
    } finally {
        if (nettyHttpRequest != null) {
            nettyHttpRequest.release();
        }
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpRequest(com.baidu.brpc.protocol.HttpRequest) BrpcMeta(com.baidu.brpc.protocol.BrpcMeta) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) JsonObject(com.google.gson.JsonObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with HttpRequest

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

the class HttpJsonProtocolTest method testEncodeHttpRequest.

@Test
public void testEncodeHttpRequest() throws Exception {
    Request request = new HttpRequest();
    request.setTargetMethod(HelloWorldService.class.getMethods()[0]);
    request.setArgs(new Object[] { "hello" });
    request.setLogId(1L);
    Mockito.when(communicationClient.getServiceInstance()).thenReturn(new ServiceInstance("127.0.0.1", 8002));
    request.setCommunicationClient(communicationClient);
    ByteBuf buf = protocol.encodeRequest(request);
    Assert.assertTrue(buf.readableBytes() > 0);
    System.out.println(buf.readableBytes());
    System.out.println(ByteBufUtils.byteBufToString(buf));
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpRequest(com.baidu.brpc.protocol.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) Request(com.baidu.brpc.protocol.Request) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpRequest(com.baidu.brpc.protocol.HttpRequest) ServiceInstance(com.baidu.brpc.client.channel.ServiceInstance) ByteBuf(io.netty.buffer.ByteBuf) BaseMockitoTest(com.baidu.brpc.test.BaseMockitoTest) Test(org.junit.Test)

Example 4 with HttpRequest

use of com.baidu.brpc.protocol.HttpRequest 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)

Example 5 with HttpRequest

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

the class HttpRpcProtocol method addHostHeader.

public void addHostHeader(Request request) {
    ServiceInstance serviceInstance = request.getCommunicationClient().getServiceInstance();
    String hostPort = serviceInstance.getIp() + ":" + serviceInstance.getPort();
    HttpRequest httpRequest = (HttpRequest) request;
    // some http server decide what to do by the 'host' param in request header
    // TODO: check if it must need domain name when using DnsNamingService
    httpRequest.headers().set(HttpHeaderNames.HOST, hostPort);
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpRequest(com.baidu.brpc.protocol.HttpRequest) ServiceInstance(com.baidu.brpc.client.channel.ServiceInstance)

Aggregations

HttpRequest (com.baidu.brpc.protocol.HttpRequest)5 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)5 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)5 ServiceInstance (com.baidu.brpc.client.channel.ServiceInstance)2 BaseMockitoTest (com.baidu.brpc.test.BaseMockitoTest)2 JsonObject (com.google.gson.JsonObject)2 ByteBuf (io.netty.buffer.ByteBuf)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Test (org.junit.Test)2 ProtobufRpcMethodInfo (com.baidu.brpc.ProtobufRpcMethodInfo)1 RpcMethodInfo (com.baidu.brpc.RpcMethodInfo)1 DynamicCompositeByteBuf (com.baidu.brpc.buffer.DynamicCompositeByteBuf)1 BadSchemaException (com.baidu.brpc.exceptions.BadSchemaException)1 NotEnoughDataException (com.baidu.brpc.exceptions.NotEnoughDataException)1 RpcException (com.baidu.brpc.exceptions.RpcException)1 TooBigDataException (com.baidu.brpc.exceptions.TooBigDataException)1 BrpcMeta (com.baidu.brpc.protocol.BrpcMeta)1 HttpResponse (com.baidu.brpc.protocol.HttpResponse)1 Request (com.baidu.brpc.protocol.Request)1