Search in sources :

Example 6 with Serialization

use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.

the class ExchangeCodec method encodeRequest.

protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) throws IOException {
    Serialization serialization = getSerialization(channel, req);
    // 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.
    int savedWriteIndex = buffer.writerIndex();
    buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
    ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer);
    if (req.isHeartbeat()) {
        // heartbeat request data is always null
        bos.write(CodecSupport.getNullBytesOf(serialization));
    } else {
        ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
        if (req.isEvent()) {
            encodeEventData(channel, out, req.getData());
        } else {
            encodeRequestData(channel, out, req.getData(), req.getVersion());
        }
        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);
}
Also used : Serialization(org.apache.dubbo.common.serialize.Serialization) ChannelBufferOutputStream(org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) Cleanable(org.apache.dubbo.common.serialize.Cleanable)

Example 7 with Serialization

use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.

the class GenericFilter method onResponse.

@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation inv) {
    if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) && inv.getArguments() != null && inv.getArguments().length == 3 && !GenericService.class.isAssignableFrom(invoker.getInterface())) {
        String generic = inv.getAttachment(GENERIC_KEY);
        if (StringUtils.isBlank(generic)) {
            generic = RpcContext.getContext().getAttachment(GENERIC_KEY);
        }
        if (appResponse.hasException()) {
            Throwable appException = appResponse.getException();
            if (appException instanceof GenericException) {
                GenericException tmp = (GenericException) appException;
                appException = new com.alibaba.dubbo.rpc.service.GenericException(tmp.getExceptionClass(), tmp.getExceptionMessage());
            }
            if (!(appException instanceof com.alibaba.dubbo.rpc.service.GenericException)) {
                appException = new com.alibaba.dubbo.rpc.service.GenericException(appException);
            }
            appResponse.setException(appException);
        }
        if (ProtocolUtils.isJavaGenericSerialization(generic)) {
            try {
                UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
                ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA).serialize(null, os).writeObject(appResponse.getValue());
                appResponse.setValue(os.toByteArray());
            } catch (IOException e) {
                throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA + "] serialize result failed.", e);
            }
        } else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
            appResponse.setValue(JavaBeanSerializeUtil.serialize(appResponse.getValue(), JavaBeanAccessor.METHOD));
        } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) {
            try {
                UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
                ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(GENERIC_SERIALIZATION_PROTOBUF).serialize(null, os).writeObject(appResponse.getValue());
                appResponse.setValue(os.toString());
            } catch (IOException e) {
                throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + "] serialize result failed.", e);
            }
        } else if (ProtocolUtils.isGenericReturnRawResult(generic)) {
            return;
        } else {
            appResponse.setValue(PojoUtils.generalize(appResponse.getValue()));
        }
    }
}
Also used : IOException(java.io.IOException) GenericException(org.apache.dubbo.rpc.service.GenericException) Serialization(org.apache.dubbo.common.serialize.Serialization) RpcException(org.apache.dubbo.rpc.RpcException) UnsafeByteArrayOutputStream(org.apache.dubbo.common.io.UnsafeByteArrayOutputStream)

Example 8 with Serialization

use of org.apache.dubbo.common.serialize.Serialization in project dubbo by alibaba.

the class DeprecatedExchangeCodec method encodeResponse.

protected void encodeResponse(Channel channel, OutputStream os, Response res) throws IOException {
    try {
        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] = 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);
        UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
        ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
        // encode response data or error message.
        if (status == Response.OK) {
            if (res.isHeartbeat()) {
                encodeHeartbeatData(channel, out, res.getResult());
            } else {
                encodeResponseData(channel, out, res.getResult());
            }
        } else
            out.writeUTF(res.getErrorMessage());
        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);
    } catch (Throwable t) {
        // send error message to Consumer, otherwise, Consumer will wait until timeout.
        if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) {
            try {
                // FIXME log error info in Codec and put all error handle logic in IoHanndler?
                logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t);
                Response r = new Response(res.getId(), res.getVersion());
                r.setStatus(Response.BAD_RESPONSE);
                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);
        }
    }
}
Also used : Serialization(org.apache.dubbo.common.serialize.Serialization) Response(org.apache.dubbo.remoting.exchange.Response) ObjectOutput(org.apache.dubbo.common.serialize.ObjectOutput) RemotingException(org.apache.dubbo.remoting.RemotingException) UnsafeByteArrayOutputStream(org.apache.dubbo.common.io.UnsafeByteArrayOutputStream) IOException(java.io.IOException)

Aggregations

Serialization (org.apache.dubbo.common.serialize.Serialization)8 ObjectOutput (org.apache.dubbo.common.serialize.ObjectOutput)5 IOException (java.io.IOException)4 UnsafeByteArrayOutputStream (org.apache.dubbo.common.io.UnsafeByteArrayOutputStream)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Cleanable (org.apache.dubbo.common.serialize.Cleanable)2 ObjectInput (org.apache.dubbo.common.serialize.ObjectInput)2 RemotingException (org.apache.dubbo.remoting.RemotingException)2 ChannelBufferOutputStream (org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream)2 Response (org.apache.dubbo.remoting.exchange.Response)2 RpcException (org.apache.dubbo.rpc.RpcException)2 Test (org.junit.jupiter.api.Test)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 GenericObjectPoolConfig (org.apache.commons.pool2.impl.GenericObjectPoolConfig)1 URL (org.apache.dubbo.common.URL)1 NativeJavaSerialization (org.apache.dubbo.common.serialize.nativejava.NativeJavaSerialization)1 ExceedPayloadLimitException (org.apache.dubbo.remoting.transport.ExceedPayloadLimitException)1 Invocation (org.apache.dubbo.rpc.Invocation)1 Protocol (org.apache.dubbo.rpc.Protocol)1 ProxyFactory (org.apache.dubbo.rpc.ProxyFactory)1