下面列出了怎么用com.google.protobuf.ServiceException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Helper method to wrap the request and send the message.
*/
private ScmContainerLocationResponse submitRequest(
StorageContainerLocationProtocolProtos.Type type,
Consumer<Builder> builderConsumer) throws IOException {
final ScmContainerLocationResponse response;
try {
Builder builder = ScmContainerLocationRequest.newBuilder()
.setCmdType(type)
.setTraceID(TracingUtil.exportCurrentSpan());
builderConsumer.accept(builder);
ScmContainerLocationRequest wrapper = builder.build();
response = submitRpcRequest(wrapper);
} catch (ServiceException ex) {
throw ProtobufHelper.getRemoteException(ex);
}
return response;
}
@Test (timeout=5000)
public void testProtoBufRandomException() throws Exception {
TestRpcService client = getClient();
EmptyRequestProto emptyRequest = EmptyRequestProto.newBuilder().build();
try {
client.error2(null, emptyRequest);
} catch (ServiceException se) {
Assert.assertTrue(se.getCause() instanceof RemoteException);
RemoteException re = (RemoteException) se.getCause();
Assert.assertTrue(re.getClassName().equals(
URISyntaxException.class.getName()));
Assert.assertTrue(re.getMessage().contains("testException"));
Assert.assertTrue(
re.getErrorCode().equals(RpcErrorCodeProto.ERROR_APPLICATION));
}
}
@Override
public final void dropDatabase(final String databaseName)
throws UndefinedDatabaseException, InsufficientPrivilegeException {
try {
final BlockingInterface stub = getStub();
final ReturnState state = stub.dropDatabase(null, ProtoUtil.convertString(databaseName));
throwsIfThisError(state, UndefinedDatabaseException.class);
throwsIfThisError(state, InsufficientPrivilegeException.class);
ensureOk(state);
} catch (ServiceException e) {
throw new RuntimeException(e);
}
}
@Override
public void journal(JournalInfo journalInfo, long epoch, long firstTxnId,
int numTxns, byte[] records) throws IOException {
JournalRequestProto req = JournalRequestProto.newBuilder()
.setJournalInfo(PBHelper.convert(journalInfo))
.setEpoch(epoch)
.setFirstTxnId(firstTxnId)
.setNumTxns(numTxns)
.setRecords(PBHelper.getByteString(records))
.build();
try {
rpcProxy.journal(NULL_CONTROLLER, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public TryKillDAGResponseProto tryKillDAG(RpcController controller,
TryKillDAGRequestProto request) throws ServiceException {
UserGroupInformation user = getRPCUser();
try {
String dagId = request.getDagId();
if (!real.getACLManager(dagId).checkDAGModifyAccess(user)) {
throw new AccessControlException("User " + user + " cannot perform DAG modify operation");
}
real.updateLastHeartbeatTime();
real.tryKillDAG(dagId);
return TryKillDAGResponseProto.newBuilder().build();
} catch (TezException e) {
throw wrapException(e);
}
}
@Override
public IndexListResponse getAllIndexes(RpcController controller, NullProto request) throws ServiceException {
rlock.lock();
try {
return IndexListResponse.newBuilder().setState(OK).addAllIndexDesc(store.getAllIndexes()).build();
} catch (Throwable t) {
printStackTraceIfError(LOG, t);
return IndexListResponse.newBuilder()
.setState(returnError(t))
.build();
} finally {
rlock.unlock();
}
}
public static void processList(Writer writer, TajoClient client) throws ParseException, IOException,
ServiceException, SQLException {
List<BriefQueryInfo> queryList = client.getRunningQueryList();
SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
String fmt = "%1$-20s %2$-7s %3$-20s %4$-30s%n";
String line = String.format(fmt, "QueryId", "State",
"StartTime", "Query");
writer.write(line);
line = String.format(fmt, line20, line7, line20, line30);
writer.write(line);
for (BriefQueryInfo queryInfo : queryList) {
String queryId = String.format("q_%s_%04d",
queryInfo.getQueryId().getId(),
queryInfo.getQueryId().getSeq());
String state = getQueryState(queryInfo.getState());
String startTime = df.format(queryInfo.getStartTime());
String sql = StringUtils.abbreviate(queryInfo.getQuery(), 30);
line = String.format(fmt, queryId, state, startTime, sql);
writer.write(line);
}
}
@Override
public void journal(JournalInfo journalInfo, long epoch, long firstTxnId,
int numTxns, byte[] records) throws IOException {
JournalRequestProto req = JournalRequestProto.newBuilder()
.setJournalInfo(PBHelper.convert(journalInfo))
.setEpoch(epoch)
.setFirstTxnId(firstTxnId)
.setNumTxns(numTxns)
.setRecords(PBHelper.getByteString(records))
.build();
try {
rpcProxy.journal(NULL_CONTROLLER, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public FunctionDescProto getFunctionMeta(RpcController controller, GetFunctionMetaRequest request)
throws ServiceException {
FunctionDescProto function = null;
if (request.hasFunctionType()) {
if (containFunction(request.getSignature(), request.getFunctionType(), request.getParameterTypesList())) {
function = findFunction(request.getSignature(), request.getFunctionType(), request.getParameterTypesList());
}
} else {
function = findFunction(request.getSignature(), request.getParameterTypesList());
}
if (function == null) {
throw new NoSuchFunctionException(request.getSignature(), request.getParameterTypesList());
} else {
return function;
}
}
@Override
public final IndexDesc getIndex(final String tableName, final String columnName) {
try {
return new ServerCallable<IndexDesc>(this.pool, catalogServerAddr, CatalogProtocol.class, false) {
public IndexDesc call(NettyClientBase client) throws ServiceException {
GetIndexRequest.Builder builder = GetIndexRequest.newBuilder();
builder.setTableName(tableName);
builder.setColumnName(columnName);
CatalogProtocolService.BlockingInterface stub = getStub(client);
return new IndexDesc(stub.getIndex(null, builder.build()));
}
}.withRetries();
} catch (ServiceException e) {
LOG.error(e.getMessage(), e);
return null;
}
}
@Override
public final void dropFunction(final String signature) throws UndefinedFunctionException,
InsufficientPrivilegeException {
try {
final UnregisterFunctionRequest request = UnregisterFunctionRequest.newBuilder()
.setSignature(signature)
.build();
final BlockingInterface stub = getStub();
final ReturnState state = stub.dropFunction(null, request);
throwsIfThisError(state, UndefinedFunctionException.class);
throwsIfThisError(state, InsufficientPrivilegeException.class);
ensureOk(state);
} catch (ServiceException e) {
throw new RuntimeException(e);
}
}
@Override
public LocatedBlock getAdditionalDatanode(String src, long fileId,
ExtendedBlock blk, DatanodeInfo[] existings, String[] existingStorageIDs,
DatanodeInfo[] excludes,
int numAdditionalNodes, String clientName) throws AccessControlException,
FileNotFoundException, SafeModeException, UnresolvedLinkException,
IOException {
GetAdditionalDatanodeRequestProto req = GetAdditionalDatanodeRequestProto
.newBuilder()
.setSrc(src)
.setFileId(fileId)
.setBlk(PBHelper.convert(blk))
.addAllExistings(PBHelper.convert(existings))
.addAllExistingStorageUuids(Arrays.asList(existingStorageIDs))
.addAllExcludes(PBHelper.convert(excludes))
.setNumAdditionalNodes(numAdditionalNodes)
.setClientName(clientName)
.build();
try {
return PBHelper.convert(rpcProxy.getAdditionalDatanode(null, req)
.getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public GetListingResponseProto getListing(RpcController controller,
GetListingRequestProto req) throws ServiceException {
try {
DirectoryListing result = server.getListing(
req.getSrc(), req.getStartAfter().toByteArray(),
req.getNeedLocation());
if (result !=null) {
return GetListingResponseProto.newBuilder().setDirList(
PBHelper.convert(result)).build();
} else {
return VOID_GETLISTING_RESPONSE;
}
} catch (IOException e) {
throw new ServiceException(e);
}
}
public Message callBlockingMethod(final MethodDescriptor method,
final RpcController controller,
final Message param,
final Message responsePrototype)
throws ServiceException {
int nextSeqId = sequence.getAndIncrement();
Message rpcRequest = buildRequest(nextSeqId, method, param);
ProtoCallFuture callFuture =
new ProtoCallFuture(controller, responsePrototype);
requests.put(nextSeqId, callFuture);
getChannel().write(rpcRequest);
try {
return callFuture.get();
} catch (Throwable t) {
if(t instanceof ExecutionException) {
ExecutionException ee = (ExecutionException)t;
throw new ServiceException(ee.getCause());
} else {
throw new RemoteException(t);
}
}
}
@Override
public GetTaskReportResponseProto getTaskReport(RpcController controller,
GetTaskReportRequestProto proto) throws ServiceException {
GetTaskReportRequest request = new GetTaskReportRequestPBImpl(proto);
try {
GetTaskReportResponse response = real.getTaskReport(request);
return ((GetTaskReportResponsePBImpl)response).getProto();
} catch (IOException e) {
throw new ServiceException(e);
}
}
@Override
public AddCacheDirectiveResponseProto addCacheDirective(
RpcController controller, AddCacheDirectiveRequestProto request)
throws ServiceException {
try {
long id = server.addCacheDirective(
PBHelper.convert(request.getInfo()),
PBHelper.convertCacheFlags(request.getCacheFlags()));
return AddCacheDirectiveResponseProto.newBuilder().
setId(id).build();
} catch (IOException e) {
throw new ServiceException(e);
}
}
@Override
public void startLogSegment(JournalInfo journalInfo, long epoch, long txid)
throws IOException {
StartLogSegmentRequestProto req = StartLogSegmentRequestProto.newBuilder()
.setJournalInfo(PBHelper.convert(journalInfo))
.setEpoch(epoch)
.setTxid(txid)
.build();
try {
rpcProxy.startLogSegment(NULL_CONTROLLER, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void tryKillDAG() throws TezException, IOException {
if(LOG.isDebugEnabled()) {
LOG.debug("TryKill for app: " + appId + " dag:" + dagId);
}
if(createAMProxyIfNeeded()) {
TryKillDAGRequestProto requestProto =
TryKillDAGRequestProto.newBuilder().setDagId(dagId).build();
try {
proxy.tryKillDAG(null, requestProto);
} catch (ServiceException e) {
resetProxy(e);
}
}
}
@Override
public SCMBlockLocationResponse send(RpcController controller,
SCMBlockLocationRequest request) throws ServiceException {
return dispatcher.processRequest(
request,
this::processMessage,
request.getCmdType(),
request.getTraceID());
}
@Override
public SumResponse sum(RpcController controller, SumRequest request)
throws ServiceException {
return SumResponse.newBuilder().setResult(
request.getX1()+request.getX2()+request.getX3()+request.getX4()
).build();
}
@Override
public ShutdownDatanodeResponseProto shutdownDatanode(
RpcController unused, ShutdownDatanodeRequestProto request)
throws ServiceException {
try {
impl.shutdownDatanode(request.getForUpgrade());
} catch (IOException e) {
throw new ServiceException(e);
}
return SHUTDOWN_DATANODE_RESP;
}
@Override
public DatanodeStorageReport[] getDatanodeStorageReport(DatanodeReportType type)
throws IOException {
final GetDatanodeStorageReportRequestProto req
= GetDatanodeStorageReportRequestProto.newBuilder()
.setType(PBHelper.convert(type)).build();
try {
return PBHelper.convertDatanodeStorageReports(
rpcProxy.getDatanodeStorageReport(null, req).getDatanodeStorageReportsList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public ReportBadBlocksResponseProto reportBadBlocks(RpcController controller,
ReportBadBlocksRequestProto request) throws ServiceException {
List<LocatedBlockProto> lbps = request.getBlocksList();
LocatedBlock [] blocks = new LocatedBlock [lbps.size()];
for(int i=0; i<lbps.size(); i++) {
blocks[i] = PBHelper.convert(lbps.get(i));
}
try {
impl.reportBadBlocks(blocks);
} catch (IOException e) {
throw new ServiceException(e);
}
return VOID_REPORT_BAD_BLOCK_RESPONSE;
}
@Override
public RegisterNodeManagerResponse registerNodeManager(
RegisterNodeManagerRequest request) throws YarnException,
IOException {
RegisterNodeManagerRequestProto requestProto = ((RegisterNodeManagerRequestPBImpl)request).getProto();
try {
return new RegisterNodeManagerResponsePBImpl(proxy.registerNodeManager(null, requestProto));
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
return null;
}
}
@Override
public GetContainersResponse getContainers(GetContainersRequest request)
throws YarnException, IOException {
GetContainersRequestProto requestProto =
((GetContainersRequestPBImpl) request).getProto();
try {
return new GetContainersResponsePBImpl(proxy.getContainers(null,
requestProto));
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
return null;
}
}
@Override
public void discardSegments(String journalId, long startTxId)
throws IOException {
try {
rpcProxy.discardSegments(NULL_CONTROLLER,
DiscardSegmentsRequestProto.newBuilder()
.setJid(convertJournalId(journalId)).setStartTxId(startTxId)
.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public UpdateNodeResourceResponse updateNodeResource(
UpdateNodeResourceRequest request) throws YarnException, IOException {
UpdateNodeResourceRequestProto requestProto =
((UpdateNodeResourceRequestPBImpl) request).getProto();
try {
return new UpdateNodeResourceResponsePBImpl(proxy.updateNodeResource(null,
requestProto));
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
return null;
}
}
@Override
public ErrorReportResponseProto errorReport(RpcController unused,
ErrorReportRequestProto request) throws ServiceException {
try {
impl.errorReport(PBHelper.convert(request.getRegistration()),
request.getErrorCode(), request.getMsg());
} catch (IOException e) {
throw new ServiceException(e);
}
return VOID_ERROR_REPORT_RESPONSE;
}
@Override
public TezTestServiceProtocolProtos.SubmitWorkResponseProto submitWork(RpcController controller,
TezTestServiceProtocolProtos.SubmitWorkRequestProto request) throws
ServiceException {
try {
return getProxy().submitWork(null, request);
} catch (IOException e) {
throw new ServiceException(e);
}
}
@Override
public EventBatchList getEditsFromTxid(long txid) throws IOException {
GetEditsFromTxidRequestProto req = GetEditsFromTxidRequestProto.newBuilder()
.setTxid(txid).build();
try {
return PBHelper.convert(rpcProxy.getEditsFromTxid(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}