Example usage for org.apache.thrift TApplicationException PROTOCOL_ERROR

List of usage examples for org.apache.thrift TApplicationException PROTOCOL_ERROR

Introduction

In this page you can find the example usage for org.apache.thrift TApplicationException PROTOCOL_ERROR.

Prototype

int PROTOCOL_ERROR

To view the source code for org.apache.thrift TApplicationException PROTOCOL_ERROR.

Click Source Link

Usage

From source file:com.facebook.swift.service.ThriftMethodProcessor.java

License:Apache License

private Object[] readArguments(TProtocol in) throws Exception {
    try {//from  w w  w. java2s .c  o  m
        int numArgs = method.getParameterTypes().length;
        Object[] args = new Object[numArgs];
        TProtocolReader reader = new TProtocolReader(in);

        // Map incoming arguments from the ID passed in on the wire to the position in the
        // java argument list we expect to see a parameter with that ID.
        reader.readStructBegin();
        while (reader.nextField()) {
            short fieldId = reader.getFieldId();

            ThriftCodec<?> codec = parameterCodecs.get(fieldId);
            if (codec == null) {
                // unknown field
                reader.skipFieldData();
            } else {
                // Map the incoming arguments to an array of arguments ordered as the java
                // code for the handler method expects to see them
                args[thriftParameterIdToJavaArgumentListPositionMap.get(fieldId)] = reader.readField(codec);
            }
        }
        reader.readStructEnd();

        // Walk through our list of expected parameters and if no incoming parameters were
        // mapped to a particular expected parameter, fill the expected parameter slow with
        // the default for the parameter type.
        int argumentPosition = 0;
        for (ThriftFieldMetadata argument : parameters) {
            if (args[argumentPosition] == null) {
                Type argumentType = argument.getThriftType().getJavaType();

                if (argumentType instanceof Class) {
                    Class<?> argumentClass = (Class<?>) argumentType;
                    argumentClass = Primitives.unwrap(argumentClass);
                    args[argumentPosition] = Defaults.defaultValue(argumentClass);
                }
            }
            argumentPosition++;
        }

        return args;
    } catch (TProtocolException e) {
        // TProtocolException is the only recoverable exception
        // Other exceptions may have left the input stream in corrupted state so we must
        // tear down the socket.
        throw new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage());
    }
}

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);
        }/*  w  w w . j a v a2  s . com*/
    }

    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   ww w .java 2 s . com
    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);
}

From source file:org.apache.hadoop.hive.metastore.TUGIBasedProcessor.java

License:Apache License

private void handleSetUGI(TUGIContainingTransport ugiTrans, ProcessFunction<I, ? extends TBase<?, ?>> fn,
        TMessage msg, TProtocol iprot, TProtocol oprot) throws TException, SecurityException,
        NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    UserGroupInformation clientUgi = ugiTrans.getClientUGI();
    if (null != clientUgi) {
        throw new TException(new IllegalStateException("UGI is already set. Resetting is not "
                + "allowed. Current ugi is: " + clientUgi.getUserName()));
    }/*from   www  .j av a 2s .  c  o  m*/

    // TODO get rid of following reflection after THRIFT-1465 is fixed.
    Method method = fn.getClass().getDeclaredMethod("getEmptyArgsInstance", new Class<?>[0]);
    method.setAccessible(true);
    set_ugi_args args = (set_ugi_args) method.invoke(fn, new Object[0]);
    try {
        args.read(iprot);
    } catch (TProtocolException e) {
        iprot.readMessageEnd();
        TApplicationException x = new TApplicationException(TApplicationException.PROTOCOL_ERROR,
                e.getMessage());
        oprot.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid));
        x.write(oprot);
        oprot.writeMessageEnd();
        oprot.getTransport().flush();
        return;
    }
    iprot.readMessageEnd();
    // TODO get rid of following reflection after THRIFT-1465 is fixed.
    method = fn.getClass().getDeclaredMethod("getResult", Iface.class, set_ugi_args.class);
    method.setAccessible(true);
    set_ugi_result result = (set_ugi_result) method.invoke(fn, iface, args);
    List<String> principals = result.getSuccess();
    // Store the ugi in transport and then continue as usual.
    ugiTrans.setClientUGI(shim.createRemoteUser(principals.remove(principals.size() - 1), principals));
    oprot.writeMessageBegin(new TMessage(msg.name, TMessageType.REPLY, msg.seqid));
    result.write(oprot);
    oprot.writeMessageEnd();
    oprot.getTransport().flush();
}