Example usage for java.lang Throwable getClass

List of usage examples for java.lang Throwable getClass

Introduction

In this page you can find the example usage for java.lang Throwable getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:net.joala.condition.timing.WaitFailStrategyTest.java

@Test
public void message_on_failed_match_should_be_contained_in_exception() throws Throwable {
    final S strategy = getFailStrategy();
    final String message = FAIL_MESSAGE_PROVIDER.get();
    boolean success = false;
    try {//from   w  w  w .ja  va 2 s.  c  o m
        strategy.fail(message, failedFunction, failedInput, failedLastValue, nullValue(),
                CONSUMED_MILLIS_PROVIDER.get());
        success = true;
    } catch (Throwable t) {
        if (!getRaisedExceptionType().isAssignableFrom(t.getClass())) {
            throw t;
        }
        assertThat("Message should be contained in exception message.", t.getMessage(),
                containsString(message));
    }
    assertFalse("An exception should have been thrown.", success);
}

From source file:net.joala.condition.timing.WaitFailStrategyTest.java

@Test
public void cause_when_failed_with_exception_should_be_contained_in_exception() throws Throwable {
    final S strategy = getFailStrategy();
    final String evaluationExceptionMessage = EXCEPTION_MESSAGE_PROVIDER.get();
    doAnswer(invocation -> {//  w w  w  .  j  av a 2  s  .  c o m
        invocation.getArgumentAt(0, PrintWriter.class).append(evaluationExceptionMessage);
        return null;
    }).when(lastFailure).printStackTrace(any(PrintWriter.class));
    boolean success = false;
    try {
        strategy.fail(FAIL_MESSAGE_PROVIDER.get(), failedFunction, failedInput, lastFailure,
                CONSUMED_MILLIS_PROVIDER.get());
        success = true;
    } catch (Throwable t) {
        if (!getRaisedExceptionType().isAssignableFrom(t.getClass())) {
            throw t;
        }
        assertThat("Cause should be mentioned in failure.", t,
                anyOf(causedBy(lastFailure), messageContains(evaluationExceptionMessage, true)));
    }
    assertFalse("An exception should have been thrown.", success);
}

From source file:com.flipkart.flux.impl.task.AkkaTask.java

/**
 * Callback method when this Actor is restarted by the Supervisor actor. This happens only when this Actor throws FluxError.ErrorType.timeout.
 * @see akka.actor.UntypedActor#preRestart(java.lang.Throwable, scala.Option)
 *//*from   w w w. j  a v a  2s  .  c o m*/
public void preRestart(Throwable reason, Option<Object> message) {
    if (FluxError.class.isAssignableFrom(reason.getClass())
            && TaskAndEvents.class.isAssignableFrom(message.get().getClass())) {
        FluxError fluxError = (FluxError) reason;
        TaskAndEvents taskAndEvent = (TaskAndEvents) message.get();
        taskAndEvent.setCurrentRetryCount(fluxError.getExecutionContextMeta().getAttemptedNoOfRetries() + 1); // increment the retry count
        // update the Flux runtime incrementing the retry count for the Task
        fluxRuntimeConnector.incrementExecutionRetries(taskAndEvent.getStateMachineId(),
                taskAndEvent.getTaskId());
        // we reschedule the message back on this Actor to see if it goes through when retried. TODO : Uses a fixed 1 second time delay and no exponential backoff for now
        getContext().system().scheduler().scheduleOnce(FiniteDuration.create(1, TimeUnit.SECONDS), getSelf(),
                taskAndEvent, getContext().system().dispatcher(), null);
    }
}

From source file:com.free.exception.ExceptionHelper.java

/**
 * <p>/* w ww  .  j  a v a  2s . c o  m*/
 * Checks whether this <code>Throwable</code> class can store a cause.
 * </p>
 * <p/>
 * <p>
 * This method does <b>not</b> check whether it actually does store a cause.
 * <p>
 * 
 * @param throwable
 *          the <code>Throwable</code> to examine, may be null
 * @return boolean <code>true</code> if nested otherwise <code>false</code>
 * @since 2.0
 */
public static boolean isNestedThrowable(Throwable throwable) {
    if (throwable == null) {
        return false;
    }

    if (throwable instanceof Nestable) {
        return true;
    } else if (throwable instanceof SQLException) {
        return true;
    } else if (throwable instanceof InvocationTargetException) {
        return true;
    } else if (isThrowableNested()) {
        return true;
    }

    Class<?> cls = throwable.getClass();
    for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
        try {
            Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], (Class[]) null);
            if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
                return true;
            }
        } catch (NoSuchMethodException ignored) {
        } catch (SecurityException ignored) {
        }
    }

    try {
        Field field = cls.getField("detail");
        if (field != null) {
            return true;
        }
    } catch (NoSuchFieldException ignored) {
    } catch (SecurityException ignored) {
    }

    return false;
}

From source file:com.google.sampling.experiential.server.MigrationBackendServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // resp.setContentType("application/json;charset=UTF-8");

    // User user = getWhoFromLogin();

    final String requestorEmail = getRequestorEmail(req);

    final String jobId = DigestUtils.md5Hex(requestorEmail + Long.toString(System.currentTimeMillis()));

    log.info("In migrate backend for job: " + jobId);
    final ReportJobStatusManager statusMgr = new ReportJobStatusManager();
    statusMgr.startReport(requestorEmail, jobId);
    final ClassLoader cl = getClass().getClassLoader();
    final Thread thread2 = ThreadManager.createBackgroundThread(new Runnable() {
        @Override//from   w  ww .j  av a 2  s.  c  om
        public void run() {

            log.info("MigrationBackend running");
            Thread.currentThread().setContextClassLoader(cl);
            try {
                doMigrations();
                statusMgr.completeReport(requestorEmail, jobId, "NA");
            } catch (Throwable e) {
                statusMgr.failReport(requestorEmail, jobId, e.getClass() + "." + e.getMessage());
                log.severe("Could not run migration job: " + e.getMessage());
            }
        }
    });
    thread2.start();
    log.info("Leaving migration backend");
    resp.setContentType("text/plain;charset=UTF-8");
    resp.getWriter().println(jobId);
}

From source file:com.yahoo.parsec.clients.ParsecHttpRequestRetryCallable.java

/**
 * Check status code and handles retry if T is type {@link Response} or Ning {@link com.ning.http.client.Response}.
 *
 * @return T//from   w w w .j a  va 2s .c  o  m
 * @throws Exception exception
 */
@Override
public T call() throws Exception {
    responses.clear();
    final Request ningRequest = request.getNingRequest();
    final List<Integer> retryStatusCodes = request.getRetryStatusCodes();
    final List<Class<? extends Throwable>> retryExceptions = request.getRetryExceptions();
    final int maxRetries = request.getMaxRetries();

    T response;
    Exception exception;
    int retries = 0;
    for (;;) {
        response = null;
        exception = null;
        try {
            response = executeRequest(ningRequest);
            responses.add(response);
            int statusCode = getStatusCode(response);
            if (statusCode == -1 || !retryStatusCodes.contains(statusCode)) {
                break;
            }
        } catch (Exception e) {
            Throwable root = ExceptionUtils.getRootCause(e);
            if (!retryExceptions.contains(root.getClass())) {
                throw e;
            }
            exception = e;
        }

        if (retries == maxRetries) {
            LOGGER.debug("Max retries reached: " + retries + " (max: " + maxRetries + ")");
            break;
        }
        retries++;
        LOGGER.debug("Retry number: " + retries + " (max: " + maxRetries + ")");
    }
    if (exception != null) {
        throw exception;
    }
    return response;
}

From source file:net.joala.condition.timing.WaitFailStrategyTest.java

@Test
public void failed_match_method_should_throw_exception() throws Exception {
    final S strategy = getFailStrategy();
    boolean success = false;
    try {//from  w  ww  . j a v  a2s. c o  m
        strategy.fail(FAIL_MESSAGE_PROVIDER.get(), failedFunction, failedInput, failedLastValue, nullValue(),
                CONSUMED_MILLIS_PROVIDER.get());
        success = true;
    } catch (RuntimeException ignored) {
        // fine, that's what we expected
    } catch (Error ignored) {
        // fine that's what we expected
    } catch (Throwable t) {
        fail(format("Unexpected exception of type %s thrown.", t.getClass()));
    }
    assertFalse("An exception should have been thrown.", success);
}

From source file:net.joala.condition.timing.WaitFailStrategyTest.java

@Test
public void failed_with_exceptions_method_should_throw_exception() throws Exception {
    final S strategy = getFailStrategy();
    boolean success = false;
    try {//from   w  ww  .  j a va2 s  .c om
        strategy.fail(FAIL_MESSAGE_PROVIDER.get(), failedFunction, failedInput, lastFailure,
                CONSUMED_MILLIS_PROVIDER.get());
        success = true;
    } catch (RuntimeException ignored) {
        // fine, that's what we expected
    } catch (Error ignored) {
        // fine that's what we expected
    } catch (Throwable t) {
        fail(format("Unexpected exception of type %s thrown.", t.getClass()));
    }
    assertFalse("An exception should have been thrown.", success);
}

From source file:com.espertech.esper.core.PatternListenerDispatch.java

public void execute() {
    EventBean[] eventArray;/*  w w w  . j ava2 s  . c o  m*/

    if (eventList != null) {
        eventArray = eventList.toArray(new EventBean[eventList.size()]);
        eventList = null;
        singleEvent = null;
    } else {
        eventArray = new EventBean[] { singleEvent };
        singleEvent = null;
    }

    for (UpdateListener listener : listeners) {
        try {
            listener.update(eventArray, null);
        } catch (Throwable t) {
            String message = "Unexpected exception invoking listener update method on listener class '"
                    + listener.getClass().getSimpleName() + "' : " + t.getClass().getSimpleName() + " : "
                    + t.getMessage();
            log.error(message, t);
        }
    }
}

From source file:at.wada811.android.library.demos.CrashExceptionHandler.java

/**
 * ?//from  ww w  .  j a  v a  2 s  .  c  om
 * 
 * @param throwable
 * @return
 * @throws JSONException
 */
private JSONObject getExceptionInfo(Throwable throwable) throws JSONException {
    JSONObject json = new JSONObject();
    json.put("name", throwable.getClass().getName());
    json.put("message", throwable.getMessage());
    if (throwable.getStackTrace() != null) {
        // ExceptionStacktrace
        JSONArray exceptionStacktrace = new JSONArray();
        for (StackTraceElement element : throwable.getStackTrace()) {
            exceptionStacktrace.put("at " + LogUtils.getMetaInfo(element));
        }
        json.put("ExceptionStacktrace", exceptionStacktrace);
    }
    if (throwable.getCause() != null) {
        json.put("cause", throwable.getCause());
        // CausedStacktrace
        if (throwable.getCause().getStackTrace() != null) {
            JSONArray causedStacktrace = new JSONArray();
            for (StackTraceElement element : throwable.getCause().getStackTrace()) {
                causedStacktrace.put("at " + LogUtils.getMetaInfo(element));
            }
            json.put("CausedStacktrace", causedStacktrace);
        }
    }
    return json;
}