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:com.alliander.osgp.acceptancetests.schedulemanagement.SetScheduleSteps.java

@DomainStep("the set schedule request is received")
public void whenTheSetScheduleRequestIsReceived() {
    LOGGER.info("WHEN: \"the set schedule request is received\".");

    try {/*  w w w . j av  a2  s .  co  m*/

        this.setScheduleAsyncResponse = this.scheduleManagementEndpoint.setLightSchedule(ORGANISATION_ID,
                this.request);
    } catch (final Throwable t) {
        LOGGER.error("Exception [{}]: {}", t.getClass().getSimpleName(), t.getMessage());
        this.throwable = t;
    }
}

From source file:io.teak.sdk.Raven.java

public void reportException(Throwable t) {
    if (t == null) {
        return;//from w  w  w.j  av a  2s .  c o m
    }

    HashMap<String, Object> additions = new HashMap<>();
    ArrayList<Object> exceptions = new ArrayList<>();
    HashMap<String, Object> exception = new HashMap<>();

    exception.put("type", t.getClass().getSimpleName());
    exception.put("value", t.getMessage());
    exception.put("module", t.getClass().getPackage().getName());

    HashMap<String, Object> stacktrace = new HashMap<>();
    ArrayList<Object> stackFrames = new ArrayList<>();

    StackTraceElement[] steArray = t.getStackTrace();
    for (int i = steArray.length - 1; i >= 0; i--) {
        StackTraceElement ste = steArray[i];
        HashMap<String, Object> frame = new HashMap<>();

        frame.put("filename", ste.getFileName());

        String method = ste.getMethodName();
        if (method.length() != 0) {
            frame.put("function", method);
        }

        int lineno = ste.getLineNumber();
        if (!ste.isNativeMethod() && lineno >= 0) {
            frame.put("lineno", lineno);
        }

        String module = ste.getClassName();
        frame.put("module", module);

        boolean in_app = true;
        if (module.startsWith("android.") || module.startsWith("java.") || module.startsWith("dalvik.")
                || module.startsWith("com.android.")) {
            in_app = false;
        }

        frame.put("in_app", in_app);

        stackFrames.add(frame);
    }
    stacktrace.put("frames", stackFrames);

    exception.put("stacktrace", stacktrace);

    exceptions.add(exception);
    additions.put("exception", exceptions);

    try {
        Report report = new Report(t.getMessage(), Level.ERROR, additions);
        report.sendToService();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to report Teak SDK exception. " + Log.getStackTraceString(t) + "\n"
                + Log.getStackTraceString(e));
    }
}

From source file:com.jkoolcloud.tnt4j.utils.Utils.java

/**
 * Generates a detailed description of an exception, including stack trace
 * of both the exception and the underlying root cause of the exception, if
 * any.//w w  w . j  a v  a2s .  c o  m
 *
 * @param ex
 *            exception to process
 * @return String representation of exception
 * @see #getStackTrace(Throwable)
 */
public static String getExceptionDetail(Throwable ex) {
    if (ex == null)
        return "";

    String detail = getStackTrace(ex);

    // find the root cause of exception
    Throwable rootCause = null;
    for (;;) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            try {
                Method method = ex.getClass().getMethod("getTargetException", (Class[]) null);
                Object target = method.invoke(ex, (Object[]) null);
                if (target instanceof Throwable)
                    cause = (Throwable) target;
            } catch (Exception exx) {
            }
        }

        if (cause == null)
            break;

        ex = cause;
        rootCause = cause;
    }

    if (rootCause != null)
        detail += LINE_FEED + "Root cause:" + LINE_FEED + getStackTrace(rootCause);

    return detail;
}

From source file:com.alliander.osgp.acceptancetests.devicemanagement.SetEventNotificationsSteps.java

@DomainStep("the get set event notifications response request should return a set event notifications response with result (.*) and description (.*)")
public boolean thenTheGetSetEventNotificationsResultRequestShouldReturnAGetSetEventNotificationsResultResponseWithResult(
        final String result, final String description) {
    LOGGER.info(/*from  ww w  . ja  va2s  .  com*/
            "THEN: \"the get set event notifications result request should return a get set event notifications response with result {} and description {}",
            result, description);

    try {
        if ("NOT_OK".equals(result)) {
            Assert.assertNull("Set Schedule Response should be null", this.response);
            Assert.assertNotNull("Throwable should not be null", this.throwable);
            Assert.assertTrue("Throwable should contain a validation exception",
                    this.throwable.getCause() instanceof ValidationException);
        } else {

            Assert.assertNotNull("Response should not be null", this.response);

            final String expectedResult = result.equals("NULL") ? null : result;
            final String actualResult = this.response.getResult().toString();

            Assert.assertTrue("Invalid result, found: " + actualResult + " , expected: " + expectedResult,
                    (actualResult == null && expectedResult == null) || actualResult.equals(expectedResult));
        }
    } catch (final Throwable t) {
        LOGGER.error("Exception [{}]: {}", t.getClass().getSimpleName(), t.getMessage());
        return false;
    }
    return true;
}

From source file:com.microsoft.windowsazure.messaging.e2etestapp.MainActivity.java

private void runTests() {
    TestGroup group = (TestGroup) mTestGroupSpinner.getSelectedItem();

    group.runTests(new TestExecutionCallback() {

        @Override/* ww  w.ja  v a  2 s. co m*/
        public void onTestStart(TestCase test) {
            TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();
            adapter.notifyDataSetChanged();
            log("TEST START", test.getName());
        }

        @Override
        public void onTestGroupComplete(TestGroup group, List<TestResult> results) {
            log("TEST GROUP COMPLETED", group.getName() + " - " + group.getStatus().toString());
            logSeparator();
        }

        @Override
        public void onTestComplete(TestCase test, TestResult result) {
            Throwable e = result.getException();
            String exMessage = "-";
            if (e != null) {
                StringBuilder sb = new StringBuilder();
                while (e != null) {
                    sb.append(e.getClass().getSimpleName() + ": ");
                    sb.append(e.getMessage());
                    sb.append(" // ");
                    e = e.getCause();
                }

                exMessage = sb.toString();
            }

            final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    adapter.notifyDataSetChanged();

                }

            });
            log("TEST LOG", test.getLog());
            log("TEST COMPLETED",
                    test.getName() + " - " + result.getStatus().toString() + " - Ex: " + exMessage);
            logSeparator();
        }
    });

}

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

@Override
public void start(final Environment env) throws IOException {
    final AuthenticationToken authenticationToken = session
            .getAttribute(Constants.SESSION_KEY_AUTHENTICATION_TOKEN);
    if (authenticationToken == null) {
        // should never happen
        throw new IllegalStateException();
    }// w  ww  . j  a va2  s  . co  m

    try {
        String uri = computeCommandPath();

        // path info format is:
        // /<project-identity>/<repository>.git

        Matcher matcher = PATH_PATTERN.matcher(uri);
        if (matcher.matches()) {
            final String projectId = matcher.group(1);
            final String path = matcher.group(2);
            if (path == null || path.indexOf('/') != -1) {
                // short-circuit everything: currently we don't support repositories with nested paths
                pathNotFound(uri);
            }

            final String requestPath = computeRequestPath(path);

            final ProjectService service;
            try {
                service = projectServiceService.findServiceByUri(projectId, requestPath);
            } catch (EntityNotFoundException e) {
                getLogger().info("Project identity not found: " + projectId);
                pathNotFound(uri);
                throw new IllegalStateException();
            }
            if (service == null) {
                getLogger().info(
                        "No ProjectService associated with project " + projectId + " path " + requestPath);
                pathNotFound(uri);
            }
            if (!service.getServiceHost().isAvailable() || service.getServiceHost().getInternalHost() == null) {
                getLogger().info("Service temporarily unavailable for " + projectId + " path " + requestPath);
                throw new CommandException(1, "Repository temporarily unavailable.  Please try again later.");
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // setup the security context
                    AuthenticationToken projectSpecializedToken = internalAuthenticationService
                            .specializeAuthenticationToken(authenticationToken,
                                    service.getProjectServiceProfile().getProject());
                    AuthenticationServiceUser user = AuthenticationServiceUser
                            .fromAuthenticationToken(projectSpecializedToken);
                    SecurityContextHolder.getContext()
                            .setAuthentication(new PreAuthenticatedAuthenticationToken(user,
                                    projectSpecializedToken, user.getAuthorities()));
                    try {
                        establishTenancyContext(projectId);
                        try {
                            if (!hasRequiredRoles()) {
                                getLogger().info("Access denied to " + user.getUsername() + " for " + getName()
                                        + " project:" + projectId + " path:" + requestPath);
                                throw new CommandException(1, "Permission denied");
                            }

                            // propagate the tenant and authentication via request headers
                            RequestHeadersSupport headers = new RequestHeadersSupport();
                            tokenSerializer.serialize(headers, projectSpecializedToken);
                            for (Entry<String, String> header : tenancySerializer.computeHeaders().entrySet()) {
                                headers.addHeader(header.getKey(), header.getValue());
                            }

                            performCommand(env, service, projectId, path, requestPath, headers);
                            callback.onExit(0);
                        } catch (CommandException e) {
                            callback.onExit(e.getReturnCode(), e.getMessage());
                        } catch (Throwable t) {
                            callback.onExit(-1, t.getClass().getSimpleName() + ": " + t.getMessage());
                            getLogger().error(t.getMessage(), t);
                        } finally {
                            TenancyUtil.clearContext();
                        }
                    } finally {
                        SecurityContextHolder.clearContext();
                    }
                }
            });
        } else {
            getLogger().info("Repository path does not match expected pattern: " + uri);
            pathNotFound(uri);
        }
    } catch (CommandException e) {
        getLogger().info("CommandException: " + e.getMessage(), e);
        callback.onExit(e.getReturnCode(), e.getMessage());
    }
}

From source file:com.alliander.osgp.acceptancetests.schedulemanagement.SetScheduleSteps.java

@DomainStep("a set schedule oslp message is sent to device (.*) should be (.*)")
public boolean thenASetScheduleOslpMessageShouldBeSent(final String deviceIdentification,
        final Boolean isMessageSent) {
    LOGGER.info("THEN: \"a set schedule oslp message is sent to device [{}] should be [{}]\".",
            deviceIdentification, isMessageSent);

    final int count = isMessageSent ? 1 : 0;

    try {/*from  w  w  w.ja  v  a  2 s.  c om*/
        final ArgumentCaptor<OslpEnvelope> argument = ArgumentCaptor.forClass(OslpEnvelope.class);
        verify(this.channelMock, timeout(10000).times(count)).write(argument.capture());

        if (isMessageSent) {
            this.oslpMessage = argument.getValue();

            Assert.assertTrue("Message should contain set schedule request.",
                    this.oslpMessage.getPayloadMessage().hasSetScheduleRequest());
        }
    } catch (final Throwable t) {
        LOGGER.error("Exception [{}]: {}", t.getClass().getSimpleName(), t.getMessage());
        return false;
    }
    return true;
}

From source file:jp.xet.uncommons.wicket.utils.ErrorReportRequestCycleListener.java

@Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
    if (ex instanceof PageExpiredException || ex instanceof StalePageException) {
        return null;
    }/*from   w w w .  ja  v a  2s .  co  m*/

    if (ex instanceof WicketRuntimeException) {
        Throwable rootCause = getRootCause(ex);
        if (rootCause == null) {
            rootCause = ex;
        }

        String environment = loadEnvironment();
        if (enabledEnvironments == null || environment == null
                || ObjectUtils.containsElement(enabledEnvironments, environment)) {
            String type = rootCause.getClass().getSimpleName();
            String message = rootCause.getMessage();
            String subject = MessageFormat.format(subjectPattern, environment, type, message);

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(from);
            mailMessage.setTo(to);
            mailMessage.setSubject(subject);
            mailMessage.setText(getStackTrace(ex));
            try {
                logger.debug("sending exception report mail...");
                mailSender.send(mailMessage);
                logger.debug("success to send exception report mail");
            } catch (MailException e) {
                logger.error("failed to send exception report mail", e);
            }
        } else {
            logger.debug(
                    "exception report mail was not sent, "
                            + "because enabledEnvironments{} does not contain environment[{}]",
                    new Object[] { Arrays.toString(enabledEnvironments), environment });
        }
    }
    return null;
}

From source file:com.alliander.osgp.acceptancetests.schedulemanagement.SetScheduleSteps.java

@DomainStep("an ovl set schedule result message with result (.*) and description (.*) should be sent to the ovl out queue")
public boolean thenAnOvlSetScheduleResultMessageShouldBeSentToTheOvlOutQueue(final String result,
        final String description) {
    LOGGER.info(//from w  w w  .j ava  2 s  . c  o m
            "THEN: \"an ovl set schedule result message with result [{}] and description [{}] should be sent to the ovl out queue\".",
            result, description);

    try {
        final ArgumentCaptor<ResponseMessage> argument = ArgumentCaptor.forClass(ResponseMessage.class);
        verify(this.webServiceResponseMessageSenderMock, timeout(10000).times(1)).send(argument.capture());

        final String expected = result.equals("NULL") ? null : result;
        final String actual = argument.getValue().getResult().getValue();

        LOGGER.info("THEN: message description: " + (argument.getValue().getOsgpException() == null ? ""
                : argument.getValue().getOsgpException().getMessage()));

        Assert.assertTrue("Invalid result, found: " + actual + " , expected: " + expected,
                actual.equals(expected));

    } catch (final Throwable t) {
        LOGGER.error("Exception [{}]: {}", t.getClass().getSimpleName(), t.getMessage());
        return false;
    }
    return true;
}

From source file:com.alliander.osgp.acceptancetests.schedulemanagement.SetScheduleSteps.java

@DomainStep("the get set schedule response request should return a set schedule response with result (.*) and description (.*)")
public boolean thenTheGetSetScheduleResultRequestShouldReturnAGetSetScheduleResultResponseWithResult(
        final String result, final String description) {
    LOGGER.info(//ww  w. ja v a2  s  .  c  o  m
            "THEN: \"the get set schedule result request should return a get set schedule response with result {} and description {}\".",
            result, description);

    try {
        if ("NOT_OK".equals(result)) {
            Assert.assertNull("Set Schedule Response should be null", this.response);
            Assert.assertNotNull("Throwable should not be null", this.throwable);
            Assert.assertTrue("Throwable should contain a validation exception",
                    this.throwable.getCause() instanceof ValidationException);
        } else {
            Assert.assertNotNull("Response should not be null", this.response);

            final String expectedResult = result.equals("NULL") ? null : result;
            final String actualResult = this.response.getResult().toString();

            Assert.assertTrue("Invalid result, found: " + actualResult + " , expected: " + expectedResult,
                    (actualResult == null && expectedResult == null) || actualResult.equals(expectedResult));
        }
    } catch (final Throwable t) {
        LOGGER.error("Exception [{}]: {}", t.getClass().getSimpleName(), t.getMessage());
        return false;
    }
    return true;
}