Java Code Examples for java.lang.reflect.UndeclaredThrowableException

The following are top voted examples for showing how to use java.lang.reflect.UndeclaredThrowableException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: teasy   File: SelectImpl.java   View source code 6 votes vote down vote up
@Override
public List<TeasyElement> getOptions() {
    try {
        return wrappedSelect().getOptions()
                .stream()
                .map(option -> new DomTeasyElement(new TeasyElementData(option, By.tagName("option"))))
                .collect(Collectors.toList());
    } catch (UndeclaredThrowableException ignored) {
        //TODO VF fix it in other places
        //Sometimes this test fails in ie due to such exception
        TestUtils.waitForSomeTime(3000, EXPLANATION_MESSAGE_FOR_WAIT);
        return wrappedSelect().getOptions()
                .stream()
                .map(option -> new DomTeasyElement(new TeasyElementData(option, By.tagName("option"))))
                .collect(Collectors.toList());
    }
}
 
Example 2
Project: fastdfs-spring-boot   File: FastdfsHandler.java   View source code 6 votes vote down vote up
private Throwable translateException(Throwable cause) {
    if (cause instanceof FastdfsException) {
        return cause;
    }

    Throwable unwrap = cause;
    for (; ; ) {

        if (unwrap instanceof InvocationTargetException) {
            unwrap = ((InvocationTargetException) unwrap).getTargetException();
            continue;
        }

        if (unwrap instanceof UndeclaredThrowableException) {
            unwrap = ((UndeclaredThrowableException) unwrap).getUndeclaredThrowable();
            continue;
        }

        break;
    }

    return new FastdfsException("fastdfs operation error.", unwrap);
}
 
Example 3
Project: pai   File: HadoopUtils.java   View source code 6 votes vote down vote up
public static void submitApplication(
    ApplicationSubmissionContext appContext, UserDescriptor user) throws Throwable {
  UserGroupInformation ugi =
      UserGroupInformation.createRemoteUser(user.getName());
  // Need to start a new YarnClient for a new UGI, since its internal Hadoop RPC
  // reuse the UGI after YarnClient.start().
  try {
    ugi.doAs((PrivilegedExceptionAction<Void>) () -> {
      YarnClient yarnClient = YarnClient.createYarnClient();
      yarnClient.init(conf);
      yarnClient.start();
      yarnClient.submitApplication(appContext);
      yarnClient.stop();
      return null;
    });
  } catch (UndeclaredThrowableException e) {
    throw e.getCause();
  }
}
 
Example 4
Project: jDialects   File: ReflectionUtils.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Project: spark-project   File: ReflectionUtils.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 6
Project: myfaces-trinidad   File: UIXComponentUINode.java   View source code 6 votes vote down vote up
private void _handleRenderException(
  RuntimeException re) throws IOException
{
  if (re instanceof UndeclaredThrowableException)
  {
    // Our UnsynchronizedPrintWriter catches IOExceptions and
    // rethrows these wrapped in UndeclaredThrowableExceptions.  If we
    // catch any UndeclaredThrowableExceptions which have an IOExceptions
    // as the root cause, let's just rethrow the original
    // IOException so that the original stack trace will be
    // preserved.
    Throwable rootCause = ((UndeclaredThrowableException)re).getCause();
    if (rootCause instanceof IOException)
      throw ((IOException)rootCause);
  }

  throw re;
}
 
Example 7
Project: myfaces-trinidad   File: JaxpXMLProvider.java   View source code 6 votes vote down vote up
/**
 * Returns an implementation of the SAX2 XMLReader interface.
 */
public XMLReader getXMLReader()
{
  try
  {
    return _SAX_PARSER_FACTORY.newSAXParser().getXMLReader();
  }
  catch (ParserConfigurationException pce)
  {
    _LOG.severe(pce);
  }
  catch (SAXException saxe)
  {
    throw new UndeclaredThrowableException(saxe);
  }
  catch (Error e)
  {
    _LOG.severe(e);
  }

  return null;
}
 
Example 8
Project: myfaces-trinidad   File: DataBoundValue.java   View source code 6 votes vote down vote up
/**
 * Handles a Throwable;  the exception is swallowed after being logged.
 */
static public void handleException(
  UIXRenderingContext context,
  Throwable throwable)
{
  if (throwable == null)
    throw new NullPointerException("throwable is null");

  if (throwable instanceof ThreadDeath)
  {
    throw ((ThreadDeath)throwable);
  }
  else if (throwable instanceof RuntimeException)
  {
    handleException(context, (RuntimeException)throwable);
  }
  else
  {
    handleException(context, new UndeclaredThrowableException(throwable));
  }
}
 
Example 9
Project: myfaces-trinidad   File: ConvertBoundValue.java   View source code 6 votes vote down vote up
private Class<?> _getTargetType()
{
  if (_class == null)
  {
    try
    {
      _class = ClassLoaderUtils.loadClass(_javaType);
    }
    catch (ClassNotFoundException e)
    {
      throw new UndeclaredThrowableException(e);
    }
  }

  return _class;
}
 
Example 10
Project: myfaces-trinidad   File: ClassRendererInstantiator.java   View source code 6 votes vote down vote up
public Renderer instantiate()
{
  try
  {
    Class<?> classInstance = ClassLoaderUtils.loadClass(_className);
    return (Renderer) classInstance.newInstance();
  }
  catch (ClassNotFoundException cnfe)
  {
    _showInstantiationError(cnfe);
    throw new UndeclaredThrowableException( cnfe,
       "Instantiation of UIX Components Renderer failed, class " +
       _className + " not found.");
  }
  catch (IllegalAccessException iae)
  {
    _showInstantiationError(iae);
  }
  catch (InstantiationException ie)
  {
    _showInstantiationError(ie);
  }

  return null;
}
 
Example 11
Project: azeroth   File: FastdfsHandler.java   View source code 6 votes vote down vote up
private Throwable translateException(Throwable cause) {
    if (cause instanceof FastdfsException) {
        return cause;
    }

    Throwable unwrap = cause;
    for (;;) {

        if (unwrap instanceof InvocationTargetException) {
            unwrap = ((InvocationTargetException) unwrap).getTargetException();
            continue;
        }

        if (unwrap instanceof UndeclaredThrowableException) {
            unwrap = ((UndeclaredThrowableException) unwrap).getUndeclaredThrowable();
            continue;
        }

        break;
    }

    return new FastdfsException("fastdfs operation error.", unwrap);
}
 
Example 12
Project: privacyidea-authenticator   File: OTPGenerator.java   View source code 6 votes vote down vote up
/**
 * This method uses the JCE to provide the crypto algorithm.
 * HMAC computes a Hashed Message Authentication Code with the
 * crypto hash algorithm as a parameter.
 *
 * @param crypto   the crypto algorithm (HmacSHA1, HmacSHA256,
 *                 HmacSHA512)
 * @param keyBytes the bytes to use for the HMAC key
 * @param text     the message or text to be authenticated
 */
private static byte[] hmac_sha(String crypto, byte[] keyBytes,
                               byte[] text) {
    try {
        Mac hmac;
        hmac = Mac.getInstance(crypto);
        SecretKeySpec macKey =
                new SecretKeySpec(keyBytes, "RAW");
        hmac.init(macKey);
        return hmac.doFinal(text);
    } catch (GeneralSecurityException gse) {
        gse.printStackTrace();
        throw new UndeclaredThrowableException(gse);

    }
}
 
Example 13
Project: hadoop   File: MockAM.java   View source code 6 votes vote down vote up
public void unregisterAppAttempt(final FinishApplicationMasterRequest req,
    boolean waitForStateRunning) throws Exception {
  if (waitForStateRunning) {
    waitForState(RMAppAttemptState.RUNNING);
  }
  if (ugi == null) {
    ugi =  UserGroupInformation.createRemoteUser(attemptId.toString());
    Token<AMRMTokenIdentifier> token =
        context.getRMApps()
            .get(attemptId.getApplicationId())
            .getRMAppAttempt(attemptId).getAMRMToken();
    ugi.addTokenIdentifier(token.decodeIdentifier());
  }
  try {
    ugi.doAs(new PrivilegedExceptionAction<Object>() {
      @Override
      public Object run() throws Exception {
        amRMProtocol.finishApplicationMaster(req);
        return null;
      }
    });
  } catch (UndeclaredThrowableException e) {
    throw (Exception) e.getCause();
  }
}
 
Example 14
Project: hadoop   File: ApplicationMaster.java   View source code 6 votes vote down vote up
@VisibleForTesting
void startTimelineClient(final Configuration conf)
    throws YarnException, IOException, InterruptedException {
  try {
    appSubmitterUgi.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        if (conf.getBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED,
            YarnConfiguration.DEFAULT_TIMELINE_SERVICE_ENABLED)) {
          // Creating the Timeline Client
          timelineClient = TimelineClient.createTimelineClient();
          timelineClient.init(conf);
          timelineClient.start();
        } else {
          timelineClient = null;
          LOG.warn("Timeline service is not enabled");
        }
        return null;
      }
    });
  } catch (UndeclaredThrowableException e) {
    throw new YarnException(e.getCause());
  }
}
 
Example 15
Project: hadoop   File: UserGroupInformation.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
  }
}
 
Example 16
Project: tangyuan2   File: ReflectionUtils.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 17
Project: bulbasaur   File: PersistHelper.java   View source code 6 votes vote down vote up
public <T> T tx(TransactionRun<T> run) {
	TransactionStatus txStatus = getTransactionStatus();
	T result;
	try {
		result = run.run();
	} catch (RuntimeException re) {
		transactionManager.rollback(txStatus);
		throw re;
	} catch (Error err) {
		transactionManager.rollback(txStatus);
		throw err;
	} catch (Exception e) {
		transactionManager.rollback(txStatus);
		throw new UndeclaredThrowableException(e, "undeclared error happened in transaction");
	}
	transactionManager.commit(txStatus);
	return result;
}
 
Example 18
Project: bulbasaur   File: Event.java   View source code 6 votes vote down vote up
@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;
}
 
Example 19
Project: bulbasaur   File: MvelScriptInvokable.java   View source code 6 votes vote down vote up
@Override
public Object invoke0(Map<String, Object> context) {
	context.putAll(beans);
	context.putAll(pojos);
	if (StringUtils.isNotBlank(expr) && !MvelUtils.evalToBoolean(expr, context)) {
		return null;
	}
	try {
		return MvelUtils.eval(script, context);
	} catch (PropertyAccessException e) {
		logger.error("mvel script execute error:" + e.getMessage(), e);
		Throwable sourceE = MvelUtils.unboxingException(e);
		if (sourceE instanceof RuntimeException) {
			throw (BizException) sourceE;
		} else {
			throw new UndeclaredThrowableException(sourceE);
		}
	}
}
 
Example 20
Project: util   File: ReflectionUtils.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 21
Project: ditb   File: TokenUtil.java   View source code 6 votes vote down vote up
/**
 * Obtain an authentication token for the given user and add it to the
 * user's credentials.
 * @param conn The HBase cluster connection
 * @param user The user for whom to obtain the token
 * @throws IOException If making a remote call to the authentication service fails
 * @throws InterruptedException If executing as the given user is interrupted
 */
public static void obtainAndCacheToken(final Connection conn,
    User user)
    throws IOException, InterruptedException {
  try {
    Token<AuthenticationTokenIdentifier> token = obtainToken(conn, user);

    if (token == null) {
      throw new IOException("No token returned for user " + user.getName());
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("Obtained token " + token.getKind().toString() + " for user " +
          user.getName());
    }
    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.getName());
  }
}
 
Example 22
Project: ditb   File: TokenUtil.java   View source code 6 votes vote down vote up
/**
 * Obtain an authentication token on behalf of the given user and add it to
 * the credentials for the given map reduce job.
 * @param conn The HBase cluster connection
 * @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 authentication service fails
 * @throws InterruptedException If executing as the given user is interrupted
 */
public static void obtainTokenForJob(final Connection conn, final JobConf job, User user)
    throws IOException, InterruptedException {
  try {
    Token<AuthenticationTokenIdentifier> token = obtainToken(conn, user);

    if (token == null) {
      throw new IOException("No token returned for user " + user.getName());
    }
    Text clusterId = getClusterId(token);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Obtained token " + token.getKind().toString() + " for user " +
          user.getName() + " 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.getName());
  }
}
 
Example 23
Project: ditb   File: User.java   View source code 6 votes vote down vote up
@Override
public void obtainAuthTokenForJob(Configuration conf, Job job)
    throws IOException, InterruptedException {
  try {
    Class<?> c = Class.forName(
        "org.apache.hadoop.hbase.security.token.TokenUtil");
    Methods.call(c, null, "obtainTokenForJob",
        new Class[]{Configuration.class, UserGroupInformation.class,
            Job.class},
        new Object[]{conf, ugi, job});
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Failure loading TokenUtil class, "
        +"is secure RPC available?", cnfe);
  } catch (IOException ioe) {
    throw ioe;
  } catch (InterruptedException ie) {
    throw ie;
  } catch (RuntimeException re) {
    throw re;
  } catch (Exception e) {
    throw new UndeclaredThrowableException(e,
        "Unexpected error calling TokenUtil.obtainAndCacheToken()");
  }
}
 
Example 24
Project: ditb   File: User.java   View source code 6 votes vote down vote up
@Override
public void obtainAuthTokenForJob(JobConf job)
    throws IOException, InterruptedException {
  try {
    Class<?> c = Class.forName(
        "org.apache.hadoop.hbase.security.token.TokenUtil");
    Methods.call(c, null, "obtainTokenForJob",
        new Class[]{JobConf.class, UserGroupInformation.class},
        new Object[]{job, ugi});
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Failure loading TokenUtil class, "
        +"is secure RPC available?", cnfe);
  } catch (IOException ioe) {
    throw ioe;
  } catch (InterruptedException ie) {
    throw ie;
  } catch (RuntimeException re) {
    throw re;
  } catch (Exception e) {
    throw new UndeclaredThrowableException(e,
        "Unexpected error calling TokenUtil.obtainAndCacheToken()");
  }
}
 
Example 25
Project: restclient   File: ExceptionUtil.java   View source code 5 votes vote down vote up
public static Throwable unwrapThrowable(Throwable wrapped) {
    Throwable unwrapped = wrapped;
    while (true) {
        if (unwrapped instanceof InvocationTargetException) {
            unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
        } else if (unwrapped instanceof UndeclaredThrowableException) {
            unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
        } else {
            return unwrapped;
        }
    }
}
 
Example 26
Project: hadoop-oss   File: UserGroupInformation.java   View source code 5 votes vote down vote up
/**
 * 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 == null) {
      throw new RuntimeException("PrivilegedActionException with no " +
              "underlying cause. UGI [" + this + "]" +": " + pae, pae);
    } else 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);
    }
  }
}
 
Example 27
Project: hadoop-oss   File: TestRetryProxy.java   View source code 5 votes vote down vote up
@Test
public void testRetryInterruptible() throws Throwable {
  final UnreliableInterface unreliable = (UnreliableInterface)
      RetryProxy.create(UnreliableInterface.class, unreliableImpl,
          retryUpToMaximumTimeWithFixedSleep(10, 10, TimeUnit.SECONDS));
  
  final CountDownLatch latch = new CountDownLatch(1);
  final AtomicReference<Thread> futureThread = new AtomicReference<Thread>();
  ExecutorService exec = Executors.newSingleThreadExecutor();
  Future<Throwable> future = exec.submit(new Callable<Throwable>(){
    @Override
    public Throwable call() throws Exception {
      futureThread.set(Thread.currentThread());
      latch.countDown();
      try {
        unreliable.alwaysFailsWithFatalException();
      } catch (UndeclaredThrowableException ute) {
        return ute.getCause();
      }
      return null;
    }
  });
  latch.await();
  Thread.sleep(1000); // time to fail and sleep
  assertTrue(futureThread.get().isAlive());
  futureThread.get().interrupt();
  Throwable e = future.get(1, TimeUnit.SECONDS); // should return immediately 
  assertNotNull(e);
  assertEquals(InterruptedException.class, e.getClass());
  assertEquals("sleep interrupted", e.getMessage());
}
 
Example 28
Project: quartz-web   File: ReflectionUtils.java   View source code 5 votes vote down vote up
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);
}
 
Example 29
Project: quartz-web   File: ReflectionUtils.java   View source code 5 votes vote down vote up
public static void rethrowRuntimeException(Throwable ex) {
    if (ex instanceof RuntimeException) {
        throw (RuntimeException) ex;
    }
    if (ex instanceof Error) {
        throw (Error) ex;
    }
    throw new UndeclaredThrowableException(ex);
}
 
Example 30
Project: alfresco-repository   File: AJExtender.java   View source code 5 votes vote down vote up
static Throwable asCheckThrowable(Throwable error, Class<?>... checkedThrowableTypes)
{
    Class<? extends Throwable> errorClass = error.getClass();
    for (int i = 0; i < checkedThrowableTypes.length; i++)
    {
        if (errorClass.equals(checkedThrowableTypes[i]))
        {
            return error;
        }
    }
    return new UndeclaredThrowableException(error);
}
 
Example 31
Project: HL4A   File: SecureCaller.java   View source code 5 votes vote down vote up
private static byte[] loadBytecodePrivileged()
{
    URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz");
    try
    {
        InputStream in = url.openStream();
        try
        {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            for(;;)
            {
                int r = in.read();
                if(r == -1)
                {
                    return bout.toByteArray();
                }
                bout.write(r);
            }
        }
        finally
        {
            in.close();
        }
    }
    catch(IOException e)
    {
        throw new UndeclaredThrowableException(e);
    }
}
 
Example 32
Project: guava-mock   File: FuturesTransformTest.java   View source code 5 votes vote down vote up
@Override
public String apply(Integer input) {
  if (input.intValue() == VALID_INPUT_DATA) {
    return RESULT_DATA;
  } else {
    throw new UndeclaredThrowableException(EXCEPTION);
  }
}
 
Example 33
Project: guava-mock   File: FuturesTransformAsyncTest.java   View source code 5 votes vote down vote up
@Override
public ListenableFuture<String> apply(Integer input) {
  switch (input) {
    case VALID_INPUT_DATA: outputFuture.set(RESULT_DATA); break;
    case SLOW_OUTPUT_VALID_INPUT_DATA: break;  // do nothing to the result
    case SLOW_FUNC_VALID_INPUT_DATA:
      funcIsWaitingLatch.countDown();
      awaitUninterruptibly(funcCompletionLatch);
      break;
    default: throw new UndeclaredThrowableException(EXCEPTION);
  }
  return outputFuture;
}
 
Example 34
Project: lams   File: BeanProperty.java   View source code 5 votes vote down vote up
/**
 * Gets the value of this property for the specified Object.
 * 
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public Object get(final Object member) throws IllegalArgumentException, IllegalAccessException {
    if (!isReadable()) {
        throw new IllegalStateException("Property " + propertyName + " of " + memberClass + " not readable");
    }

    try {
        return getter.invoke(member);
    } catch (final InvocationTargetException e) {
        throw new UndeclaredThrowableException(e.getTargetException());
    }
}
 
Example 35
Project: lams   File: BeanProperty.java   View source code 5 votes vote down vote up
/**
 * Sets the value of this property for the specified Object.
 * 
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public Object set(final Object member, final Object newValue)
        throws IllegalArgumentException, IllegalAccessException {
    if (!isWritable()) {
        throw new IllegalStateException("Property " + propertyName + " of " + memberClass + " not writable");
    }

    try {
        return setter.invoke(member, newValue);
    } catch (final InvocationTargetException e) {
        throw new UndeclaredThrowableException(e.getTargetException());
    }
}
 
Example 36
Project: FirefoxData-android   File: BackoffStrategyExec.java   View source code 5 votes vote down vote up
public CloseableHttpResponse execute(
        final HttpRoute route,
        final HttpRequestWrapper request,
        final HttpClientContext context,
        final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");
    CloseableHttpResponse out = null;
    try {
        out = this.requestExecutor.execute(route, request, context, execAware);
    } catch (final Exception ex) {
        if (out != null) {
            out.close();
        }
        if (this.connectionBackoffStrategy.shouldBackoff(ex)) {
            this.backoffManager.backOff(route);
        }
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        }
        if (ex instanceof HttpException) {
            throw (HttpException) ex;
        }
        if (ex instanceof IOException) {
            throw (IOException) ex;
        }
        throw new UndeclaredThrowableException(ex);
    }
    if (this.connectionBackoffStrategy.shouldBackoff(out)) {
        this.backoffManager.backOff(route);
    } else {
        this.backoffManager.probe(route);
    }
    return out;
}
 
Example 37
Project: spring-backend-boilerplate   File: TOTP.java   View source code 5 votes vote down vote up
private static byte[] hmac_sha(String crypto, byte[] keyBytes, byte[] text) {
	try {
		Mac hmac;
		hmac = Mac.getInstance(crypto);
		SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
		hmac.init(macKey);
		return hmac.doFinal(text);
	}
	catch (GeneralSecurityException gse) {
		throw new UndeclaredThrowableException(gse);
	}
}
 
Example 38
Project: whackpad   File: SecureCaller.java   View source code 5 votes vote down vote up
private static byte[] loadBytecodePrivileged()
{
    URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz");
    try
    {
        InputStream in = url.openStream();
        try
        {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            for(;;)
            {
                int r = in.read();
                if(r == -1)
                {
                    return bout.toByteArray();
                }
                bout.write(r);
            }
        }
        finally
        {
            in.close();
        }
    }
    catch(IOException e)
    {
        throw new UndeclaredThrowableException(e);
    }
}
 
Example 39
Project: hadoop   File: TimelineClientImpl.java   View source code 5 votes vote down vote up
private ClientResponse doPosting(final Object obj, final String path)
    throws IOException, YarnException {
  ClientResponse resp;
  try {
    resp = authUgi.doAs(new PrivilegedExceptionAction<ClientResponse>() {
      @Override
      public ClientResponse run() throws Exception {
        return doPostingObject(obj, path);
      }
    });
  } catch (UndeclaredThrowableException e) {
      throw new IOException(e.getCause());
  } catch (InterruptedException ie) {
    throw new IOException(ie);
  }
  if (resp == null ||
      resp.getClientResponseStatus() != ClientResponse.Status.OK) {
    String msg =
        "Failed to get the response from the timeline server.";
    LOG.error(msg);
    if (LOG.isDebugEnabled() && resp != null) {
      String output = resp.getEntity(String.class);
      LOG.debug("HTTP error code: " + resp.getStatus()
          + " Server response : \n" + output);
    }
    throw new YarnException(msg);
  }
  return resp;
}
 
Example 40
Project: hadoop   File: TimelineClientImpl.java   View source code 5 votes vote down vote up
@Override
public HttpURLConnection getHttpURLConnection(final URL url) throws IOException {
  authUgi.checkTGTAndReloginFromKeytab();
  try {
    return new DelegationTokenAuthenticatedURL(
        authenticator, connConfigurator).openConnection(url, token,
          doAsUser);
  } catch (UndeclaredThrowableException e) {
    throw new IOException(e.getCause());
  } catch (AuthenticationException ae) {
    throw new IOException(ae);
  }
}