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();
}
}
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();
}
}
}
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));
}
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);
}
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);
}
Aggregations