use of org.apache.thrift.TApplicationException in project dubbo by alibaba.
the class ThriftCodec method decode.
private Object decode(TProtocol protocol) throws IOException {
// version
String serviceName;
long id;
TMessage message;
try {
protocol.readI16();
protocol.readByte();
serviceName = protocol.readString();
id = protocol.readI64();
message = protocol.readMessageBegin();
} catch (TException e) {
throw new IOException(e.getMessage(), e);
}
if (message.type == TMessageType.CALL) {
RpcInvocation result = new RpcInvocation();
result.setAttachment(Constants.INTERFACE_KEY, serviceName);
result.setMethodName(message.name);
String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class).getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName(serviceName, message.name);
if (StringUtils.isEmpty(argsClassName)) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, "The specified interface name incorrect.");
}
Class clazz = cachedClass.get(argsClassName);
if (clazz == null) {
try {
clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName);
cachedClass.putIfAbsent(argsClassName, clazz);
} catch (ClassNotFoundException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
}
}
TBase args;
try {
args = (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);
}
try {
args.read(protocol);
protocol.readMessageEnd();
} catch (TException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
}
List<Object> parameters = new ArrayList<Object>();
List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
int index = 1;
while (true) {
TFieldIdEnum fieldIdEnum = args.fieldForId(index++);
if (fieldIdEnum == null) {
break;
}
String fieldName = fieldIdEnum.getFieldName();
String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
Method getMethod;
try {
getMethod = clazz.getMethod(getMethodName);
} catch (NoSuchMethodException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
}
parameterTypes.add(getMethod.getReturnType());
try {
parameters.add(getMethod.invoke(args));
} catch (IllegalAccessException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
}
}
result.setArguments(parameters.toArray());
result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()]));
Request request = new Request(id);
request.setData(result);
cachedRequest.putIfAbsent(id, RequestData.create(message.seqid, serviceName, message.name));
return request;
} else if (message.type == TMessageType.EXCEPTION) {
TApplicationException exception;
try {
exception = TApplicationException.read(protocol);
protocol.readMessageEnd();
} catch (TException e) {
throw new IOException(e.getMessage(), e);
}
RpcResult result = new RpcResult();
result.setException(new RpcException(exception.getMessage()));
Response response = new Response();
response.setResult(result);
response.setId(id);
return response;
} else if (message.type == TMessageType.REPLY) {
String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class).getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name);
if (StringUtils.isEmpty(resultClassName)) {
throw new IllegalArgumentException(new StringBuilder(32).append("Could not infer service result class name from service name ").append(serviceName).append(", the service name you specified may not generated by thrift idl compiler").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<?, ? extends TFieldIdEnum> result;
try {
result = (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);
}
try {
result.read(protocol);
protocol.readMessageEnd();
} catch (TException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
}
Object realResult = null;
int index = 0;
while (true) {
TFieldIdEnum fieldIdEnum = result.fieldForId(index++);
if (fieldIdEnum == null) {
break;
}
Field field;
try {
field = clazz.getDeclaredField(fieldIdEnum.getFieldName());
field.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
}
try {
realResult = field.get(result);
} catch (IllegalAccessException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
}
if (realResult != null) {
break;
}
}
Response response = new Response();
response.setId(id);
RpcResult rpcResult = new RpcResult();
if (realResult instanceof Throwable) {
rpcResult.setException((Throwable) realResult);
} else {
rpcResult.setValue(realResult);
}
response.setResult(rpcResult);
return response;
} else {
// Impossible
throw new IOException();
}
}
use of org.apache.thrift.TApplicationException in project dubbo by alibaba.
the class ThriftCodec method encodeResponse.
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;
Method setMethod;
try {
getMethod = clazz.getMethod(getMethodName);
setMethod = clazz.getMethod(setMethodName, getMethod.getReturnType());
setMethod.invoke(resultObj, realResult);
} 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 (applicationException != null) {
message = new TMessage(rd.methodName, TMessageType.EXCEPTION, rd.id);
} else {
message = new TMessage(rd.methodName, TMessageType.REPLY, rd.id);
}
RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);
TIOStreamTransport transport = new TIOStreamTransport(bos);
TBinaryProtocol protocol = new TBinaryProtocol(transport);
int messageLength;
int headerLength;
byte[] bytes = new byte[4];
try {
// magic
protocol.writeI16(MAGIC);
// message length
protocol.writeI32(Integer.MAX_VALUE);
// message header length
protocol.writeI16(Short.MAX_VALUE);
// version
protocol.writeByte(VERSION);
// service name
protocol.writeString(rd.serviceName);
// id
protocol.writeI64(response.getId());
protocol.getTransport().flush();
headerLength = bos.size();
// message
protocol.writeMessageBegin(message);
switch(message.type) {
case TMessageType.EXCEPTION:
applicationException.write(protocol);
break;
case TMessageType.REPLY:
resultObj.write(protocol);
break;
}
protocol.writeMessageEnd();
protocol.getTransport().flush();
int oldIndex = messageLength = bos.size();
try {
TFramedTransport.encodeFrameSize(messageLength, bytes);
bos.setWriteIndex(MESSAGE_LENGTH_INDEX);
protocol.writeI32(messageLength);
bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX);
protocol.writeI16((short) (0xffff & headerLength));
} finally {
bos.setWriteIndex(oldIndex);
}
} catch (TException e) {
throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
}
buffer.writeBytes(bytes);
buffer.writeBytes(bos.toByteArray());
}
use of org.apache.thrift.TApplicationException in project dubbo by alibaba.
the class ThriftCodecTest method testDecodeExceptionResponse.
@Test
public void testDecodeExceptionResponse() throws Exception {
URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName());
Channel channel = new MockedChannel(url);
RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128);
Request request = createRequest();
DefaultFuture future = new DefaultFuture(channel, request, 10);
TMessage message = new TMessage("echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId());
TTransport transport = new TIOStreamTransport(bos);
TBinaryProtocol protocol = new TBinaryProtocol(transport);
TApplicationException exception = new TApplicationException();
int messageLength, headerLength;
// prepare
protocol.writeI16(ThriftCodec.MAGIC);
protocol.writeI32(Integer.MAX_VALUE);
protocol.writeI16(Short.MAX_VALUE);
protocol.writeByte(ThriftCodec.VERSION);
protocol.writeString(Demo.class.getName());
protocol.writeI64(request.getId());
protocol.getTransport().flush();
headerLength = bos.size();
protocol.writeMessageBegin(message);
exception.write(protocol);
protocol.writeMessageEnd();
protocol.getTransport().flush();
int oldIndex = messageLength = bos.size();
try {
bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX);
protocol.writeI32(messageLength);
bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX);
protocol.writeI16((short) (0xffff & headerLength));
} finally {
bos.setWriteIndex(oldIndex);
}
// prepare
ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray()));
Object obj = codec.decode((Channel) null, bis);
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof Response);
Response response = (Response) obj;
Assert.assertTrue(response.getResult() instanceof RpcResult);
RpcResult result = (RpcResult) response.getResult();
Assert.assertTrue(result.hasException());
Assert.assertTrue(result.getException() instanceof RpcException);
}
use of org.apache.thrift.TApplicationException in project netvirt by opendaylight.
the class BgpConfigurationManager method replay.
@SuppressWarnings("checkstyle:IllegalCatch")
public synchronized boolean replay() throws InterruptedException, TimeoutException, ExecutionException {
boolean replaySucceded = true;
String host = getConfigHost();
int port = getConfigPort();
LOG.error("connecting to bgp host {} ", host);
boolean res = bgpRouter.connect(host, port);
if (!res) {
LOG.error("Cannot connect to BGP config server at {}:{}{}", host, port, config != null ? "; Configuration Replay aborted" : "");
return replaySucceded;
}
config = getConfig();
if (config == null) {
LOG.error("bgp config is empty nothing to push to bgp");
return replaySucceded;
}
BgpRouter br = bgpRouter;
AsId asId = config.getAsId();
if (asId == null) {
LOG.error("bgp as-id is null");
return replaySucceded;
}
long asNum = asId.getLocalAs();
IpAddress routerId = asId.getRouterId();
String rid = routerId == null ? "" : new String(routerId.getValue());
int stalepathTime = (int) getStalePathtime(RESTART_DEFAULT_GR, config.getAsId());
boolean announceFbit = true;
boolean replayDone = false;
final int numberOfStartBgpRetries = 3;
RetryOnException startBgpRetry = new RetryOnException(numberOfStartBgpRetries);
do {
try {
LOG.debug("Replaying BGPConfig ");
br.startBgp(asNum, rid, stalepathTime, announceFbit);
LOG.debug("Replay BGPConfig successful");
replayDone = true;
break;
} catch (BgpRouterException bre) {
if (bre.getErrorCode() == BgpRouterException.BGP_ERR_ACTIVE) {
LOG.debug("Starting the routesync for exception", bre);
startBgpRetry.errorOccured();
if (!startBgpRetry.shouldRetry()) {
LOG.debug("starting route sync for BgpRouter exception");
doRouteSync();
}
} else {
LOG.error("Replay: startBgp() received exception error {} : ", bre.getErrorCode(), bre);
startBgpRetry.errorOccured();
}
} catch (TApplicationException tae) {
if (tae.getType() == BgpRouterException.BGP_ERR_ACTIVE) {
LOG.debug("Starting the routesync for exception", tae);
startBgpRetry.errorOccured();
if (!startBgpRetry.shouldRetry()) {
LOG.debug("starting route sync for Thrift BGP_ERR_ACTIVE exception");
doRouteSync();
}
} else if (tae.getType() == BgpRouterException.BGP_ERR_COMMON_FAILURE) {
LOG.debug("Starting the routesync for AS-ID started exception", tae);
startBgpRetry.errorOccured();
if (!startBgpRetry.shouldRetry()) {
LOG.debug("starting route sync for Thrift BGP_ERR_COMMON_FAILURE exception");
doRouteSync();
}
} else {
LOG.error("Replay: startBgp() received exception type {}: ", tae.getType(), tae);
startBgpRetry.errorOccured();
}
} catch (Exception e) {
// not unusual. We may have restarted & BGP is already on
LOG.error("Replay:startBgp() received exception: ", e);
startBgpRetry.errorOccured();
}
} while (startBgpRetry.shouldRetry());
replaySucceded = replayDone;
startBgpCountersTask();
startBgpAlarmsTask();
/*
* commenting this due to a bug with QBGP. Will uncomment once QBGP fix is done.
* This wont have any functional impacts
*/
// try {
// br.delayEOR(delayEorSeconds);
// } catch (TException | BgpRouterException e) {
// LOG.error("Replay: delayEOR() number of seconds to wait for EOR from ODL:", e);
// }
List<Neighbors> neighbors = config.getNeighbors();
if (neighbors != null) {
LOG.error("configuring existing Neighbors present for replay total neighbors {}", neighbors.size());
boolean neighborConfigReplayResult = replayNbrConfig(neighbors, br);
if (neighborConfigReplayResult == false) {
replaySucceded = false;
}
} else {
LOG.error("no Neighbors present for replay config ");
}
Logging logging = config.getLogging();
if (logging != null) {
try {
br.setLogging(logging.getFile(), logging.getLevel());
} catch (TException | BgpRouterException e) {
LOG.error("Replay:setLogging() received exception", e);
}
}
GracefulRestart gracefulRestart = config.getGracefulRestart();
if (gracefulRestart != null) {
try {
br.addGracefulRestart(gracefulRestart.getStalepathTime().intValue());
} catch (TException | BgpRouterException e) {
LOG.error("Replay:addGr() received exception", e);
}
}
List<Vrfs> vrfs = config.getVrfs();
if (vrfs == null) {
vrfs = new ArrayList<>();
}
for (Vrfs vrf : vrfs) {
for (AddressFamiliesVrf adf : vrf.getAddressFamiliesVrf()) {
try {
br.addVrf(BgpUtil.getLayerType(adf), vrf.getRd(), vrf.getImportRts(), vrf.getExportRts());
} catch (TException | BgpRouterException e) {
LOG.error("Replay:addVrf() received exception", e);
}
}
}
List<Networks> ln = config.getNetworks();
if (ln != null) {
for (Networks net : ln) {
String rd = net.getRd();
String pfxlen = net.getPrefixLen();
String nh = net.getNexthop().getValue();
Long label = net.getLabel();
int lbl = label == null ? 0 : label.intValue();
int l3vni = net.getL3vni() == null ? 0 : net.getL3vni().intValue();
int l2vni = net.getL2vni() == null ? 0 : net.getL2vni().intValue();
if (rd == null && lbl > 0) {
// LU prefix is being deleted.
rd = Integer.toString(lbl);
}
BgpControlPlaneType protocolType = net.getBgpControlPlaneType();
int ethernetTag = net.getEthtag().intValue();
String esi = net.getEsi();
String macaddress = net.getMacaddress();
EncapType encapType = net.getEncapType();
String routerMac = net.getRoutermac();
try {
br.addPrefix(rd, pfxlen, nh, lbl, l3vni, l2vni, BgpUtil.convertToThriftProtocolType(protocolType), ethernetTag, esi, macaddress, BgpUtil.convertToThriftEncapType(encapType), routerMac);
} catch (TException | BgpRouterException e) {
LOG.error("Replay:addPfx() received exception", e);
}
}
}
List<Multipath> multipaths = config.getMultipath();
if (multipaths != null) {
for (Multipath multipath : multipaths) {
if (multipath != null) {
af_afi afi = af_afi.findByValue(multipath.getAfi().intValue());
af_safi safi = af_safi.findByValue(multipath.getSafi().intValue());
try {
if (multipath.isMultipathEnabled()) {
br.enableMultipath(afi, safi);
} else {
br.disableMultipath(afi, safi);
}
} catch (TException | BgpRouterException e) {
LOG.info("Replay:multipaths() received exception", e);
}
}
}
}
List<VrfMaxpath> vrfMaxpaths = config.getVrfMaxpath();
if (vrfMaxpaths != null) {
for (VrfMaxpath vrfMaxpath : vrfMaxpaths) {
try {
br.multipaths(vrfMaxpath.getRd(), vrfMaxpath.getMaxpaths());
} catch (TException | BgpRouterException e) {
LOG.info("Replay:vrfMaxPath() received exception", e);
}
}
}
// send End of Rib Marker to Qthriftd.
final int numberOfEORRetries = 3;
replayDone = false;
RetryOnException eorRetry = new RetryOnException(numberOfEORRetries);
do {
try {
br.sendEOR();
LOG.debug("Replay sendEOR {} successful");
replayDone = true;
break;
} catch (Exception e) {
eorRetry.errorOccured();
LOG.error("Replay:sedEOR() received exception:", e);
}
} while (eorRetry.shouldRetry());
return replaySucceded && replayDone;
}
use of org.apache.thrift.TApplicationException in project accumulo by apache.
the class ThriftScanner method getBatchFromServer.
public static boolean getBatchFromServer(ClientContext context, Range range, KeyExtent extent, String server, SortedMap<Key, Value> results, SortedSet<Column> fetchedColumns, List<IterInfo> serverSideIteratorList, Map<String, Map<String, String>> serverSideIteratorOptions, int size, Authorizations authorizations, boolean retry, long batchTimeOut, String classLoaderContext) throws AccumuloException, AccumuloSecurityException, NotServingTabletException {
if (server == null)
throw new AccumuloException(new IOException());
final HostAndPort parsedServer = HostAndPort.fromString(server);
try {
TInfo tinfo = Tracer.traceInfo();
TabletClientService.Client client = ThriftUtil.getTServerClient(parsedServer, context);
try {
// not reading whole rows (or stopping on row boundries) so there is no need to enable isolation below
ScanState scanState = new ScanState(context, extent.getTableId(), authorizations, range, fetchedColumns, size, serverSideIteratorList, serverSideIteratorOptions, false, Constants.SCANNER_DEFAULT_READAHEAD_THRESHOLD, null, batchTimeOut, classLoaderContext);
TabletType ttype = TabletType.type(extent);
boolean waitForWrites = !serversWaitedForWrites.get(ttype).contains(server);
InitialScan isr = client.startScan(tinfo, scanState.context.rpcCreds(), extent.toThrift(), scanState.range.toThrift(), Translator.translate(scanState.columns, Translators.CT), scanState.size, scanState.serverSideIteratorList, scanState.serverSideIteratorOptions, scanState.authorizations.getAuthorizationsBB(), waitForWrites, scanState.isolated, scanState.readaheadThreshold, null, scanState.batchTimeOut, classLoaderContext);
if (waitForWrites)
serversWaitedForWrites.get(ttype).add(server);
Key.decompress(isr.result.results);
for (TKeyValue kv : isr.result.results) results.put(new Key(kv.key), new Value(kv.value));
client.closeScan(tinfo, isr.scanID);
return isr.result.more;
} finally {
ThriftUtil.returnClient(client);
}
} catch (TApplicationException tae) {
throw new AccumuloServerException(server, tae);
} catch (TooManyFilesException e) {
log.debug("Tablet ({}) has too many files {} : {}", extent, server, e.getMessage());
} catch (ThriftSecurityException e) {
log.warn("Security Violation in scan request to {}: {}", server, e.getMessage());
throw new AccumuloSecurityException(e.user, e.code, e);
} catch (TException e) {
log.debug("Error getting transport to {}: {}", server, e.getMessage());
}
throw new AccumuloException("getBatchFromServer: failed");
}
Aggregations