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:edu.stolaf.cs.wmrserver.JobServiceHandler.java

public static InternalException wrapException(String message, Throwable cause) {
    InternalException ex = new InternalException(message);

    // Serialize cause chain
    ArrayList<CausingException> causeChain = new ArrayList<CausingException>();
    while (cause != null) {
        CausingException causeStruct = new CausingException();

        causeStruct.setMessage(cause.getMessage());
        causeStruct.setType(cause.getClass().getName());

        // Store stack trace as string
        StringWriter stackTraceWriter = new StringWriter();
        cause.printStackTrace(new PrintWriter(stackTraceWriter));
        causeStruct.setStackTrace(stackTraceWriter.toString());

        causeChain.add(causeStruct);/*from   w w w .  ja v  a2s .  c  o m*/

        // Move to next in chain and loop
        cause = cause.getCause();
    }
    ex.setCauses(causeChain);

    return ex;
}

From source file:org.glowroot.central.SyntheticMonitorService.java

private static String getBestMessageForSyntheticFailure(Throwable throwable) {
    String message = throwable.getMessage();
    if (throwable.getClass() == Exception.class && throwable.getCause() == null && message != null) {
        // special case so synthetic monitors can display a simple error message without the
        // exception class name clutter
        return message;
    } else {/*from  www.jav a  2s . c  o m*/
        return Throwables.getBestMessage(throwable);
    }
}

From source file:com.oncore.calorders.core.utils.FormatHelper.java

/**
 * This method returns the stack trace of an exception
 *
 * @param throwable The exception//  w  w w.  ja  v a2  s . c o  m
 * @return The stack trace in string
 */
public static String getStackTrace(Throwable throwable) {
    StringBuilder trace = new StringBuilder();
    trace.append(throwable.getClass().getCanonicalName());
    trace.append("\n\t");

    trace.append(throwable.getMessage());
    trace.append("\n");

    for (StackTraceElement stackTrace : throwable.getStackTrace()) {
        trace.append(stackTrace.toString());
        trace.append("\n\t");
    }

    return trace.toString();
}

From source file:fiftyfive.wicket.util.LoggingUtils.java

/**
 * Attempts to find the most meaningful exception in a runtime exception
 * chain by stripping away the exceptions commonly used as "wrappers",
 * namely: RuntimeException, WicketRuntimeException,
 * InvocationTargetException and ExecutionException. These four exception
 * types are usually language cruft that don't add much desciptive value.
 * <p>/*from   www.  j  a v a 2  s .com*/
 * For example, if the exception chain is:
 * <pre class="example">
 * WicketRuntimeException
 * -> InvocationTargetException
 *    -> MyBusinessException
 *       -> SQLException</pre>
 * <p>
 * Then the unwrapped exception would be {@code MyBusinessException}. 
 */
public static Throwable unwrap(Throwable e) {
    Args.notNull(e, "e");

    Throwable unwrapped = e;
    while (true) {
        Throwable cause = null;

        if (unwrapped instanceof WicketRuntimeException || unwrapped instanceof InvocationTargetException
                || unwrapped instanceof ExecutionException
                || unwrapped.getClass().equals(RuntimeException.class)) {
            cause = unwrapped.getCause();
        }
        if (null == cause || unwrapped == cause) {
            break;
        }
        unwrapped = cause;
    }
    return unwrapped;
}

From source file:net.opentsdb.tree.Branch.java

/**
 * Attempts to fetch the branch, it's leaves and all child branches.
 * The UID names for each leaf may also be loaded if configured.
 * @param tsdb The TSDB to use for storage access
 * @param branch_id ID of the branch to retrieve
 * @param load_leaf_uids Whether or not to load UID names for each leaf
 * @return A branch if found, null if it did not exist
 * @throws JSONException if the object could not be deserialized
 *///from   ww  w .ja  v  a 2  s . co  m
public static Deferred<Branch> fetchBranch(final TSDB tsdb, final byte[] branch_id,
        final boolean load_leaf_uids) {

    final Deferred<Branch> result = new Deferred<Branch>();
    final Scanner scanner = setupBranchScanner(tsdb, branch_id);

    // This is the branch that will be loaded with data from the scanner and
    // returned at the end of the process.
    final Branch branch = new Branch();

    // A list of deferreds to wait on for child leaf processing
    final ArrayList<Deferred<Object>> leaf_group = new ArrayList<Deferred<Object>>();

    /**
     * Exception handler to catch leaves with an invalid UID name due to a 
     * possible deletion. This will allow the scanner to keep loading valid
     * leaves and ignore problems. The fsck tool can be used to clean up
     * orphaned leaves. If we catch something other than an NSU, it will
     * re-throw the exception
     */
    final class LeafErrBack implements Callback<Object, Exception> {

        final byte[] qualifier;

        public LeafErrBack(final byte[] qualifier) {
            this.qualifier = qualifier;
        }

        @Override
        public Object call(final Exception e) throws Exception {
            Throwable ex = e;
            while (ex.getClass().equals(DeferredGroupException.class)) {
                ex = ex.getCause();
            }
            if (ex.getClass().equals(NoSuchUniqueId.class)) {
                LOG.debug("Invalid UID for leaf: " + idToString(qualifier) + " in branch: "
                        + idToString(branch_id), ex);
            } else {
                throw (Exception) ex;
            }
            return null;
        }

    }

    /**
     * Called after a leaf has been loaded successfully and adds the leaf
     * to the branch's leaf set. Also lazily initializes the leaf set if it 
     * hasn't been.
     */
    final class LeafCB implements Callback<Object, Leaf> {

        @Override
        public Object call(final Leaf leaf) throws Exception {
            if (leaf != null) {
                if (branch.leaves == null) {
                    branch.leaves = new HashMap<Integer, Leaf>();
                }
                branch.leaves.put(leaf.hashCode(), leaf);
            }
            return null;
        }

    }

    /**
     * Scanner callback executed recursively each time we get a set of data
     * from storage. This is responsible for determining what columns are 
     * returned and issuing requests to load leaf objects.
     * When the scanner returns a null set of rows, the method initiates the
     * final callback.
     */
    final class FetchBranchCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> {

        /**
         * Starts the scanner and is called recursively to fetch the next set of
         * rows from the scanner.
         * @return The branch if loaded successfully, null if the branch was not
         * found.
         */
        public Object fetchBranch() {
            return scanner.nextRows().addCallback(this);
        }

        /**
         * Loops through each row of the scanner results and parses out branch
         * definitions and child leaves.
         * @return The final branch callback if the scanner returns a null set
         */
        @Override
        public Object call(final ArrayList<ArrayList<KeyValue>> rows) throws Exception {
            if (rows == null) {
                if (branch.tree_id < 1 || branch.path == null) {
                    result.callback(null);
                } else {
                    result.callback(branch);
                }
                return null;
            }

            for (final ArrayList<KeyValue> row : rows) {
                for (KeyValue column : row) {

                    // matched a branch column
                    if (Bytes.equals(BRANCH_QUALIFIER, column.qualifier())) {
                        if (Bytes.equals(branch_id, column.key())) {

                            // it's *this* branch. We deserialize to a new object and copy
                            // since the columns could be in any order and we may get a 
                            // leaf before the branch
                            final Branch local_branch = JSON.parseToObject(column.value(), Branch.class);
                            branch.path = local_branch.path;
                            branch.display_name = local_branch.display_name;
                            branch.tree_id = Tree.bytesToId(column.key());

                        } else {
                            // it's a child branch
                            final Branch child = JSON.parseToObject(column.value(), Branch.class);
                            child.tree_id = Tree.bytesToId(column.key());
                            branch.addChild(child);
                        }
                        // parse out a leaf
                    } else if (Bytes.memcmp(Leaf.LEAF_PREFIX(), column.qualifier(), 0,
                            Leaf.LEAF_PREFIX().length) == 0) {
                        if (Bytes.equals(branch_id, column.key())) {
                            // process a leaf and skip if the UIDs for the TSUID can't be 
                            // found. Add an errback to catch NoSuchUniqueId exceptions
                            leaf_group.add(Leaf.parseFromStorage(tsdb, column, load_leaf_uids)
                                    .addCallbacks(new LeafCB(), new LeafErrBack(column.qualifier())));
                        } else {
                            // TODO - figure out an efficient way to increment a counter in 
                            // the child branch with the # of leaves it has
                        }
                    }
                }
            }

            // recursively call ourself to fetch more results from the scanner
            return fetchBranch();
        }
    }

    // start scanning
    new FetchBranchCB().fetchBranch();
    return result;
}

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

/**
 * <p>//  w ww  . j ava 2 s.  c  om
 * Finds a <code>Throwable</code> by field name.
 * </p>
 * 
 * @param throwable
 *          the exception to examine
 * @param fieldName
 *          the name of the attribute to examine
 * @return the wrapped exception, or <code>null</code> if not found
 */
private static Throwable getCauseUsingFieldName(Throwable throwable, String fieldName) {
    Field field = null;
    try {
        field = throwable.getClass().getField(fieldName);
    } catch (NoSuchFieldException ignored) {
    } catch (SecurityException ignored) {
    }

    if (field != null && Throwable.class.isAssignableFrom(field.getType())) {
        try {
            return (Throwable) field.get(throwable);
        } catch (IllegalAccessException ignored) {
        } catch (IllegalArgumentException ignored) {
        }
    }
    return null;
}

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

/**
 * <p>//from  w  w w  .j av a2 s  . c om
 * Finds a <code>Throwable</code> by method name.
 * </p>
 * 
 * @param throwable
 *          the exception to examine
 * @param methodName
 *          the name of the method to find and invoke
 * @return the wrapped exception, or <code>null</code> if not found
 */
private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) {
    Method method = null;
    try {
        method = throwable.getClass().getMethod(methodName, (Class[]) null);
    } catch (NoSuchMethodException ignored) {
    } catch (SecurityException ignored) {
    }

    if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
        try {
            return (Throwable) method.invoke(throwable, EMPTY_OBJECT_ARRAY);
        } catch (IllegalAccessException ignored) {
        } catch (IllegalArgumentException ignored) {
        } catch (InvocationTargetException ignored) {
        }
    }
    return null;
}

From source file:org.jruby.rack.mock.WebUtils.java

/**
 * Expose the Servlet spec's error attributes as {@link javax.servlet.http.HttpServletRequest}
 * attributes under the keys defined in the Servlet 2.3 specification, for error pages that
 * are rendered directly rather than through the Servlet container's error page resolution:
 * {@code javax.servlet.error.status_code},
 * {@code javax.servlet.error.exception_type},
 * {@code javax.servlet.error.message},/*from   w ww  .j  a  v a 2s .c o  m*/
 * {@code javax.servlet.error.exception},
 * {@code javax.servlet.error.request_uri},
 * {@code javax.servlet.error.servlet_name}.
 * <p>Does not override values if already present, to respect attribute values
 * that have been exposed explicitly before.
 * <p>Exposes status code 200 by default. Set the "javax.servlet.error.status_code"
 * attribute explicitly (before or after) in order to expose a different status code.
 * @param request current servlet request
 * @param ex the exception encountered
 * @param servletName the name of the offending servlet
 */
public static void exposeErrorRequestAttributes(HttpServletRequest request, Throwable ex, String servletName) {
    exposeRequestAttributeIfNotPresent(request, ERROR_STATUS_CODE_ATTRIBUTE, HttpServletResponse.SC_OK);
    exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_TYPE_ATTRIBUTE, ex.getClass());
    exposeRequestAttributeIfNotPresent(request, ERROR_MESSAGE_ATTRIBUTE, ex.getMessage());
    exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_ATTRIBUTE, ex);
    exposeRequestAttributeIfNotPresent(request, ERROR_REQUEST_URI_ATTRIBUTE, request.getRequestURI());
    exposeRequestAttributeIfNotPresent(request, ERROR_SERVLET_NAME_ATTRIBUTE, servletName);
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Sets the HTTP status on the response according to the exception
 * /*from  w ww. j ava  2  s . co  m*/
 * @param ex
 * @param response
 */
public static void setResponseStatus(Throwable ex, HttpServletResponse response) {
    ResponseStatus ann = ex.getClass().getAnnotation(ResponseStatus.class);
    if (ann != null) {
        if (StringUtils.isNotBlank(ann.reason())) {
            response.setStatus(ann.value().value(), ann.reason());
        } else {
            response.setStatus(ann.value().value());
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:Debug.java

public static String getDebug(Throwable e, int max) {
    StringBuffer result = new StringBuffer();

    String datetime = timestamp.format(new Date()).toLowerCase();

    result.append(newline);/*www . j  a  v  a 2 s  .c o m*/
    result.append("Throwable: " + ((e == null) ? "" : ("(" + e.getClass().getName() + ")")) + ":" + datetime
            + newline);
    result.append("Throwable: " + ((e == null) ? "null" : e.getLocalizedMessage()) + newline);
    result.append(newline);

    result.append(getStackTrace(e, max));

    result.append("Caught here:" + newline);
    result.append(getStackTrace(new Exception(), max, 1));
    //        Debug.dumpStack();
    result.append(newline);
    return result.toString();
}