下面列出了怎么用java.lang.reflect.UndeclaredThrowableException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testAspectMethodThrowsExceptionIllegalOnSignature() {
TestBean target = new TestBean();
RemoteException expectedException = new RemoteException();
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
try {
itb.getAge();
fail();
}
catch (UndeclaredThrowableException ex) {
assertSame(expectedException, ex.getCause());
}
}
@Test
public void testNillable() throws Exception {
SOAPService service = new SOAPService();
assertNotNull(service);
Greeter greeter = service.getPort(portName, Greeter.class);
updateAddressPort(greeter, PORT);
try {
String reply = greeter.testNillable("test", 100);
assertEquals("test", reply);
reply = greeter.testNillable(null, 100);
assertNull(reply);
} catch (UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
@Test
public void testVersioning() throws Exception {
try {
// expect two MAPs instances versioned with 200408, i.e. for both
// the partial and full responses
mapVerifier.addToExpectedExposedAs(Names200408.WSA_NAMESPACE_NAME);
mapVerifier.addToExpectedExposedAs(Names200408.WSA_NAMESPACE_NAME);
String greeting = greeter.greetMe("versioning1");
assertEquals("unexpected response received from service",
"Hello versioning1",
greeting);
checkVerification();
greeting = greeter.greetMe("versioning2");
assertEquals("unexpected response received from service",
"Hello versioning2",
greeting);
checkVerification();
} catch (UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
public static void main(final String[] args) {
final String configurationDirectory = CliFrontend.getConfigurationDirectoryFromEnv();
final Configuration flinkConfiguration = GlobalConfiguration.loadConfiguration();
int retCode;
try {
final FlinkYarnSessionCli cli = new FlinkYarnSessionCli(
flinkConfiguration,
configurationDirectory,
"",
""); // no prefix for the YARN session
SecurityUtils.install(new SecurityConfiguration(flinkConfiguration));
retCode = SecurityUtils.getInstalledContext().runSecured(() -> cli.run(args));
} catch (CliArgsException e) {
retCode = handleCliArgsException(e);
} catch (Throwable t) {
final Throwable strippedThrowable = ExceptionUtils.stripException(t, UndeclaredThrowableException.class);
retCode = handleError(strippedThrowable);
}
System.exit(retCode);
}
private void injectField(Configuration config, Field field, Object target) {
ConfigurationValue configurationValue = field.getAnnotation(ConfigurationValue.class);
if (configurationValue == null) {
// field should not be injected
return;
}
field.setAccessible(true);
Injector injector = injectorMap.get(field.getType());
if (injector == null) {
throw new IllegalClassException(UNINJECTABLE_FIELD_TYPE + field.getType());
}
try {
injector.injectInto(config, configurationValue.value(), field, target);
} catch (IllegalAccessException e) {
/* since fields are set accessible at the beginning of this method IllegalAccessExceptions should not occur.
* That makes it ok to throw an UndeclaredThrowableException */
throw new UndeclaredThrowableException(e);
}
}
@Override
public void onFailure(Throwable t) {
try {
Preconditions.checkState(eventInFlight.get());
// stop further event processing
pluginFailed.set(true);
eventQueue.clear();
// catch real root cause of failure, it would throw UndeclaredThrowableException
// if using UGI.doAs
if (t instanceof UndeclaredThrowableException) {
t = t.getCause();
}
Preconditions.checkState(appContext != null);
Preconditions.checkState(managedVertex != null);
// state change must be triggered via an event transition
appContext.getEventHandler().handle(
new VertexEventManagerUserCodeError(managedVertex.getVertexId(),
new AMUserCodeException(Source.VertexManager, t)));
// enqueue no further events due to user code error
} catch (Exception e) {
sendInternalError(e);
}
}
@Override
public StateLike parse(Element elem) {
super.parse(elem);
List<Element> pre_invokesPaths = elem.selectNodes(PRE_INVOKES_TAG);
for (Element node : pre_invokesPaths) {// 拿 孩子节点
for (Iterator i = node.elementIterator(); i.hasNext(); ) {
Element child = (Element)i.next();
try {
preInvokes.add(InvokableFactory.newInstance(child.getName(), child));
} catch (RuntimeException re) {
logger.error(String.format("实例Invokable类型时候出错,类型为:%s , 异常为: %s", child.getName(), re.toString()));
throw re;
} catch (Throwable e) {
logger.error(String.format("实例Invokable类型时候出错,类型为: %s , 异常为:", child.getName(), e.toString()));
throw new UndeclaredThrowableException(e,
"error happened when newInstance Invokable class:" + child.getName());
}
}
}
return this;
}
@Override
public void handleFailure(RetryingCallerInterceptorContext context, Throwable t) throws IOException {
if (t instanceof UndeclaredThrowableException) {
t = t.getCause();
}
if (t instanceof RemoteException) {
RemoteException re = (RemoteException)t;
t = re.unwrapRemoteException();
}
if (t instanceof DoNotRetryIOException) {
throw (DoNotRetryIOException)t;
}
if (t instanceof IOException) {
throw (IOException) t;
}
throw new IOException(t);
}
public DataSet<DataPosterior> computePosterior(){
Attribute seq_id = this.dataFlink.getAttributes().getSeq_id();
if (seq_id==null)
throw new IllegalArgumentException("Functionality only available for data sets with a seq_id attribute");
try{
Configuration config = new Configuration();
config.setString(ParameterLearningAlgorithm.BN_NAME, this.dag.getName());
config.setBytes(SVB, Serialization.serializeObject(svb));
return this.dataFlink
.getBatchedDataSet(this.batchSize)
.flatMap(new ParallelVBMapInference())
.withParameters(config);
}catch(Exception ex){
throw new UndeclaredThrowableException(ex);
}
}
@Test
public void testVersionBasedRouting() throws Exception {
SOAPService service = new SOAPService();
assertNotNull(service);
try {
Greeter greeter = service.getPort(portName, Greeter.class);
updateAddressPort(greeter, PORT);
GreetMe1 request = new GreetMe1();
request.setRequestType("Bonjour");
GreetMeResponse greeting = greeter.greetMe(request);
assertNotNull("no response received from service", greeting);
assertEquals("Hello Bonjour version1", greeting.getResponseType());
String reply = greeter.sayHi();
assertNotNull("no response received from service", reply);
assertEquals("Bonjour version2", reply);
} catch (UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
/**
* Handle the given reflection exception. Should only be called if no
* checked exception is expected to be thrown by the target method.
* <p>Throws the underlying RuntimeException or Error in case of an
* InvocationTargetException with such a root cause. Throws an
* IllegalStateException with an appropriate message or
* UndeclaredThrowableException otherwise.
* @param ex the reflection exception to handle
*/
public static void handleReflectionException(Exception ex) {
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("Method not found: " + ex.getMessage());
}
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method: " + ex.getMessage());
}
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new UndeclaredThrowableException(ex);
}
public DataSet<DataPosterior> computePosterior(DataFlink<DataInstance> dataFlink){
Attribute seq_id = dataFlink.getAttributes().getSeq_id();
if (seq_id==null)
throw new IllegalArgumentException("Functionality only available for data sets with a seq_id attribute");
try{
Configuration config = new Configuration();
config.setString(ParameterLearningAlgorithm.BN_NAME, this.getName());
config.setBytes(SVB, Serialization.serializeObject(svb));
return dataFlink
.getBatchedDataSet(this.batchSize,batchConverter)
.flatMap(new ParallelVBMapInference())
.withParameters(config);
}catch(Exception ex){
throw new UndeclaredThrowableException(ex);
}
}
/**
* Gets and creates the formatter from the LogManager or creates the default
* formatter.
*
* @param p the class name prefix.
* @return the formatter.
* @throws NullPointerException if the given argument is null.
* @throws UndeclaredThrowableException if the formatter can not be created.
*/
private Formatter initFormatter(final String p) {
Formatter f;
String v = fromLogManager(p.concat(".formatter"));
if (v != null && v.length() != 0) {
if (!"null".equalsIgnoreCase(v)) {
try {
f = LogManagerProperties.newFormatter(v);
} catch (final RuntimeException re) {
throw re;
} catch (final Exception e) {
throw new UndeclaredThrowableException(e);
}
} else {
f = null;
}
} else {
//Don't force the byte code verifier to load the formatter.
f = Formatter.class.cast(new CompactFormatter());
}
return f;
}
public static void handleHBaseException(
Throwable t, Iterator<Record> records, ErrorRecordHandler errorRecordHandler
) throws StageException {
Throwable cause = t;
// Drill down to root cause
while ((
cause instanceof UncheckedExecutionException ||
cause instanceof UndeclaredThrowableException ||
cause instanceof ExecutionException
) && cause.getCause() != null) {
cause = cause.getCause();
}
// Column is null or No such Column Family exception
if (cause instanceof NullPointerException || cause instanceof NoSuchColumnFamilyException) {
while (records.hasNext()) {
Record record = records.next();
errorRecordHandler.onError(new OnRecordErrorException(record, Errors.HBASE_37, cause));
}
} else {
LOG.error(Errors.HBASE_36.getMessage(), cause.toString(), cause);
throw new StageException(Errors.HBASE_36, cause.toString(), cause);
}
}
@Test
public void testToResponse_GetClassAndCause2() {
Exception e = new UndeclaredThrowableException(null, "java.lang.IllegalArgumentException: ");
StackTraceElement[] traceArr = new StackTraceElement[1];
traceArr[0] = new StackTraceElement("dummyClass", "dummyMethod", null, 0);
e.setStackTrace(traceArr);
Response response = rem.toResponse(e);
MultivaluedMap<String,Object> responseMap = response.getHeaders();
Assert.assertEquals(400, response.getStatus());
Assert.assertEquals(6, responseMap.size());
Assert.assertEquals(Lists.newArrayList(true), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
Assert.assertEquals(Lists.newArrayList("*"), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
Assert.assertEquals(Lists.newArrayList(864000), responseMap.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
Assert.assertEquals(Lists.newArrayList("400-1"), responseMap.get(Constants.ERROR_CODE));
Assert.assertEquals(Lists.newArrayList("null/null"), responseMap.get(Constants.RESPONSE_ORIGIN));
Assert.assertEquals(Lists.newArrayList("X-SSL-ClientCert-Subject, X-ProxiedEntitiesChain, X-ProxiedIssuersChain, Accept, Accept-Encoding"),
responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS));
}
public DataSet<DataPosterior> computePosterior(DataFlink<DataInstance> dataFlink, List<Variable> latentVariables){
Attribute seq_id = dataFlink.getAttributes().getSeq_id();
if (seq_id==null)
throw new IllegalArgumentException("Functionality only available for data sets with a seq_id attribute");
try{
Configuration config = new Configuration();
config.setString(ParameterLearningAlgorithm.BN_NAME, this.dag.getName());
config.setBytes(SVB, Serialization.serializeObject(svb));
config.setBytes(LATENT_VARS, Serialization.serializeObject(latentVariables));
return dataFlink
.getBatchedDataSet(this.batchSize)
.flatMap(new ParallelVBMapInference())
.withParameters(config);
}catch(Exception ex){
throw new UndeclaredThrowableException(ex);
}
}
/**
* Handle the given reflection exception. Should only be called if no
* checked exception is expected to be thrown by the target method.
* <p>Throws the underlying RuntimeException or Error in case of an
* InvocationTargetException with such a root cause. Throws an
* IllegalStateException with an appropriate message or
* UndeclaredThrowableException otherwise.
* @param ex the reflection exception to handle
*/
public static void handleReflectionException(Exception ex) {
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("Method not found: " + ex.getMessage());
}
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method: " + ex.getMessage());
}
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new UndeclaredThrowableException(ex);
}
/**
* Handle the given reflection exception. Should only be called if no
* checked exception is expected to be thrown by the target method.
* <p>Throws the underlying RuntimeException or Error in case of an
* InvocationTargetException with such a root cause. Throws an
* IllegalStateException with an appropriate message else.
* @param ex the reflection exception to handle
*/
public static void handleReflectionException(Exception ex) {
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("Method not found: " + ex.getMessage());
}
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method: " + ex.getMessage());
}
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new UndeclaredThrowableException(ex);
}
/**
* Handle the given reflection exception. Should only be called if no
* checked exception is expected to be thrown by the target method.
* <p>Throws the underlying RuntimeException or Error in case of an
* InvocationTargetException with such a root cause. Throws an
* IllegalStateException with an appropriate message else.
* @param ex the reflection exception to handle
*/
public static void handleReflectionException(Exception ex) {
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("Method not found: " + ex.getMessage());
}
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method: " + ex.getMessage());
}
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new UndeclaredThrowableException(ex);
}
public DataSet<DataPosteriorAssignment> computePosteriorAssignment(DataFlink<DataInstance> dataFlink, List<Variable> latentVariables){
Attribute seq_id = dataFlink.getAttributes().getSeq_id();
if (seq_id==null)
throw new IllegalArgumentException("Functionality only available for data sets with a seq_id attribute");
try{
Configuration config = new Configuration();
config.setString(ParameterLearningAlgorithm.BN_NAME, this.dag.getName());
config.setBytes(SVB, Serialization.serializeObject(svb));
config.setBytes(LATENT_VARS, Serialization.serializeObject(latentVariables));
return dataFlink
.getBatchedDataSet(this.batchSize)
.flatMap(new ParallelVBMapInferenceAssignment())
.withParameters(config);
}catch(Exception ex){
throw new UndeclaredThrowableException(ex);
}
}
/**
* Run the given action as the user, potentially throwing an exception.
* @param <T> the return type of the run method
* @param action the method to execute
* @return the value from the run method
* @throws IOException if the action throws an IOException
* @throws Error if the action throws an Error
* @throws RuntimeException if the action throws a RuntimeException
* @throws InterruptedException if the action throws an InterruptedException
* @throws UndeclaredThrowableException if the action throws something else
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public <T> T doAs(PrivilegedExceptionAction<T> action
) throws IOException, InterruptedException {
try {
logPrivilegedAction(subject, action);
return Subject.doAs(subject, action);
} catch (PrivilegedActionException pae) {
Throwable cause = pae.getCause();
if (LOG.isDebugEnabled()) {
LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause);
}
if (cause instanceof IOException) {
throw (IOException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof InterruptedException) {
throw (InterruptedException) cause;
} else {
throw new UndeclaredThrowableException(cause);
}
}
}
@Test
public void testXMLBindingOfSoapHeaderWSDL() throws Exception {
XMLHeaderService service = new XMLHeaderService();
HeaderTester port = service.getXMLPort9000();
updateAddressPort(port, REG_PORT);
try {
verifyInHeader(port);
verifyInOutHeader(port);
verifyOutHeader(port);
} catch (UndeclaredThrowableException ex) {
throw (Exception) ex.getCause();
}
}
@Test
public void testJSPayloadMode() throws Exception {
URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
QName serviceName = new QName(NS, "SOAPService_Test1");
QName portName = new QName(NS, "SoapPort_Test1");
SOAPServiceTest1 service = new SOAPServiceTest1(wsdl, serviceName);
assertNotNull(service);
String response1 = new String("TestGreetMeResponse");
String response2 = new String("TestSayHiResponse");
try {
Greeter greeter = service.getPort(portName, Greeter.class);
updateAddressPort(greeter, JSX_PORT);
String greeting = greeter.greetMe("TestGreetMeRequest");
assertNotNull("no response received from service", greeting);
assertEquals(response1, greeting);
String reply = greeter.sayHi();
assertNotNull("no response received from service", reply);
assertEquals(response2, reply);
} catch (UndeclaredThrowableException ex) {
ex.printStackTrace();
throw (Exception)ex.getCause();
}
}
private static void rewrapAndThrowException(Exception e) {
if (e instanceof UndeclaredThrowableException) {
rewrapAndThrowThrowable(e.getCause());
} else {
rewrapAndThrowThrowable(e);
}
}
byte[] getBytes() {
if (request instanceof HttpEntityEnclosingRequestBase) {
try {
HttpEntity entity = ((HttpEntityEnclosingRequestBase) request).getEntity();
return EntityUtils.toByteArray(entity);
} catch (IOException e) {
throw new UndeclaredThrowableException(e);
}
}
return EMPTY_BYTES;
}
@Override
public void write(char[] cbuf) {
try {
super.write(cbuf);
} catch (IOException e) {
throw new UndeclaredThrowableException(e);
}
}
@Test
public void invokeListenerCheckedException() {
Method method = ReflectionUtils.findMethod(
SampleEvents.class, "generateCheckedException", GenericTestEvent.class);
GenericTestEvent<String> event = createGenericTestEvent("fail");
assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy(() ->
invokeListener(method, event))
.withCauseInstanceOf(IOException.class);
}
@Override
public String getName() {
try {
return (webSocketPassiveScript
.getName()
.equals(ScriptsWebSocketPassiveScanner.PLUGIN_NAME))
? scriptWrapper.getName()
: webSocketPassiveScript.getName();
} catch (UndeclaredThrowableException e) {
// Python script implementation throws an exception if this optional/default method is
// not actually implemented by the script (other script implementations,
// Zest/ECMAScript, jus tuse the default method).
if (e.getCause() instanceof NoSuchMethodException
&& "getName".equals(e.getCause().getMessage())) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Script [Name="
+ scriptWrapper.getName()
+ ", Engine="
+ scriptWrapper.getEngineName()
+ "] does not implement the optional method getName: ",
e);
}
return scriptWrapper.getName();
}
getExtension().handleScriptException(scriptWrapper, e);
}
return scriptWrapper.getName();
}
public AllocateResponse doAllocateAs(UserGroupInformation ugi,
final AllocateRequest req) throws Exception {
req.setResponseId(++responseId);
try {
return ugi.doAs(new PrivilegedExceptionAction<AllocateResponse>() {
@Override
public AllocateResponse run() throws Exception {
return amRMProtocol.allocate(req);
}
});
} catch (UndeclaredThrowableException e) {
throw (Exception) e.getCause();
}
}
/**
* An interceptor throws a checked exception not on the method signature.
* For efficiency, we don't bother unifying java.lang.reflect and
* org.springframework.cglib UndeclaredThrowableException
*/
@Test
public void testUndeclaredCheckedException() throws Throwable {
final Exception unexpectedException = new Exception();
// Test return value
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
throw unexpectedException;
}
};
AdvisedSupport pc = new AdvisedSupport(new Class<?>[] {ITestBean.class});
pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
pc.addAdvice(mi);
// We don't care about the object
pc.setTarget(new TestBean());
AopProxy aop = createAopProxy(pc);
ITestBean tb = (ITestBean) aop.getProxy();
try {
// Note: exception param below isn't used
tb.getAge();
fail("Should have wrapped exception raised by interceptor");
}
catch (UndeclaredThrowableException thrown) {
assertEquals("exception matches", unexpectedException, thrown.getUndeclaredThrowable());
}
catch (Exception ex) {
ex.printStackTrace();
fail("Didn't expect exception: " + ex);
}
}