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:fr.gael.dhus.server.http.valve.AccessValve.java

@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    // valve disabled or previous valve sent an error, return
    if (!isEnable() || response.isError()) {
        getNext().invoke(request, response);
        return;/*from   ww  w . j  a  va2  s . c  o m*/
    }

    final AccessInformation ai = new AccessInformation();
    ai.setConnectionStatus(new PendingConnectionStatus());

    // To be sure not to retrieve the same date trough concurrency calls.
    synchronized (this) {
        ai.setStartTimestamp(System.nanoTime());
        ai.setStartDate(new Date());
    }
    try {
        this.doLog(request, response, ai);
    } finally {
        Element cached_element = new Element(UUID.randomUUID(), ai);
        getCache().put(cached_element);

        try {
            // Log of the pending request command.
            if (isUseLogger())
                LOGGER.info("Access " + ai);

            getNext().invoke(request, response);
        } catch (Throwable e) {
            response.addHeader("cause-message", e.getClass().getSimpleName() + " : " + e.getMessage());
            //ai.setConnectionStatus(new FailureConnectionStatus(e));
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            //throw e;
        } finally {
            ai.setReponseSize(response.getContentLength());
            ai.setWrittenResponseSize(response.getContentWritten());

            if (response.getStatus() >= 400) {
                String message = RequestUtil.filter(response.getMessage());
                if (message == null) {
                    // The cause-message has been inserted into the reponse header
                    // at error handler time. It no message is retrieved in the
                    // standard response, the cause-message is used.
                    message = response.getHeader("cause-message");
                }
                Throwable throwable = null;
                if (message != null)
                    throwable = new Throwable(message);
                else
                    throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
                if (throwable == null)
                    throwable = new Throwable();

                ai.setConnectionStatus(new FailureConnectionStatus(throwable));
            } else
                ai.setConnectionStatus(new SuccessConnectionStatus());

            ai.setEndTimestamp(System.nanoTime());
            if ((getPattern() == null) || ai.getRequest().matches(getPattern())) {
                cached_element.updateUpdateStatistics();
                if (isUseLogger())
                    LOGGER.info("Access " + ai);
            }
        }
    }
}

From source file:de.codesourcery.jasm16.ide.ui.views.CPUView.java

private void internalRefreshDisplay() {
    if (emulator == null) {
        return;//from  w ww  . j  ava2 s.  com
    }
    final IReadOnlyCPU cpu = emulator.getCPU();

    final StringBuilder builder = new StringBuilder();
    final List<ITextRegion> redRegions = new ArrayList<ITextRegion>();

    Throwable lastError = emulator.getLastEmulationError();
    if (lastError != null) {
        final String msg = StringUtils.isBlank(lastError.getMessage()) ? lastError.getClass().getName()
                : lastError.getMessage();
        builder.append("Emulation stopped with an error: " + msg + "\n");
        redRegions.add(new TextRegion(0, builder.length()));
    }

    int itemsInLine = 0;
    for (int i = 0; i < ICPU.COMMON_REGISTER_NAMES.length; i++) {
        final int value = cpu.getRegisterValue(ICPU.COMMON_REGISTERS[i]);
        builder.append(ICPU.COMMON_REGISTER_NAMES[i] + ": " + Misc.toHexString(value) + "    ");

        Address address = Address.wordAddress(value);
        final byte[] data = MemUtils.getBytes(emulator.getMemory(), address, Size.words(4), true);

        builder.append(Misc.toHexDump(address, data, data.length, 4, true, false, true));
        builder.append("\n");
        itemsInLine++;
        if (itemsInLine == 4) {
            itemsInLine = 0;
            builder.append("\n");
        }
    }
    builder.append("\nPC: " + Misc.toHexString(cpu.getPC().getValue()));
    builder.append(" (elapsed cycles: " + cpu.getCurrentCycleCount()).append(")");
    builder.append("\n");

    builder.append("EX: " + Misc.toHexString(cpu.getEX())).append("\n");
    builder.append("IA: " + Misc.toHexString(cpu.getInterruptAddress())).append("\n");

    builder.append("IQ: Interrupt queueing is ");
    if (cpu.isQueueInterrupts()) {
        int start = builder.length();
        builder.append("ON");
        redRegions.add(new TextRegion(start, builder.length() - start));
    } else {
        builder.append("OFF");
    }
    builder.append("\n");
    builder.append("IRQs: " + StringUtils.join(cpu.getInterruptQueue(), ",")).append("\n");
    builder.append("SP: " + Misc.toHexString(cpu.getSP().getValue())).append("\n");

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            final StyledDocument doc = textArea.getStyledDocument();
            doc.putProperty(Document.StreamDescriptionProperty, null);

            textArea.setText(builder.toString());
            for (ITextRegion region : redRegions) {
                doc.setCharacterAttributes(region.getStartingOffset(), region.getLength(), errorStyle, true);
            }
        }
    });
}

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

@Override
protected void doGet(final HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    log.info("MIGRATE BACKEND");
    final String requestorEmail = getRequestorEmail(req);
    final String migrationJobName = HttpUtil.getParam(req, "migrationName");
    final String useTaskQueue = HttpUtil.getParam(req, "queue");
    final String cursor = HttpUtil.getParam(req, "cursor");
    final String sTime = HttpUtil.getParam(req, "startTime");
    final String eTime = HttpUtil.getParam(req, "endTime");

    final String jobId = migrationJobName + "_"
            + 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// w w w.j  a  v  a 2 s .  c  om
        public void run() {

            log.info("MigrationBackend running");
            Thread.currentThread().setContextClassLoader(cl);
            try {
                DateTime startTime = null;
                DateTime endTime = null;
                if (sTime != null && eTime != null) {
                    startTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.sssZ").parseDateTime(sTime);
                    endTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.sssZ").parseDateTime(eTime);
                }
                if (doMigration(migrationJobName, cursor, startTime, endTime)) {
                    statusMgr.completeReport(requestorEmail, jobId, Constants.LOCATION_NA);
                } else {
                    statusMgr.failReport(requestorEmail, jobId, "Check server logs for stacktrace");
                }
            } catch (Throwable e) {
                final String fullStack = getStackTraceAsString(e);
                final String string = fullStack.length() > 700 ? fullStack.substring(0, 700) : fullStack;
                statusMgr.failReport(requestorEmail, jobId,
                        e.getClass() + "." + e.getMessage() + "\n" + string);
                log.severe("Could not run migration job: " + e.getMessage());

                log.severe("stacktrace: " + fullStack);
            }
        }
    });
    thread2.start();
    log.info("Leaving migration backend");
    resp.setContentType("text/plain;charset=UTF-8");
    resp.getWriter().println(jobId);
}

From source file:com.jxva.exception.ExceptionUtil.java

/**
 * <p>Checks whether this <code>Throwable</code> class can store a cause.</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//  w  w  w.  j  a va2 s  .  co  m
 */
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<? extends Throwable> cls = throwable.getClass();
    synchronized (CAUSE_METHOD_NAMES) {
        for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
            try {
                Method method = cls.getMethod(CAUSE_METHOD_NAMES[i]);
                if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
                    return true;
                }
            } catch (NoSuchMethodException ignored) {
                // exception ignored
            } catch (SecurityException ignored) {
                // exception ignored
            }
        }
    }

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

    return false;
}

From source file:de.decoit.visa.http.ajax.handlers.IOToolLoadTopoHandler.java

@Override
public void handle(HttpExchange he) throws IOException {
    log.info(he.getRequestURI().toString());

    // Get the URI of the request and extract the query string from it
    QueryString queryParameters = new QueryString(he.getRequestURI());

    // Create String for the response
    String response = null;/*from   w w w  .j a va2  s .  c o  m*/

    // Check if the query parameters are valid for this handler
    if (this.checkQueryParameters(queryParameters)) {
        // Any exception thrown during object creation will
        // cause failure of the AJAX request
        try {
            // Execute the request to the IO-Tool
            IOToolRequestStatus status = TEBackend.getIOConnector()
                    .requestTopology(queryParameters.get("id").get());

            JSONObject rv = new JSONObject();
            if (status == IOToolRequestStatus.SUCCESS) {
                Map<String, String> data = TEBackend.getIOConnector().getLastReturnData();

                // Wrap the RDF/XML information into an InputStream
                ByteArrayInputStream bais = new ByteArrayInputStream(
                        data.get(queryParameters.get("id").get()).getBytes());

                // Read that InputStream into the RDFManager
                TEBackend.RDF_MANAGER.loadRDF(bais, true, queryParameters.get("id").get());

                TEBackend.TOPOLOGY_STORAGE.setTopologyID(queryParameters.get("id").get());

                rv.put("status", AJAXServer.AJAX_SUCCESS);
                rv.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON());
            } else if (status == IOToolRequestStatus.IOTOOL_BUSY) {
                rv.put("status", AJAXServer.AJAX_ERROR_IOTOOL_BUSY);
            } else {
                rv.put("status", AJAXServer.AJAX_ERROR_GENERAL);
            }

            rv.put("returncode", TEBackend.getIOConnector().getLastReturnCode());
            rv.put("message", TEBackend.getIOConnector().getLastReturnMsg());
            response = rv.toString();
        } catch (Throwable ex) {
            TEBackend.logException(ex, log);

            JSONObject rv = new JSONObject();
            try {
                rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION);
                rv.put("type", ex.getClass().getSimpleName());
                rv.put("message", ex.getMessage());
                rv.put("topology", TEBackend.TOPOLOGY_STORAGE.genTopologyJSON());
            } catch (JSONException exc) {
                /* Ignore */
            }

            response = rv.toString();
        }
    } else {
        JSONObject rv = new JSONObject();
        try {
            // Missing or malformed query string, set response to error code
            rv.put("status", AJAXServer.AJAX_ERROR_MISSING_ARGS);
        } catch (JSONException exc) {
            /* Ignore */
        }

        response = rv.toString();
    }

    // Send the response
    sendResponse(he, response);
}

From source file:com.graphhopper.http.GraphHopperServlet.java

private void writeJson(HttpServletRequest req, HttpServletResponse res, GHResponse rsp, float took)
        throws JSONException, IOException {
    boolean enableInstructions = getBooleanParam(req, "instructions", true);
    boolean pointsEncoded = getBooleanParam(req, "points_encoded", true);
    boolean calcPoints = getBooleanParam(req, "calc_points", true);
    boolean includeElevation = getBooleanParam(req, "elevation", false);
    JSONObject json = new JSONObject();
    JSONObject jsonInfo = new JSONObject();
    json.put("info", jsonInfo);

    if (rsp.hasErrors()) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (Throwable t : rsp.getErrors()) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("message", t.getMessage());
            map.put("details", t.getClass().getName());
            list.add(map);/*from   w  w w .j av a2s  .c om*/
        }
        jsonInfo.put("errors", list);
    } else if (!rsp.isFound()) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("message", "Not found");
        map.put("details", "");
        jsonInfo.put("errors", Collections.singletonList(map));
    } else {
        jsonInfo.put("took", Math.round(took * 1000));
        JSONObject jsonPath = new JSONObject();
        jsonPath.put("distance", Helper.round(rsp.getDistance(), 3));
        jsonPath.put("time", rsp.getMillis());

        if (calcPoints) {
            jsonPath.put("points_encoded", pointsEncoded);

            PointList points = rsp.getPoints();
            if (points.getSize() >= 2)
                jsonPath.put("bbox", rsp.calcRouteBBox(hopper.getGraph().getBounds()).toGeoJson());

            jsonPath.put("points", createPoints(points, pointsEncoded, includeElevation));

            if (enableInstructions) {
                InstructionList instructions = rsp.getInstructions();
                jsonPath.put("instructions", instructions.createJson());
            }
        }
        json.put("paths", Collections.singletonList(jsonPath));
    }

    writeJson(req, res, json);
}

From source file:io.dyn.core.EventedBase.java

@SuppressWarnings({ "unchecked" })
@Override//  www. ja  v a  2  s. c o m
public E handler(Object handler) {
    if (null != handler) {
        if (handler instanceof Collection) {
            for (Object o : (Collection) handler) {
                handler(o);
            }
        } else if (handler instanceof Map) {
            for (Map.Entry<String, Object> entry : ((Map<String, Object>) handler).entrySet()) {
                on(entry.getKey(), entry.getValue());
            }
        } else if (handler instanceof Class) {
            try {
                Object o = ((Class<?>) handler).newInstance();
                if (null != beanFactory) {
                    beanFactory.autowireBean(o);
                }
                handler(o);
            } catch (Throwable t) {
                event(Events.classToEventExpression(t.getClass()), t);
            }
        } else {
            Class<?> targetClass;

            if (AopUtils.isAopProxy(handler)) {
                targetClass = AopUtils.getTargetClass(handler);
            } else {
                targetClass = handler.getClass();
            }

            Map<Object, HandlerMethod> handlers = handlerMethodResolver.resolve(targetClass);
            for (Map.Entry<Object, HandlerMethod> entry : handlers.entrySet()) {
                final Object key = entry.getKey();
                final HandlerMethod hm = entry.getValue();
                registerHandlerMethod(key, hm, handler);
            }
        }
    }
    return (E) this;
}

From source file:com.atinternet.tracker.CrashDetectionHandler.java

@Override
public void uncaughtException(Thread thread, Throwable throwable) {
    String className = (throwable.getCause() != null) ? getClassNameException(throwable.getCause())
            : getClassNameException(throwable);
    String exceptionName = (throwable.getCause() != null) ? throwable.getCause().getClass().getName()
            : throwable.getClass().getName();

    preferences.edit().putBoolean(CRASH_DETECTION, true)
            .putString(CRASH_LAST_SCREEN, lastScreen != null ? lastScreen : "")
            .putString(CRASH_CLASS_CAUSE, className)
            .putString(CRASH_EXCEPTION_NAME, exceptionName != null ? exceptionName : "").apply();
    defaultHandler.uncaughtException(thread, throwable);
}

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

@DomainStep("the OSGP should send an event notification response")
public boolean thenTheOSGPShouldSendAnEventNotificationResponse() {
    LOGGER.info("THEN: the OSGP should send an event notification response");

    try {//w  w w .  j  a  v a 2  s.c  om
        verify(this.eventRepositoryMock, times(1)).findAll(this.actualSpecifications.capture(),
                this.actualPageRequest.capture());
    } catch (final Throwable t) {
        LOGGER.error("Exception [{}]: {}", t.getClass().getSimpleName(), t.getMessage());
        return false;
    }

    // Expect the response to be returned.
    return this.response != null;
}

From source file:org.opennms.netmgt.poller.monitors.PageSequenceMonitorIT.java

@Test
@Ignore("EBay tests stopped working, we REALLY need to make our own repeatable version of this test")
public void testHttpsWithHostValidation() throws Exception {
    m_params.put("page-sequence", "" + "<?xml version=\"1.0\"?>" + "<page-sequence>\n"
            + "  <page scheme=\"https\" path=\"/ws/eBayISAPI.dll\" query=\"RegisterEnterInfo\" port=\"443\" user-agent=\"Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)\" successMatch=\"ebaystatic.com/\" virtual-host=\"scgi.ebay.com\" disable-ssl-verification=\"false\"/>\n"
            + "</page-sequence>\n");

    try {/* w w w. j  a  va 2 s . c  o  m*/
        m_monitor.poll(getHttpService("scgi.ebay.com"), m_params);
        fail("Expected SSL host mismatch error");
    } catch (Throwable e) {
        assertTrue("Wrong exception caught: " + e.getClass().getName(), e instanceof AssertionError);
    }
}