}
private void encodeResponse( Channel channel, ChannelBuffer buffer, Response response )
throws IOException {
RpcResult result = ( RpcResult ) response.getResult();
RequestData rd = cachedRequest.get( response.getId() );
String resultClassName = ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ).getExtension(
channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME))
.generateResultClassName(rd.serviceName, rd.methodName);
if ( StringUtils.isEmpty( resultClassName ) ) {
throw new RpcException( RpcException.SERIALIZATION_EXCEPTION,
new StringBuilder( 32 ).append(
"Could not encode response, the specified interface may be incorrect." ).toString() );
}
Class clazz = cachedClass.get( resultClassName );
if ( clazz == null ) {
try {
clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName);
cachedClass.putIfAbsent( resultClassName, clazz );
} catch ( ClassNotFoundException e ) {
throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e );
}
}
TBase resultObj;
try {
resultObj = ( TBase ) clazz.newInstance();
} catch ( InstantiationException e ) {
throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e );
} catch ( IllegalAccessException e ) {
throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e );
}
TApplicationException applicationException = null;
TMessage message;
if ( result.hasException() ) {
Throwable throwable = result.getException();
int index = 1;
boolean found = false;
while ( true ) {
TFieldIdEnum fieldIdEnum = resultObj.fieldForId( index++ );
if ( fieldIdEnum == null ) { break; }
String fieldName = fieldIdEnum.getFieldName();
String getMethodName = ThriftUtils.generateGetMethodName( fieldName );
String setMethodName = ThriftUtils.generateSetMethodName( fieldName );
Method getMethod;
Method setMethod;
try {
getMethod = clazz.getMethod( getMethodName );
if ( getMethod.getReturnType().equals( throwable.getClass() ) ) {
found = true;
setMethod = clazz.getMethod( setMethodName, throwable.getClass() );
setMethod.invoke( resultObj, throwable );
}
} catch ( NoSuchMethodException e ) {
throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e );
} catch ( InvocationTargetException e ) {
throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e );
} catch ( IllegalAccessException e ) {
throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e );
}
}
if ( !found ) {
applicationException = new TApplicationException( throwable.getMessage() );
}
} else {
Object realResult = result.getResult();
// result field id is 0
String fieldName = resultObj.fieldForId( 0 ).getFieldName();
String setMethodName = ThriftUtils.generateSetMethodName( fieldName );
String getMethodName = ThriftUtils.generateGetMethodName( fieldName );
Method getMethod;