Example usage for java.lang.reflect UndeclaredThrowableException UndeclaredThrowableException

List of usage examples for java.lang.reflect UndeclaredThrowableException UndeclaredThrowableException

Introduction

In this page you can find the example usage for java.lang.reflect UndeclaredThrowableException UndeclaredThrowableException.

Prototype

public UndeclaredThrowableException(Throwable undeclaredThrowable, String s) 

Source Link

Document

Constructs an UndeclaredThrowableException with the specified Throwable and a detail message.

Usage

From source file:Main.java

/**
 * Causes runnable to have its run method called in the dispatch thread of
 * the event queue. This will happen after all pending events are processed.
 * The call blocks until this has happened.
 *//*  w ww .  j av a 2 s .c  om*/
public static void invokeAndWait(final Runnable runnable) {
    if (EventQueue.isDispatchThread()) {
        runnable.run();
    } else {
        try {
            EventQueue.invokeAndWait(runnable);
        } catch (InterruptedException exception) {
            // Someone don't want to let us sleep. Go back to work.
        } catch (InvocationTargetException target) {
            final Throwable exception = target.getTargetException();
            if (exception instanceof RuntimeException) {
                throw (RuntimeException) exception;
            }
            if (exception instanceof Error) {
                throw (Error) exception;
            }
            // Should not happen, since {@link Runnable#run} do not allow checked exception.
            throw new UndeclaredThrowableException(exception, exception.getLocalizedMessage());
        }
    }
}

From source file:com.ery.ertc.estorm.util.Methods.java

public static <T> Object call(Class<T> clazz, T instance, String methodName, Class[] types, Object[] args)
        throws Exception {
    try {//from w ww.j a  v a  2 s. c om
        Method m = clazz.getMethod(methodName, types);
        return m.invoke(instance, args);
    } catch (IllegalArgumentException arge) {
        LOG.fatal("Constructed invalid call. class=" + clazz.getName() + " method=" + methodName + " types="
                + Classes.stringify(types), arge);
        throw arge;
    } catch (NoSuchMethodException nsme) {
        throw new IllegalArgumentException("Can't find method " + methodName + " in " + clazz.getName() + "!",
                nsme);
    } catch (InvocationTargetException ite) {
        // unwrap the underlying exception and rethrow
        if (ite.getTargetException() != null) {
            if (ite.getTargetException() instanceof Exception) {
                throw (Exception) ite.getTargetException();
            } else if (ite.getTargetException() instanceof Error) {
                throw (Error) ite.getTargetException();
            }
        }
        throw new UndeclaredThrowableException(ite,
                "Unknown exception invoking " + clazz.getName() + "." + methodName + "()");
    } catch (IllegalAccessException iae) {
        throw new IllegalArgumentException("Denied access calling " + clazz.getName() + "." + methodName + "()",
                iae);
    } catch (SecurityException se) {
        LOG.fatal("SecurityException calling method. class=" + clazz.getName() + " method=" + methodName
                + " types=" + Classes.stringify(types), se);
        throw se;
    }
}

From source file:com.bigdata.rdf.sail.webapp.client.BackgroundTupleResult.java

@Override
public List<String> getBindingNames() {
    try {//from  w w w .j  a v a  2s  .  co m
        /*
         * Note: close() will interrupt the parserThread if it is running.
         * That will cause the latch to countDown() and unblock this method
         * if the binding names have not yet been parsed from the
         * connection.
         */
        bindingNamesReady.await();
        queue.checkException();
        if (closed)
            throw new UndeclaredThrowableException(null, "Result closed");
        return bindingNames;
    } catch (InterruptedException e) {
        throw new UndeclaredThrowableException(e);
    } catch (QueryEvaluationException e) {
        throw new UndeclaredThrowableException(e);
    }
}

From source file:org.apache.hadoop.hbase.security.token.TokenUtil.java

/**
 * Obtain an authentication token for the given user and add it to the
 * user's credentials.//w ww .  ja  v a2  s. c o  m
 * @param conf The configuration for connecting to the cluster
 * @param user The user for whom to obtain the token
 * @throws IOException If making a remote call to the {@link TokenProvider} fails
 * @throws InterruptedException If executing as the given user is interrupted
 */
public static void obtainAndCacheToken(final Configuration conf, UserGroupInformation user)
        throws IOException, InterruptedException {
    try {
        Token<AuthenticationTokenIdentifier> token = user
                .doAs(new PrivilegedExceptionAction<Token<AuthenticationTokenIdentifier>>() {
                    public Token<AuthenticationTokenIdentifier> run() throws Exception {
                        return obtainToken(conf);
                    }
                });

        if (token == null) {
            throw new IOException("No token returned for user " + user.getUserName());
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Obtained token " + token.getKind().toString() + " for user " + user.getUserName());
        }
        user.addToken(token);
    } catch (IOException ioe) {
        throw ioe;
    } catch (InterruptedException ie) {
        throw ie;
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new UndeclaredThrowableException(e,
                "Unexpected exception obtaining token for user " + user.getUserName());
    }
}

From source file:org.bonitasoft.engine.api.HTTPServerAPITest.java

@Test(expected = ServerWrappedException.class)
public void invokeMethodCatchUndeclaredThrowableException() throws Exception {
    final PrintStream printStream = System.err;
    final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
    System.setErr(new PrintStream(myOut));
    final Logger logger = Logger.getLogger(HTTPServerAPI.class.getName());
    logger.setLevel(Level.FINE);//from w ww .j  av  a  2  s .c o m
    final ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.FINE);
    logger.addHandler(ch);

    try {
        final Map<String, Serializable> options = new HashMap<String, Serializable>();
        final String apiInterfaceName = "apiInterfaceName";
        final String methodName = "methodName";
        final List<String> classNameParameters = new ArrayList<String>();
        final Object[] parametersValues = null;

        final HTTPServerAPI httpServerAPI = mock(HTTPServerAPI.class);
        final String response = "response";
        doReturn(response).when(httpServerAPI, "executeHttpPost", eq(options), eq(apiInterfaceName),
                eq(methodName), eq(classNameParameters), eq(parametersValues), Matchers.any(XStream.class));
        doThrow(new UndeclaredThrowableException(new BonitaException("Bonita exception"), "Exception plop"))
                .when(httpServerAPI, "checkInvokeMethodReturn", eq(response), Matchers.any(XStream.class));

        // Let's call it for real:
        doCallRealMethod().when(httpServerAPI).invokeMethod(options, apiInterfaceName, methodName,
                classNameParameters, parametersValues);
        httpServerAPI.invokeMethod(options, apiInterfaceName, methodName, classNameParameters,
                parametersValues);
    } finally {
        System.setErr(printStream);
        final String logs = myOut.toString();
        assertTrue("should have written in logs an exception",
                logs.contains("java.lang.reflect.UndeclaredThrowableException"));
        assertTrue("should have written in logs an exception", logs.contains("BonitaException"));
        assertTrue("should have written in logs an exception", logs.contains("Exception plop"));
    }
}

From source file:org.opennms.mock.snmp.PropsMockSnmpMOLoaderImpl.java

public static Variable getVariableFromValueString(String oidStr, String valStr) {
    Variable newVar;//from   ww w.  ja v a 2 s . co m

    if ("\"\"".equals(valStr)) {
        newVar = new Null();
    } else {
        String moTypeStr = valStr.substring(0, valStr.indexOf(":"));
        String moValStr = valStr.substring(valStr.indexOf(":") + 2);

        try {

            if (moTypeStr.equals("STRING")) {
                newVar = new OctetString(moValStr);
            } else if (moTypeStr.equals("Hex-STRING")) {
                newVar = OctetString.fromHexString(moValStr.trim().replace(' ', ':'));
            } else if (moTypeStr.equals("INTEGER")) {
                newVar = new Integer32(Integer.parseInt(moValStr));
            } else if (moTypeStr.equals("Gauge32")) {
                newVar = new Gauge32(Long.parseLong(moValStr));
            } else if (moTypeStr.equals("Counter32")) {
                newVar = new Counter32(Long.parseLong(moValStr)); // a 32 bit counter can be > 2 ^ 31, which is > INTEGER_MAX
            } else if (moTypeStr.equals("Counter64")) {
                newVar = new Counter64(Long.parseLong(moValStr));
            } else if (moTypeStr.equals("Timeticks")) {
                Integer ticksInt = Integer
                        .parseInt(moValStr.substring(moValStr.indexOf("(") + 1, moValStr.indexOf(")")));
                newVar = new TimeTicks(ticksInt);
            } else if (moTypeStr.equals("OID")) {
                newVar = new OID(moValStr);
            } else if (moTypeStr.equals("IpAddress")) {
                newVar = new IpAddress(moValStr.trim());
            } else if (moTypeStr.equals("Network Address")) {
                newVar = OctetString.fromHexString(moValStr.trim());
            } else {
                // Punt, assume it's a String
                //newVar = new OctetString(moValStr);
                throw new IllegalArgumentException("Unrecognized Snmp Type " + moTypeStr);
            }
        } catch (Throwable t) {
            throw new UndeclaredThrowableException(t, "Could not convert value '" + moValStr + "' of type '"
                    + moTypeStr + "' to SNMP object for OID " + oidStr);
        }
    }
    return newVar;
}

From source file:org.apache.hadoop.hbase.security.token.TokenUtil.java

/**
 * Obtain an authentication token on behalf of the given user and add it to
 * the credentials for the given map reduce job.
 * @param conf The configuration for connecting to the cluster
 * @param user The user for whom to obtain the token
 * @param job The job instance in which the token should be stored
 * @throws IOException If making a remote call to the {@link TokenProvider} fails
 * @throws InterruptedException If executing as the given user is interrupted
 *//*from w  w w . j  a  va2 s .  com*/
public static void obtainTokenForJob(final Configuration conf, UserGroupInformation user, Job job)
        throws IOException, InterruptedException {
    try {
        Token<AuthenticationTokenIdentifier> token = user
                .doAs(new PrivilegedExceptionAction<Token<AuthenticationTokenIdentifier>>() {
                    public Token<AuthenticationTokenIdentifier> run() throws Exception {
                        return obtainToken(conf);
                    }
                });

        if (token == null) {
            throw new IOException("No token returned for user " + user.getUserName());
        }
        Text clusterId = getClusterId(token);
        LOG.info("Obtained token " + token.getKind().toString() + " for user " + user.getUserName()
                + " on cluster " + clusterId.toString());
        job.getCredentials().addToken(clusterId, token);
    } catch (IOException ioe) {
        throw ioe;
    } catch (InterruptedException ie) {
        throw ie;
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new UndeclaredThrowableException(e,
                "Unexpected exception obtaining token for user " + user.getUserName());
    }
}

From source file:org.springframework.transaction.support.TransactionTemplate.java

@Override
@Nullable//  w  ww  . jav  a2 s .c o m
public <T> T execute(TransactionCallback<T> action) throws TransactionException {
    Assert.state(this.transactionManager != null, "No PlatformTransactionManager set");

    if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
        return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
    } else {
        TransactionStatus status = this.transactionManager.getTransaction(this);
        T result;
        try {
            result = action.doInTransaction(status);
        } catch (RuntimeException | Error ex) {
            // Transactional code threw application exception -> rollback
            rollbackOnException(status, ex);
            throw ex;
        } catch (Throwable ex) {
            // Transactional code threw unexpected exception -> rollback
            rollbackOnException(status, ex);
            throw new UndeclaredThrowableException(ex,
                    "TransactionCallback threw undeclared checked exception");
        }
        this.transactionManager.commit(status);
        return result;
    }
}

From source file:org.apache.hadoop.hbase.security.token.TokenUtil.java

/**
 * Obtain an authentication token on behalf of the given user and add it to
 * the credentials for the given map reduce job.
 * @param user The user for whom to obtain the token
 * @param job The job configuration in which the token should be stored
 * @throws IOException If making a remote call to the {@link TokenProvider} fails
 * @throws InterruptedException If executing as the given user is interrupted
 *///  w w  w.jav a 2s. c o  m
public static void obtainTokenForJob(final JobConf job, UserGroupInformation user)
        throws IOException, InterruptedException {
    try {
        Token<AuthenticationTokenIdentifier> token = user
                .doAs(new PrivilegedExceptionAction<Token<AuthenticationTokenIdentifier>>() {
                    public Token<AuthenticationTokenIdentifier> run() throws Exception {
                        return obtainToken(job);
                    }
                });

        if (token == null) {
            throw new IOException("No token returned for user " + user.getUserName());
        }
        Text clusterId = getClusterId(token);
        LOG.info("Obtained token " + token.getKind().toString() + " for user " + user.getUserName()
                + " on cluster " + clusterId.toString());
        job.getCredentials().addToken(clusterId, token);
    } catch (IOException ioe) {
        throw ioe;
    } catch (InterruptedException ie) {
        throw ie;
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new UndeclaredThrowableException(e,
                "Unexpected exception obtaining token for user " + user.getUserName());
    }
}

From source file:org.springframework.context.event.ApplicationListenerMethodAdapter.java

/**
 * Invoke the event listener method with the given argument values.
 *///from w  w w .ja va  2 s  .  co m
@Nullable
protected Object doInvoke(Object... args) {
    Object bean = getTargetBean();
    ReflectionUtils.makeAccessible(this.bridgedMethod);
    try {
        return this.bridgedMethod.invoke(bean, args);
    } catch (IllegalArgumentException ex) {
        assertTargetBean(this.bridgedMethod, bean, args);
        throw new IllegalStateException(getInvocationErrorMessage(bean, ex.getMessage(), args), ex);
    } catch (IllegalAccessException ex) {
        throw new IllegalStateException(getInvocationErrorMessage(bean, ex.getMessage(), args), ex);
    } catch (InvocationTargetException ex) {
        // Throw underlying exception
        Throwable targetException = ex.getTargetException();
        if (targetException instanceof RuntimeException) {
            throw (RuntimeException) targetException;
        } else {
            String msg = getInvocationErrorMessage(bean, "Failed to invoke event listener method", args);
            throw new UndeclaredThrowableException(targetException, msg);
        }
    }
}