Example usage for org.apache.thrift ProcessFunction getEmptyArgsInstance

List of usage examples for org.apache.thrift ProcessFunction getEmptyArgsInstance

Introduction

In this page you can find the example usage for org.apache.thrift ProcessFunction getEmptyArgsInstance.

Prototype

public abstract T getEmptyArgsInstance();

Source Link

Usage

From source file:com.flipkart.phantom.thrift.impl.ThriftProxy.java

License:Apache License

/**
 *
 * Is called by the {@link com.flipkart.phantom.thrift.impl.ThriftProxyExecutor#run()} for processing the request.
 * Currently not utilizing the generic pooled objects.
 *
 * @param clientTransport//  ww  w  . j a va 2  s .c o  m
 * @return transport {@link TTransport} containing clientOutput
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public TTransport doRequest(TTransport clientTransport) {
    TSocket serviceSocket = null;
    try {
        //Get Protocol from transport
        TProtocol clientProtocol = this.protocolFactory.getProtocol(clientTransport);

        TMessage message = clientProtocol.readMessageBegin();
        //Arguments
        ProcessFunction invokedProcessFunction = this.getProcessMap().get(message.name);
        if (invokedProcessFunction == null) {
            throw new RuntimeException(
                    "Unable to find a matching ProcessFunction for invoked method : " + message.name);
        }
        TBase args = invokedProcessFunction.getEmptyArgsInstance(); // get the empty args. The values will then be read from the client's TProtocol
        //Read the argument values from the client's TProtocol
        args.read(clientProtocol);
        clientProtocol.readMessageEnd();

        // Instantiate the call result object using the Thrift naming convention used for classes
        TBase result = (TBase) Class
                .forName(this.getThriftServiceClass() + "$" + message.name + DEFAULT_RESULT_CLASS_NAME)
                .newInstance();

        serviceSocket = new TSocket(this.getThriftServer(), this.getThriftPort(),
                this.getThriftTimeoutMillis());
        TProtocol serviceProtocol = new TBinaryProtocol(serviceSocket);
        serviceSocket.open();

        //Send the arguments to the server and relay the response back
        //Create the custom TServiceClient client which sends request to actual Thrift servers and relays the response back to the client
        ProxyServiceClient proxyClient = new ProxyServiceClient(clientProtocol, serviceProtocol,
                serviceProtocol);

        //Send the request
        proxyClient.sendBase(message.name, args, message.seqid);
        //Get the response back (it is written to client's TProtocol)
        proxyClient.receiveBase(result, message.name);

        LOGGER.debug("Processed message : " + this.getThriftServiceClass() + "." + message.name);
    } catch (Exception e) {
        if (e.getClass().isAssignableFrom(TTransportException.class)) {
            //isConnectionValid = false;
            throw new RuntimeException("Thrift transport exception executing the proxy service call : "
                    + THRIFT_ERRORS.get(((TTransportException) e).getType()), e);
        } else {
            throw new RuntimeException("Exception executing the proxy service call : " + e.getMessage(), e);
        }
    } finally {
        if (serviceSocket != null) {
            serviceSocket.close();
        }
    }
    return clientTransport;
}

From source file:com.linecorp.armeria.server.thrift.ThriftServiceCodec.java

License:Apache License

@Override
public DecodeResult decodeRequest(Channel ch, SessionProtocol sessionProtocol, String hostname, String path,
        String mappedPath, ByteBuf in, Object originalRequest, Promise<Object> promise) throws Exception {

    if (originalRequest instanceof HttpRequest) {
        if (((HttpRequest) originalRequest).method() != HttpMethod.POST) {
            return new DefaultDecodeResult(
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.METHOD_NOT_ALLOWED),
                    HTTP_METHOD_NOT_ALLOWED_EXCEPTION);
        }/*from   w  w  w  .j  ava2s  .  co  m*/
    }

    final TProtocol inProto = this.inProto.get();
    final TByteBufTransport inTransport = (TByteBufTransport) inProto.getTransport();
    inTransport.reset(in);

    try {
        final TMessage header = inProto.readMessageBegin();
        final byte typeValue = header.type;
        final int seqId = header.seqid;
        final String methodName = header.name;

        // Basic sanity check. We usually should never fail here.
        if (typeValue != TMessageType.CALL && typeValue != TMessageType.ONEWAY) {
            final TApplicationException cause = new TApplicationException(
                    TApplicationException.INVALID_MESSAGE_TYPE,
                    "unexpected " + "TMessageType: " + typeString(typeValue));

            return new ThriftDecodeFailureResult(serializationFormat,
                    encodeException(ch.alloc(), methodName, seqId, cause), cause, seqId, methodName, null);
        }

        // Ensure that such a method exists.
        final ThriftFunction f = functions.get(methodName);
        if (f == null) {
            final TApplicationException cause = new TApplicationException(TApplicationException.UNKNOWN_METHOD,
                    "unknown method: " + methodName);

            return new ThriftDecodeFailureResult(serializationFormat,
                    encodeException(ch.alloc(), methodName, seqId, cause), cause, seqId, methodName, null);
        }

        // Decode the invocation parameters.
        final TBase<TBase<?, ?>, TFieldIdEnum> args;
        try {
            if (f.isAsync()) {
                AsyncProcessFunction<Object, TBase<TBase<?, ?>, TFieldIdEnum>, Object> asyncFunc = f
                        .asyncFunc();

                args = asyncFunc.getEmptyArgsInstance();
                args.read(inProto);
                inProto.readMessageEnd();
            } else {
                ProcessFunction<Object, TBase<TBase<?, ?>, TFieldIdEnum>> syncFunc = f.syncFunc();

                args = syncFunc.getEmptyArgsInstance();
                args.read(inProto);
                inProto.readMessageEnd();
            }
        } catch (Exception e) {
            // Failed to decode the invocation parameters.
            final TApplicationException cause = new TApplicationException(TApplicationException.PROTOCOL_ERROR,
                    "argument decode failure: " + e);

            return new ThriftDecodeFailureResult(serializationFormat,
                    encodeException(ch.alloc(), methodName, seqId, cause), cause, seqId, methodName, null);
        }

        return new ThriftServiceInvocationContext(ch, Scheme.of(serializationFormat, sessionProtocol), hostname,
                path, mappedPath, serviceLoggerName, originalRequest, f, seqId, args);
    } finally {
        inTransport.clear();
    }
}

From source file:com.linecorp.armeria.server.thrift.THttpService.java

License:Apache License

private void decodeAndInvoke(ServiceRequestContext ctx, AggregatedHttpMessage req,
        SerializationFormat serializationFormat, HttpResponseWriter res) {

    final TProtocol inProto = FORMAT_TO_THREAD_LOCAL_INPUT_PROTOCOL.get(serializationFormat).get();
    inProto.reset();//from  w ww .  j  ava  2 s  . c  om
    final TMemoryInputTransport inTransport = (TMemoryInputTransport) inProto.getTransport();
    final HttpData content = req.content();
    inTransport.reset(content.array(), content.offset(), content.length());

    final int seqId;
    final ThriftFunction f;
    final RpcRequest decodedReq;

    try {
        final TMessage header;
        final TBase<TBase<?, ?>, TFieldIdEnum> args;

        try {
            header = inProto.readMessageBegin();
        } catch (Exception e) {
            logger.debug("{} Failed to decode Thrift header:", ctx, e);
            res.respond(HttpStatus.BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8,
                    "Failed to decode Thrift header: " + Throwables.getStackTraceAsString(e));
            return;
        }

        seqId = header.seqid;

        final byte typeValue = header.type;
        final int colonIdx = header.name.indexOf(':');
        final String serviceName;
        final String methodName;
        if (colonIdx < 0) {
            serviceName = "";
            methodName = header.name;
        } else {
            serviceName = header.name.substring(0, colonIdx);
            methodName = header.name.substring(colonIdx + 1);
        }

        // Basic sanity check. We usually should never fail here.
        if (typeValue != TMessageType.CALL && typeValue != TMessageType.ONEWAY) {
            final TApplicationException cause = new TApplicationException(
                    TApplicationException.INVALID_MESSAGE_TYPE,
                    "unexpected TMessageType: " + typeString(typeValue));

            handlePreDecodeException(ctx, res, cause, serializationFormat, seqId, methodName);
            return;
        }

        // Ensure that such a method exists.
        final ThriftServiceEntry entry = entries().get(serviceName);
        f = entry != null ? entry.metadata.function(methodName) : null;
        if (f == null) {
            final TApplicationException cause = new TApplicationException(TApplicationException.UNKNOWN_METHOD,
                    "unknown method: " + header.name);

            handlePreDecodeException(ctx, res, cause, serializationFormat, seqId, methodName);
            return;
        }

        // Decode the invocation parameters.
        try {
            if (f.isAsync()) {
                AsyncProcessFunction<Object, TBase<TBase<?, ?>, TFieldIdEnum>, Object> asyncFunc = f
                        .asyncFunc();

                args = asyncFunc.getEmptyArgsInstance();
                args.read(inProto);
                inProto.readMessageEnd();
            } else {
                ProcessFunction<Object, TBase<TBase<?, ?>, TFieldIdEnum>> syncFunc = f.syncFunc();

                args = syncFunc.getEmptyArgsInstance();
                args.read(inProto);
                inProto.readMessageEnd();
            }

            decodedReq = toRpcRequest(f.serviceType(), header.name, args);
            ctx.logBuilder().requestContent(decodedReq, new ThriftCall(header, args));
        } catch (Exception e) {
            // Failed to decode the invocation parameters.
            logger.debug("{} Failed to decode Thrift arguments:", ctx, e);

            final TApplicationException cause = new TApplicationException(TApplicationException.PROTOCOL_ERROR,
                    "failed to decode arguments: " + e);

            handlePreDecodeException(ctx, res, cause, serializationFormat, seqId, methodName);
            return;
        }
    } finally {
        inTransport.clear();
        ctx.logBuilder().requestContent(null, null);
    }

    invoke(ctx, serializationFormat, seqId, f, decodedReq, res);
}