use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.
the class DeprecatedExchangeCodec method encodeRequest.
protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException {
Serialization serialization = CodecSupport.getSerialization(channel.getUrl());
// header.
byte[] header = new byte[HEADER_LENGTH];
// set magic number.
Bytes.short2bytes(MAGIC, header);
// set request and serialization flag.
header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());
if (req.isTwoWay())
header[2] |= FLAG_TWOWAY;
if (req.isEvent())
header[2] |= FLAG_EVENT;
// set request id.
Bytes.long2bytes(req.getId(), header, 4);
// encode request data.
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
if (req.isEvent()) {
encodeEventData(channel, out, req.getData());
} else {
encodeRequestData(channel, out, req.getData());
}
out.flushBuffer();
bos.flush();
bos.close();
byte[] data = bos.toByteArray();
checkPayload(channel, data.length);
Bytes.int2bytes(data.length, header, 12);
// write
// write header.
os.write(header);
// write data.
os.write(data);
}
use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.
the class DubboCodecSupport method getResponseSerialization.
public static Serialization getResponseSerialization(URL url, AppResponse appResponse) {
Object invocationObj = appResponse.getAttribute(INVOCATION_KEY);
if (invocationObj != null) {
Invocation invocation = (Invocation) invocationObj;
Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY);
if (serializationTypeObj != null) {
return CodecSupport.getSerializationById((byte) serializationTypeObj);
}
}
return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
}
use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.
the class HessianProtocolTest method testGenericInvokeWithNativeJava.
@Test
public void testGenericInvokeWithNativeJava() throws IOException, ClassNotFoundException {
// temporary enable native java generic serialize
System.setProperty(CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE, "true");
HessianServiceImpl server = new HessianServiceImpl();
Assertions.assertFalse(server.isCalled());
ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
int port = NetUtils.getAvailablePort();
URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0&generic=nativejava");
Exporter<HessianService> exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url));
Invoker<GenericService> invoker = protocol.refer(GenericService.class, url);
GenericService client = proxyFactory.getProxy(invoker);
Serialization serialization = new NativeJavaSerialization();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
objectOutput.writeObject("haha");
objectOutput.flushBuffer();
Object result = client.$invoke("sayHello", new String[] { "java.lang.String" }, new Object[] { byteArrayOutputStream.toByteArray() });
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream((byte[]) result);
ObjectInput objectInput = serialization.deserialize(url, byteArrayInputStream);
Assertions.assertTrue(server.isCalled());
Assertions.assertEquals("Hello, haha", objectInput.readObject());
invoker.destroy();
exporter.unexport();
System.clearProperty(CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE);
}
use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.
the class RedisProtocolTest method testAuthRedis.
@Test
public void testAuthRedis() {
// default db.index=0
Invoker<IDemoService> refer = PROTOCOL.refer(IDemoService.class, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
IDemoService demoService = this.PROXY.getProxy(refer);
String value = demoService.get("key");
assertThat(value, is(nullValue()));
demoService.set("key", "newValue");
value = demoService.get("key");
assertThat(value, is("newValue"));
demoService.delete("key");
value = demoService.get("key");
assertThat(value, is(nullValue()));
refer.destroy();
// change db.index=1
String password = "123456";
int database = 1;
this.registryUrl = this.registryUrl.setPassword(password).addParameter("db.index", database);
refer = PROTOCOL.refer(IDemoService.class, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
demoService = this.PROXY.getProxy(refer);
demoService.set("key", "newValue");
value = demoService.get("key");
assertThat(value, is("newValue"));
// jedis gets the result comparison
JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "localhost", registryUrl.getPort(), 2000, password, database, (String) null);
try (Jedis jedis = pool.getResource()) {
byte[] valueByte = jedis.get("key".getBytes());
Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY, "java"));
ObjectInput oin = serialization.deserialize(this.registryUrl, new ByteArrayInputStream(valueByte));
String actual = (String) oin.readObject();
assertThat(value, is(actual));
} catch (Exception e) {
Assertions.fail("jedis gets the result comparison is error!");
} finally {
pool.destroy();
}
demoService.delete("key");
value = demoService.get("key");
assertThat(value, is(nullValue()));
refer.destroy();
}
use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.
the class ExchangeCodec method encodeResponse.
protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response res) throws IOException {
int savedWriteIndex = buffer.writerIndex();
try {
Serialization serialization = getSerialization(channel, res);
// header.
byte[] header = new byte[HEADER_LENGTH];
// set magic number.
Bytes.short2bytes(MAGIC, header);
// set request and serialization flag.
header[2] = serialization.getContentTypeId();
if (res.isHeartbeat()) {
header[2] |= FLAG_EVENT;
}
// set response status.
byte status = res.getStatus();
header[3] = status;
// set request id.
Bytes.long2bytes(res.getId(), header, 4);
buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer);
// encode response data or error message.
if (status == Response.OK) {
if (res.isHeartbeat()) {
// heartbeat response data is always null
bos.write(CodecSupport.getNullBytesOf(serialization));
} else {
ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
if (res.isEvent()) {
encodeEventData(channel, out, res.getResult());
} else {
encodeResponseData(channel, out, res.getResult(), res.getVersion());
}
out.flushBuffer();
if (out instanceof Cleanable) {
((Cleanable) out).cleanup();
}
}
} else {
ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
out.writeUTF(res.getErrorMessage());
out.flushBuffer();
if (out instanceof Cleanable) {
((Cleanable) out).cleanup();
}
}
bos.flush();
bos.close();
int len = bos.writtenBytes();
checkPayload(channel, len);
Bytes.int2bytes(len, header, 12);
// write
buffer.writerIndex(savedWriteIndex);
// write header.
buffer.writeBytes(header);
buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len);
} catch (Throwable t) {
// clear buffer
buffer.writerIndex(savedWriteIndex);
// send error message to Consumer, otherwise, Consumer will wait till timeout.
if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) {
Response r = new Response(res.getId(), res.getVersion());
r.setStatus(Response.BAD_RESPONSE);
if (t instanceof ExceedPayloadLimitException) {
logger.warn(t.getMessage(), t);
try {
r.setErrorMessage(t.getMessage());
channel.send(r);
return;
} catch (RemotingException e) {
logger.warn("Failed to send bad_response info back: " + t.getMessage() + ", cause: " + e.getMessage(), e);
}
} else {
// FIXME log error message in Codec and handle in caught() of IoHanndler?
logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t);
try {
r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t));
channel.send(r);
return;
} catch (RemotingException e) {
logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e);
}
}
}
// Rethrow exception
if (t instanceof IOException) {
throw (IOException) t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new RuntimeException(t.getMessage(), t);
}
}
}
Aggregations