@Override public boolean process(TProtocol in, TProtocol out) throws TException { TMessage msg = in.readMessageBegin(); Controller<?, ?> fn = (Controller<?, ?>) this.beanFactory .getBean(msg.name); if (fn == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Invalid request: failed to find interface=" + msg.name + ", from: " + getInetAddress(in)); } TProtocolUtil.skip(in, TType.STRUCT); in.readMessageEnd(); TApplicationException x = new TApplicationException( TApplicationException.UNKNOWN_METHOD, "Invalid method name: '" + msg.name + "'"); out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); x.write(out); out.writeMessageEnd(); out.getTransport().flush(); return true; } process(msg.seqid, msg.name, in, out, fn); return true; }
protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException { Invocation invocation = (Invocation) request.getData(); TProtocol protocol = newProtocol(channel.getUrl(), buffer); try { protocol.writeMessageBegin(new TMessage( invocation.getMethodName(), TMessageType.CALL, thriftSeq.getAndIncrement())); protocol.writeStructBegin(new TStruct(invocation.getMethodName() + "_args")); for(int i = 0; i < invocation.getParameterTypes().length; i++) { Class<?> type = invocation.getParameterTypes()[i]; } } catch (TException e) { throw new IOException(e.getMessage(), e); } }
private static void writeRequest(MethodMetadata method, List<Object> parameters, TProtocol protocol) throws Exception { TMessage requestMessage = new TMessage(method.getName(), CALL, SEQUENCE_ID); protocol.writeMessageBegin(requestMessage); // write the parameters ProtocolWriter writer = new ProtocolWriter(new ThriftToDriftProtocolWriter(protocol)); writer.writeStructBegin(method.getName() + "_args"); for (int i = 0; i < parameters.size(); i++) { Object value = parameters.get(i); ParameterMetadata parameter = method.getParameters().get(i); writer.writeField(parameter.getName(), parameter.getId(), parameter.getCodec(), value); } writer.writeStructEnd(); protocol.writeMessageEnd(); protocol.getTransport().flush(); }
@SuppressWarnings({ "rawtypes" }) @Override public void beforeWrite(TMessage msg, TBase args, TBase result) { // reuse message's buffer when write? yes, we use the pool. ByteBuf readedBuf = message.getContent(); int refCount = readedBuf.refCnt(); if (refCount > 0) { readedBuf.release(refCount); } // voidMethod's return message is very short int initialCapacity = serverDef.trafficForecast.getInitBytesForWrite(msg.name); // logger.debug("initialCapacity = {} , msg = {}",initialCapacity, msg); ByteBuf buf = ctx.alloc().buffer(initialCapacity, serverDef.maxFrameSize); message.setContent(buf).beforeWrite(ctx); transport.setOutputBuffer(buf); }
@SuppressWarnings("rawtypes") private void writeResult(final TProtocol out, final TMessage msg, final WriterHandler onComplete, TBase args, final TBase result) { try { onComplete.beforeWrite(msg, args, result); // if (!isOneway()) { out.writeMessageBegin(new TMessage(msg.name, TMessageType.REPLY, msg.seqid)); if (result != null) { result.write(out); } else { out.writeStructBegin(null); out.writeFieldStop(); out.writeStructEnd(); } out.writeMessageEnd(); out.getTransport().flush(); // } onComplete.afterWrite(msg, null, TMessageType.REPLY, args, result); } catch (Throwable e) { onComplete.afterWrite(msg, e, TMessageType.EXCEPTION, args, result); } }
@Override public final boolean process(final TProtocol in, final TProtocol out) throws TException { final TMessage msg = in.readMessageBegin(); final ProcessFunction<LocatorServiceImpl, ?> fn = this.fnMap .get(msg.name); if (fn != null) { fn.process(msg.seqid, in, out, this.inst); // terminate connection on receiving closeConnection // direct class comparison should be the fastest way return fn.getClass() != LocatorService.Processor.closeConnection.class; } else { TProtocolUtil.skip(in, TType.STRUCT); in.readMessageEnd(); TApplicationException x = new TApplicationException( TApplicationException.UNKNOWN_METHOD, "Invalid method name: '" + msg.name + "'"); out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); x.write(out); out.writeMessageEnd(); out.getTransport().flush(); return true; } }
@Override public <Message extends PMessage<Message, Field>, Field extends PField> int serialize(@Nonnull OutputStream output, @Nonnull PServiceCall<Message, Field> call) throws IOException { CountingOutputStream wrapper = new CountingOutputStream(output); TTransport transport = new TIOStreamTransport(wrapper); try { TProtocol protocol = protocolFactory.getProtocol(transport); TMessage tm = new TMessage(call.getMethod(), (byte) call.getType().asInteger(), call.getSequence()); protocol.writeMessageBegin(tm); writeMessage(call.getMessage(), protocol); protocol.writeMessageEnd(); transport.flush(); wrapper.flush(); return wrapper.getByteCount(); } catch (TException e) { throw new SerializerException(e, e.getMessage()); } }
@Override public <Message extends PMessage<Message, Field>, Field extends PField> int serialize(@Nonnull OutputStream output, @Nonnull PServiceCall<Message, Field> call) throws IOException { CountingOutputStream wrapper = new CountingOutputStream(output); TTransport transport = new TIOStreamTransport(wrapper); try { TTupleProtocol protocol = (TTupleProtocol) protocolFactory.getProtocol(transport); TMessage tm = new TMessage(call.getMethod(), (byte) call.getType().asInteger(), call.getSequence()); protocol.writeMessageBegin(tm); writeMessage(call.getMessage(), protocol); protocol.writeMessageEnd(); transport.flush(); wrapper.flush(); return wrapper.getByteCount(); } catch (TException e) { throw new SerializerException(e, e.getMessage()); } }
@Override public boolean process(TProtocol in, TProtocol out) throws TException { TMessage msg = in.readMessageBegin(); ProcessFunction fn = processMap.get(msg.name); if (fn == null) { TProtocolUtil.skip(in, TType.STRUCT); in.readMessageEnd(); TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD, "Invalid method name: '"+msg.name+"'"); out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); x.write(out); out.writeMessageEnd(); out.getTransport().flush(); return true; } fn.process(msg.seqid, in, out, iface); return true; }
@Override public void writeMessageBegin(TMessage tMessage) throws TException { oprot.writeStructBegin(null); oprot.writeString(METHOD_KEY); oprot.writeString(tMessage.name); switch (tMessage.type) { case TMessageType.CALL: oprot.writeString(ARGUMENTS_KEY); break; case TMessageType.REPLY: oprot.writeString(RESULT_KEY); break; case TMessageType.EXCEPTION: oprot.writeString(EXCEPTION_KEY); break; } }
private static TApplicationException readApplicationException(int seqId, ThriftFunction func, TProtocol inputProtocol, TMessage msg) throws TException { if (msg.seqid != seqId) { throw new TApplicationException(TApplicationException.BAD_SEQUENCE_ID); } if (!func.name().equals(msg.name)) { return new TApplicationException(TApplicationException.WRONG_METHOD_NAME, msg.name); } if (msg.type == TMessageType.EXCEPTION) { final TApplicationException appEx = TApplicationExceptions.read(inputProtocol); inputProtocol.readMessageEnd(); return appEx; } return null; }
/** * Returns newly created {@link ObjectMapper} which is configured properly to serialize some knows classes * in a good way. */ public static ObjectMapper newObjectMapper(SimpleModule... userModules) { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(TMessage.class, new TMessageSerializer()); module.addSerializer(TBase.class, new TBaseSerializer()); module.addSerializer(TApplicationException.class, new TApplicationExceptionSerializer()); module.addSerializer(ThriftCall.class, new ThriftCallSerializer()); module.addSerializer(ThriftReply.class, new ThriftReplySerializer()); objectMapper.registerModule(module); for (SimpleModule userModule : userModules) { objectMapper.registerModule(userModule); } return objectMapper; }
/** * I believe these two messages are called for a thrift service * interface. We don't plan on storing any text objects of that * type on disk. */ @Override public void writeMessageBegin(TMessage message) throws TException { try { getCurrentWriter().writeStartObject(); getCurrentWriter().writeFieldName("method"); getCurrentWriter().writeString(message.name); getCurrentWriter().writeFieldName("type"); TypedParser.TMESSAGE_TYPE.writeValue(getCurrentWriter(), message.type); getCurrentWriter().writeFieldName("seqid"); getCurrentWriter().writeNumber(message.seqid); getCurrentWriter().writeFieldName("args"); } catch (IOException e) { throw new TTransportException(e); } }
@Test public void sendAndReceive() throws TException { // GIVEN TMessage msg = new TMessage("a", (byte) 0, 0); int content = 100; outputIntegrityValidatingProtocol.writeMessageBegin(msg); outputIntegrityValidatingProtocol.writeI32(content); outputIntegrityValidatingProtocol.writeMessageEnd(); inputMemoryTrans.reset(outputMemoryBuf.getArray(), 0, outputMemoryBuf.length()); // WHEN TMessage readMsg = inputIntegrityValidatingProtocol.readMessageBegin(); int readContent = inputIntegrityValidatingProtocol.readI32(); inputIntegrityValidatingProtocol.readMessageEnd(); // THEN Assert.assertEquals(readMsg, msg, "Expected to read correct TMessage"); Assert.assertEquals(content, readContent, "Expected to read correct content"); // and: Expected not to have a validity exception! }
@Test(expectedExceptions = IntegrityViolatedException.class) public void sendAndReceiveTamperedMessage() throws TException { // GIVEN TMessage msg = new TMessage("a", (byte) 0, 0); int content = 100; outputIntegrityValidatingProtocol.writeMessageBegin(msg); outputIntegrityValidatingProtocol.writeI32(content); outputIntegrityValidatingProtocol.writeMessageEnd(); byte[] wireData = outputMemoryBuf.getArray(); // tamper with the message on the wire wireData[wireData.length / 2] = (byte) -wireData[wireData.length / 2]; inputMemoryTrans.reset(wireData); // WHEN inputIntegrityValidatingProtocol.readMessageBegin(); inputIntegrityValidatingProtocol.readI32(); inputIntegrityValidatingProtocol.readMessageEnd(); // THEN // and: Expected to have a validity exception! }
@Test public void noSideeffects() throws TException { // GIVEN TMessage msg = new TMessage("a", (byte) 0, 0); int content = 100; outputIntegrityValidatingProtocol.writeMessageBegin(msg); outputIntegrityValidatingProtocol.writeI32(content); outputIntegrityValidatingProtocol.writeMessageEnd(); int intermediaryPos = outputMemoryBuf.length(); // WHEN outputIntegrityValidatingProtocol.writeMessageBegin(msg); outputIntegrityValidatingProtocol.writeI32(content); outputIntegrityValidatingProtocol.writeMessageEnd(); // THEN byte[] firstMsg = new byte[intermediaryPos]; byte[] secondMsg = new byte[outputMemoryBuf.length() - intermediaryPos]; System.arraycopy(outputMemoryBuf.getArray(), 0, firstMsg, 0, intermediaryPos); System.arraycopy(outputMemoryBuf.getArray(), intermediaryPos, secondMsg, 0, secondMsg.length); Assert.assertEquals(firstMsg, secondMsg, "Expected that first and second message are encoded in the same way!"); }
@Override public void after(Object target, Object[] args, Object result, Throwable throwable) { if (isDebug) { logger.afterInterceptor(target, args, result, throwable); } if (!validate(target)) { return; } final boolean shouldTrace = ((AsyncMarkerFlagFieldAccessor)target)._$PINPOINT$_getAsyncMarkerFlag(); if (shouldTrace) { String methodName = ThriftConstants.UNKNOWN_METHOD_NAME; if (result instanceof TMessage) { TMessage message = (TMessage)result; methodName = message.name; } ThriftClientCallContext clientCallContext = new ThriftClientCallContext(methodName); InterceptorScopeInvocation currentTransaction = this.scope.getCurrentInvocation(); currentTransaction.setAttachment(clientCallContext); } }
protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException { Invocation invocation = (Invocation) request.getData(); TProtocol protocol = newProtocol(channel.getUrl(), buffer); try { protocol.writeMessageBegin(new TMessage( invocation.getMethodName(), TMessageType.CALL, thriftSeq.getAndIncrement())); protocol.writeStructBegin(new TStruct(invocation.getMethodName() + "_args")); for (int i = 0; i < invocation.getParameterTypes().length; i++) { Class<?> type = invocation.getParameterTypes()[i]; } } catch (TException e) { throw new IOException(e.getMessage(), e); } }
public final void process(int seqid, TProtocol iprot, TProtocol oprot, I iface) throws TException { T args = getEmptyArgsInstance(); try { args.read(iprot); } catch (TProtocolException e) { iprot.readMessageEnd(); TApplicationException x = new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage()); oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.EXCEPTION, seqid)); x.write(oprot); oprot.writeMessageEnd(); oprot.getTransport().flush(); return; } iprot.readMessageEnd(); TBase result = getResult(iface, args); oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.REPLY, seqid)); result.write(oprot); oprot.writeMessageEnd(); oprot.getTransport().flush(); }
public boolean process(TProtocol in, TProtocol out) throws TException { TMessage msg = in.readMessageBegin(); ProcessFunction fn = processMap.get(msg.name); if (fn == null) { TProtocolUtil.skip(in, TType.STRUCT); in.readMessageEnd(); TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD, "Invalid method name: '"+msg.name+"'"); out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); x.write(out); out.writeMessageEnd(); out.getTransport().flush(); return true; } fn.process(msg.seqid, in, out, iface); return true; }
public void writeMessageBegin(TMessage message) throws TException { trans_.write(LBRACKET); pushWriteContext(new ListContext()); writeString(message.name); writeByte(message.type); writeI32(message.seqid); }
@SuppressWarnings({ "rawtypes" }) @Override public void afterWrite(TMessage msg, Throwable cause, int code, TBase args, TBase result) { if (transport.isHasFlush()) { message.write(ctx); serverDef.trafficForecast.saveWritedBytes(msg.name, transport.getWrittenByteCount(), args, result); } else { message.getContent().release(); logger.error("fail to process! code={}", code, cause); } }