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:de.decoit.visa.http.ajax.handlers.IOToolReplicateHandler.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 www . j av  a2 s .co  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()
                    .replicateTopology(queryParameters.get("id").get());

            JSONObject rv = new JSONObject();
            if (status == IOToolRequestStatus.SUCCESS) {
                rv.put("status", AJAXServer.AJAX_SUCCESS);
            } else if (status == IOToolRequestStatus.WAIT) {
                rv.put("status", AJAXServer.AJAX_IOTOOL_WAIT);
            } 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());
            } 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.serli.chell.framework.exception.handler.ExceptionHandler.java

protected String renderError(Throwable exception, Throwable cause, PhaseType phase) {
    if (LOGGER.isErrorEnabled()) {
        String portletName = PortletHelper.getPortletContext().getPortletContextName();
        LOGGER.error("Portlet " + portletName + " throws exception during phase " + phase + ":", exception);
    }//from  w  w w .j av a 2  s. co  m
    String message = MessageBundle.getMessageFormatted(MessageKey.MESSAGE_EXCEPTION, cause.getClass().getName(),
            cause.getMessage());
    return MessageType.ERROR.buildMessage(message);
}

From source file:fr.duminy.jbackup.swing.ProgressPanel.java

@Override
public void taskFinished(String configurationName, Throwable error) {
    progressBar.setIndeterminate(false);
    if (error == null) {
        progressBar.setString("Finished");
    } else {//from  w  ww . j a v a  2 s  . com
        String errorMessage = error.getMessage();
        if (errorMessage == null) {
            errorMessage = error.getClass().getSimpleName();
        }
        progressBar.setString("Error : " + errorMessage);
    }
    if (cancelButton != null) {
        remove(cancelButton);
        revalidate();
    }
    removeFromParent();
    finished = true;
}

From source file:com.bstek.dorado.view.task.LongTaskThread.java

public ExceptionInfo(Exception e) {
    Throwable throwable = e;
    // while (throwable.getCause() != null) {
    // throwable = throwable.getCause();
    // }/*from w  w  w  . j a  va  2 s  .c  o  m*/

    message = throwable.getMessage();
    if (message == null) {
        message = throwable.getClass().getSimpleName();
    }

    StackTraceElement[] stackTraceElements = throwable.getStackTrace();
    stackTrace = new String[stackTraceElements.length];
    int i = 0;
    for (StackTraceElement stackTraceElement : stackTraceElements) {
        stackTrace[i] = stackTraceElement.getClassName() + '.' + stackTraceElement.getMethodName() + '('
                + stackTraceElement.getFileName() + ':' + stackTraceElement.getLineNumber() + ')';
        i++;
    }
}

From source file:com.googlecode.struts2gwtplugin.interceptor.GWTServlet.java

public String processCall(String payload) throws SerializationException {

    // default return value - Should this be something else?
    // no known constants to use in this case
    String result = null;//from  w ww  .  ja  va 2  s. c o m

    // get the RPC Request from the request data
    //RPCRequest rpcRequest= RPC.decodeRequest(payload);
    RPCRequest rpcRequest = RPC.decodeRequest(payload, null, this);

    onAfterRequestDeserialized(rpcRequest);

    // get the parameter types for the method look-up
    Class<?>[] paramTypes = rpcRequest.getMethod().getParameterTypes();
    paramTypes = rpcRequest.getMethod().getParameterTypes();

    // we need to get the action method from Struts
    Method method = findInterfaceMethod(actionInvocation.getAction().getClass(),
            rpcRequest.getMethod().getName(), paramTypes, true);

    // if the method is null, this may be a hack attempt
    // or we have some other big problem
    if (method == null) {
        // present the params
        StringBuffer params = new StringBuffer();
        for (int i = 0; i < paramTypes.length; i++) {
            params.append(paramTypes[i]);
            if (i < paramTypes.length - 1) {
                params.append(", ");
            }
        }

        // throw a security exception, could be attempted hack
        throw new GWTServletException("Failed to locate method " + rpcRequest.getMethod().getName() + "("
                + params + ") on interface " + actionInvocation.getAction().getClass().getName()
                + " requested through interface " + rpcRequest.getClass().getName());
    }

    Object callResult = null;
    try {
        callResult = method.invoke(actionInvocation.getAction(), rpcRequest.getParameters());
        // package  up response for GWT
        result = RPC.encodeResponseForSuccess(method, callResult);

    } catch (Exception e) {
        // check for checked exceptions
        if (e.getCause() != null) {
            log.error("Struts2GWT exception", e.getCause());
            Throwable cause = e.getCause();
            boolean found = false;
            for (Class<?> checkedException : rpcRequest.getMethod().getExceptionTypes()) {
                if (cause.getClass().equals(checkedException)) {
                    found = true;
                    break;
                }
            }
            if (!found) {

                throw new Struts2GWTBridgeException("Unhandled exception!", cause);
            }
            result = RPC.encodeResponseForFailure(null, e.getCause(), rpcRequest.getSerializationPolicy());
        } else {
            throw new Struts2GWTBridgeException("Unable to serialize the exception.", e);
        }
    }

    // return our response
    return result;
}

From source file:com.haulmont.cuba.core.global.RemoteException.java

/**
 * @return First exception in the causes list if it is checked or it is supported by client, null otherwise
 *//* w  w  w  . ja  v  a  2s  .com*/
@Nullable
@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
public Exception getFirstCauseException() {
    if (!causes.isEmpty()) {
        Throwable t = causes.get(0).getThrowable();
        if (t != null) {
            if (!(t instanceof RuntimeException) && !(t instanceof Error)) {
                return (Exception) t;
            }
            if (!(t instanceof Error) && t.getClass().getAnnotation(SupportedByClient.class) != null)
                return (Exception) t;
        }
    }
    return null;
}

From source file:ch.entwine.weblounge.preview.jai.JAIPreviewGenerator.java

/**
 * Resizes the given image to what is defined by the image style and writes
 * the result to the output stream.// w  w w .ja v  a  2  s. co m
 * 
 * @param is
 *          the input stream
 * @param os
 *          the output stream
 * @param format
 *          the image format
 * @param style
 *          the style
 * @throws IllegalArgumentException
 *           if the image is in an unsupported format
 * @throws IllegalArgumentException
 *           if the input stream is empty
 * @throws IOException
 *           if reading from or writing to the stream fails
 * @throws OutOfMemoryError
 *           if the image is too large to be processed in memory
 */
private void style(InputStream is, OutputStream os, String format, ImageStyle style)
        throws IllegalArgumentException, IOException, OutOfMemoryError {

    // Does the input stream contain any data?
    if (is.available() == 0)
        throw new IllegalArgumentException("Empty input stream was passed to image styling");

    // Do we need to do any work at all?
    if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) {
        logger.trace("No scaling needed, performing a noop stream copy");
        IOUtils.copy(is, os);
        return;
    }

    SeekableStream seekableInputStream = null;
    RenderedOp image = null;
    try {
        // Load the image from the given input stream
        seekableInputStream = new FileCacheSeekableStream(is);
        image = JAI.create("stream", seekableInputStream);
        if (image == null)
            throw new IOException("Error reading image from input stream");

        // Get the original image size
        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();

        // Resizing
        float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style);

        RenderingHints scaleHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        scaleHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        scaleHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        scaleHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        int scaledWidth = Math.round(scale * image.getWidth());
        int scaledHeight = Math.round(scale * image.getHeight());
        int cropX = 0;
        int cropY = 0;

        // If either one of scaledWidth or scaledHeight is < 1.0, then
        // the scale needs to be adapted to scale to 1.0 exactly and accomplish
        // the rest by cropping.

        if (scaledWidth < 1.0f) {
            scale = 1.0f / imageWidth;
            scaledWidth = 1;
            cropY = imageHeight - scaledHeight;
            scaledHeight = Math.round(imageHeight * scale);
        } else if (scaledHeight < 1.0f) {
            scale = 1.0f / imageHeight;
            scaledHeight = 1;
            cropX = imageWidth - scaledWidth;
            scaledWidth = Math.round(imageWidth * scale);
        }

        if (scale > 1.0) {
            ParameterBlock scaleParams = new ParameterBlock();
            scaleParams.addSource(image);
            scaleParams.add(scale).add(scale).add(0.0f).add(0.0f);
            scaleParams.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2));
            image = JAI.create("scale", scaleParams, scaleHints);
        } else if (scale < 1.0) {
            ParameterBlock subsampleAverageParams = new ParameterBlock();
            subsampleAverageParams.addSource(image);
            subsampleAverageParams.add(Double.valueOf(scale));
            subsampleAverageParams.add(Double.valueOf(scale));
            image = JAI.create("subsampleaverage", subsampleAverageParams, scaleHints);
        }

        // Cropping
        cropX = (int) Math.max(cropX,
                (float) Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style)));
        cropY = (int) Math.max(cropY,
                (float) Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style)));

        if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) {

            ParameterBlock cropTopLeftParams = new ParameterBlock();
            cropTopLeftParams.addSource(image);
            cropTopLeftParams.add(cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f);
            cropTopLeftParams.add(cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f);
            cropTopLeftParams.add(scaledWidth - Math.max(cropX, 0.0f)); // width
            cropTopLeftParams.add(scaledHeight - Math.max(cropY, 0.0f)); // height

            RenderingHints croppingHints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                    BorderExtender.createInstance(BorderExtender.BORDER_COPY));

            image = JAI.create("crop", cropTopLeftParams, croppingHints);
        }

        // Write resized/cropped image encoded as JPEG to the output stream
        ParameterBlock encodeParams = new ParameterBlock();
        encodeParams.addSource(image);
        encodeParams.add(os);
        encodeParams.add("jpeg");
        JAI.create("encode", encodeParams);

    } catch (Throwable t) {
        if (t.getClass().getName().contains("ImageFormat")) {
            throw new IllegalArgumentException(t.getMessage());
        }
    } finally {
        IOUtils.closeQuietly(seekableInputStream);
        if (image != null)
            image.dispose();
    }
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.uplink.UplinkReceiver.java

/**
 * Run the relay server./*w  w  w.j  a  va2s  .co m*/
 */
@Override
public void run() {
    initRelayServers();
    RelayServer me = this.relayServers.getMe();

    this.databaseLoggerTimer.init();
    this.expireNodesTimer.init();

    byte[] receiveBuffer = new byte[BUFFERSIZE];
    DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);

    while (this.run.get()) {
        try {
            this.sock.receive(packet);
            try {
                if (this.packetHandler.processPacket(me, packet)) {
                    this.relayClusterSender.addPacket(me, packet);
                    this.distributor.signalUpdate();
                    this.databaseLogger.log(this.logger, Level.DEBUG);
                }
            } catch (Throwable e) {
                this.logger.error(e);
            }
        } catch (Exception e) {
            if (!SocketException.class.equals(e.getClass())) {
                e.printStackTrace();
            }
        }
    }

    if (this.sock != null) {
        this.sock.close();
        this.sock = null;
    }
}