Example usage for java.lang Throwable toString

List of usage examples for java.lang Throwable toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:de.axelfaust.alfresco.nashorn.repo.web.scripts.console.ExecutePost.java

protected void collectCallstackLines(final Throwable exception, final List<String> callstackLines) {
    if (exception.getCause() != null) {
        this.collectCallstackLines(exception.getCause(), callstackLines);

        callstackLines.add("Wrapped in " + exception.toString());
        callstackLines.add(CALLSTACK_AT_PREFIX + exception.getStackTrace()[0].toString());
    } else {//from  w w  w  .ja  v  a 2  s.c o  m
        callstackLines.add(exception.toString());
        for (final StackTraceElement element : exception.getStackTrace()) {
            callstackLines.add(CALLSTACK_AT_PREFIX + element.toString());
        }
    }
}

From source file:com.aipo.container.protocol.AipoDataServiceServlet.java

/**
 * Handler for non-batch requests./*from  w  ww . ja  v a2 s.c  o  m*/
 */
protected void handleSingleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        SecurityToken token) throws IOException {

    // Always returns a non-null handler.
    RestHandler handler = getRestHandler(servletRequest);

    // Get Content-Type
    String contentType = null;

    try {
        // TODO: First implementation causes bug when Content-Type is
        // application/atom+xml. Fix is applied.
        contentType = ContentTypes.extractMimePart(servletRequest.getContentType());
    } catch (Throwable t) {
        // this happens while testing
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Unexpected error : content type is null " + t.toString());
        }
    }

    // Get BeanConverter for Request payload.
    BeanConverter requestConverter = getConverterForRequest(contentType, null);

    // Get BeanConverter for Response body.
    BeanConverter responseConverter = getConverterForFormat(null);

    // Execute the request
    Map<String, FormDataItem> formItems = Maps.newHashMap();
    Map<String, String[]> parameterMap = loadParameters(servletRequest, formItems);
    Future<?> future = handler.execute(parameterMap, formItems, token, requestConverter);
    ResponseItem responseItem = getResponseItem(future);

    servletResponse.setContentType(responseConverter.getContentType());

    if (responseItem.getErrorCode() >= 200 && responseItem.getErrorCode() < 400) {
        Object response = responseItem.getResponse();

        if (response instanceof StreamContent) {
            InputStream is = null;
            OutputStream out = null;
            try {
                StreamContent content = (StreamContent) response;
                servletResponse.setContentType(content.getContentType());
                if (content.getContentLength() != 0) {
                    servletResponse.setContentLength(content.getContentLength());
                }
                is = content.getInputStream();
                out = servletResponse.getOutputStream();
                int b;
                while ((b = is.read()) != -1) {
                    out.write(b);
                }
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ignore) {
                    // ignore
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException ignore) {
                    // ignore
                }
            }
            return;
        }

        // TODO: ugliness resulting from not using RestfulItem
        if (!(response instanceof DataCollection) && !(response instanceof RestfulCollection)) {
            response = ImmutableMap.of("entry", response);
        }

        // JSONP style callbacks
        String callback = (HttpUtil.isJSONP(servletRequest)
                && ContentTypes.OUTPUT_JSON_CONTENT_TYPE.equals(responseConverter.getContentType()))
                        ? servletRequest.getParameter("callback")
                        : null;

        PrintWriter writer = servletResponse.getWriter();
        if (callback != null) {
            writer.write(callback + '(');
        }
        writer.write(responseConverter.convertToString(response));
        if (callback != null) {
            writer.write(");\n");
        }
    } else {
        sendError(servletResponse, responseItem);
    }
}

From source file:com.sketchy.image.ImageProcessingThread.java

public void run() {
    status = Status.RENDERING;//from ww  w .java 2 s .co  m

    try {
        progress = 5;

        DrawingSize drawingSize = DrawingSize.parse(renderedImageAttributes.getDrawingSize());

        double dotsPerMM = 1 / renderedImageAttributes.getPenWidth();

        statusMessage = "Loading Image";
        progress = 10;

        File sourceImage = HttpServer
                .getUploadFile(ImageAttributes.getImageFilename(renderedImageAttributes.getSourceImageName()));
        BufferedImage bufferedImage = ImageIO.read(sourceImage);

        if (cancel) {
            throw new CancelledException();
        }

        progress = 25;

        if ((renderedImageAttributes.getBrightness() != 50) || (renderedImageAttributes.getContrast() != 50)) {
            statusMessage = "Adjusting Contrast/Brightness";
            MarvinImage image = new MarvinImage(bufferedImage);
            MarvinImagePlugin plugin = MarvinPluginLoader
                    .loadImagePlugin("org.marvinproject.image.color.brightnessAndContrast.jar");
            if (plugin == null) {
                throw new Exception("Error loading Marvin Brightness Plugin!");
            }
            // Range is -127 to 127.. convert from 0 - 100
            int brightnessValue = (int) (renderedImageAttributes.getBrightness() * 2.54) - 127;
            int contrastValue = (int) (renderedImageAttributes.getContrast() * 2.54) - 127;
            plugin.setAttribute("brightness", brightnessValue);
            plugin.setAttribute("contrast", contrastValue);
            plugin.process(image, image, null, MarvinImageMask.NULL_MASK, false);
            image.update();
            bufferedImage = image.getBufferedImage();
        }

        if (cancel) {
            throw new CancelledException();
        }

        progress = 30;
        if ((renderedImageAttributes.isInvertImage())) {
            statusMessage = "Inverting Image";
            MarvinImage image = new MarvinImage(bufferedImage);
            MarvinImagePlugin plugin = MarvinPluginLoader
                    .loadImagePlugin("org.marvinproject.image.color.invert.jar");
            if (plugin == null) {
                throw new Exception("Error loading Marvin Invert Image Plugin!");
            }
            plugin.process(image, image, null, MarvinImageMask.NULL_MASK, false);
            image.update();
            bufferedImage = image.getBufferedImage();
        }

        if (cancel) {
            throw new CancelledException();
        }

        progress = 35;
        if (renderedImageAttributes.getRotateOption() != RotateOption.ROTATE_NONE) {
            statusMessage = "Rotating Image";
            bufferedImage = rotateImage(bufferedImage, renderedImageAttributes.getRotateOption());
        }

        if (cancel) {
            throw new CancelledException();
        }

        progress = 40;
        if (renderedImageAttributes.getFlipOption() != FlipOption.FLIP_NONE) {
            statusMessage = "Flipping Image";
            bufferedImage = flipImage(bufferedImage, renderedImageAttributes.getFlipOption());
        }

        if (cancel) {
            throw new CancelledException();
        }

        progress = 50;
        if (renderedImageAttributes.getRenderOption() == RenderOption.RENDER_EDGE_DETECTION) {
            statusMessage = "Processing Edge Detection";
            MarvinImage image = new MarvinImage(bufferedImage);
            MarvinImagePlugin plugin = MarvinPluginLoader
                    .loadImagePlugin("org.marvinproject.image.edge.edgeDetector.jar");
            if (plugin == null) {
                throw new Exception("Error loading Marvin EdgeDetector Plugin!");
            }
            plugin.process(image, image, null, MarvinImageMask.NULL_MASK, false);
            image.update();
            bufferedImage = image.getBufferedImage();
        }

        int drawingWidth = (int) Math.ceil(drawingSize.getWidth() * dotsPerMM);
        int drawingHeight = (int) Math.ceil(drawingSize.getHeight() * dotsPerMM);

        if (cancel) {
            throw new CancelledException();
        }

        progress = 55;
        statusMessage = "Scaling Image";
        bufferedImage = resizeImage(bufferedImage, drawingWidth, drawingHeight,
                renderedImageAttributes.getCenterOption(), renderedImageAttributes.getScaleOption());

        if (cancel) {
            throw new CancelledException();
        }

        progress = 60;
        if (renderedImageAttributes.getRenderOption() == RenderOption.RENDER_HALFTONE) {
            statusMessage = "Processing Halftone";
            MarvinImage image = new MarvinImage(bufferedImage);
            MarvinImagePlugin plugin = MarvinPluginLoader
                    .loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion.jar");
            if (plugin == null) {
                throw new Exception("Error loading Marvin Halftone Plugin!");
            }
            plugin.process(image, image, null, MarvinImageMask.NULL_MASK, false);
            image.update();
            bufferedImage = image.getBufferedImage();
        }

        if (cancel) {
            throw new CancelledException();
        }

        progress = 65;
        if ((renderedImageAttributes.getThreshold() != 50)
                && (renderedImageAttributes.getRenderOption() != RenderOption.RENDER_HALFTONE)) {
            statusMessage = "Processing Threshold";
            MarvinImage image = new MarvinImage(bufferedImage);
            MarvinImagePlugin plugin = MarvinPluginLoader
                    .loadImagePlugin("org.marvinproject.image.color.thresholding.jar");
            if (plugin == null) {
                throw new Exception("Error loading Marvin Threshold Plugin!");
            }
            // Range is 0 to 256.. convert from 0 - 100
            int thresholdValue = (256 - (int) (renderedImageAttributes.getThreshold() * 2.56));
            plugin.setAttribute("threshold", thresholdValue);
            plugin.process(image, image, null, MarvinImageMask.NULL_MASK, false);
            image.update();
            bufferedImage = image.getBufferedImage();
        }

        if (cancel) {
            throw new CancelledException();
        }
        statusMessage = "Saving Rendered Image";

        File renderedFile = HttpServer.getUploadFile(renderedImageAttributes.getImageFilename());

        renderedImageAttributes.setWidth(bufferedImage.getWidth());
        renderedImageAttributes.setHeight(bufferedImage.getHeight());

        progress = 70;
        SketchyImage sketchyImage = new SketchyImage(bufferedImage, dotsPerMM, dotsPerMM);

        if (cancel) {
            throw new CancelledException();
        }

        progress = 80;
        SketchyImage.save(sketchyImage, renderedFile);

        File renderedDataFile = HttpServer.getUploadFile(renderedImageAttributes.getDataFilename());
        FileUtils.writeStringToFile(renderedDataFile, renderedImageAttributes.toJson());
        progress = 100;

        status = Status.COMPLETED;
        statusMessage = "Complete";
    } catch (CancelledException e) {
        status = Status.CANCELLED;
        statusMessage = "Cancelled!";
    } catch (Throwable t) {
        status = Status.ERROR;
        statusMessage = "Exception occured while processing Image!! " + t.getMessage();
        throw new RuntimeException("Error Running ImageProcessingThread!  " + t.toString());
    }
}

From source file:org.eweb4j.spiderman.plugin.util.PageFetcherImpl.java

/**
 * ?url//from  www.  j a v a  2s  . c  om
 * @date 2013-1-7 ?11:08:54
 * @param toFetchURL
 * @return
 */
public FetchResult fetch(FetchRequest req) throws Exception {
    if (req.getHttpMethod() != null && !Http.Method.GET.equals(req.getHttpMethod())) {
        //?URL??QueryParam
        String query = new URL(req.getUrl()).getQuery();
        for (String q : query.split("\\&")) {
            String[] qv = q.split("=");
            String name = qv[0];
            String val = qv[1];
            List<Object> vals = req.getParams().get(name);
            if (vals == null) {
                vals = new ArrayList<Object>();
                req.getParams().put(name, vals);
            }

            vals.add(val);
        }

        return request(req);
    }
    FetchResult fetchResult = new FetchResult();
    HttpGet get = null;
    HttpEntity entity = null;
    String toFetchURL = req.getUrl();
    try {
        get = new HttpGet(toFetchURL);
        //GZIP???GZIP?
        get.addHeader("Accept-Encoding", "gzip");
        for (Iterator<Entry<String, String>> it = headers.entrySet().iterator(); it.hasNext();) {
            Entry<String, String> entry = it.next();
            get.addHeader(entry.getKey(), entry.getValue());
        }

        //???,??
        // TODO ?delay?
        synchronized (mutex) {
            //??
            long now = (new Date()).getTime();
            //?Host??
            if (now - lastFetchTime < config.getPolitenessDelay())
                Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime));
            //????HOST??URL
            lastFetchTime = (new Date()).getTime();
        }

        //get?
        Header[] headers = get.getAllHeaders();
        for (Header h : headers) {
            Map<String, List<String>> hs = req.getHeaders();
            String key = h.getName();
            List<String> val = hs.get(key);
            if (val == null)
                val = new ArrayList<String>();
            val.add(h.getValue());

            hs.put(key, val);
        }

        req.getCookies().putAll(this.cookies);

        fetchResult.setReq(req);
        //get??
        HttpResponse response = httpClient.execute(get);
        headers = response.getAllHeaders();
        for (Header h : headers) {
            Map<String, List<String>> hs = fetchResult.getHeaders();
            String key = h.getName();
            List<String> val = hs.get(key);
            if (val == null)
                val = new ArrayList<String>();
            val.add(h.getValue());

            hs.put(key, val);
        }
        //URL
        fetchResult.setFetchedUrl(toFetchURL);
        String uri = get.getURI().toString();
        if (!uri.equals(toFetchURL))
            if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL))
                fetchResult.setFetchedUrl(uri);

        entity = response.getEntity();
        //???
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode != HttpStatus.SC_NOT_FOUND) {
                Header locationHeader = response.getFirstHeader("Location");
                //301?302?URL??
                if (locationHeader != null && (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY))
                    fetchResult.setMovedToUrl(
                            URLCanonicalizer.getCanonicalURL(locationHeader.getValue(), toFetchURL));
            }
            //???OKURLstatusCode??
            //???
            if (this.site.getSkipStatusCode() != null && this.site.getSkipStatusCode().trim().length() > 0) {
                String[] scs = this.site.getSkipStatusCode().split(",");
                for (String code : scs) {
                    int c = CommonUtil.toInt(code);
                    //????entity
                    if (statusCode == c) {
                        assemPage(fetchResult, entity);
                        break;
                    }
                }
            }
            fetchResult.setStatusCode(statusCode);
            return fetchResult;
        }

        //??
        if (entity != null) {
            fetchResult.setStatusCode(statusCode);
            assemPage(fetchResult, entity);
            return fetchResult;
        }
    } catch (Throwable e) {
        fetchResult.setFetchedUrl(e.toString());
        fetchResult.setStatusCode(Status.INTERNAL_SERVER_ERROR.ordinal());
        return fetchResult;
    } finally {
        try {
            if (entity == null && get != null)
                get.abort();
        } catch (Exception e) {
            throw e;
        }
    }

    fetchResult.setStatusCode(Status.UNSPECIFIED_ERROR.ordinal());
    return fetchResult;
}

From source file:com.mirth.connect.client.ui.SettingsPanelResources.java

public void refresh() {
    try {// w  w  w  .  j  a va2 s.  c o  m
        updateResourcesTable(getFrame().mirthClient.getResources(), resourceTable.getSelectedRow(), false);
    } catch (Throwable t) {
        getFrame().alertThrowable(getFrame(), t, "Error loading resources: " + t.toString(), false);
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.LabelsPane.java

/**
 * @param throwable//  w  w w.j a  va 2s . c  om
 * @return
 */
protected String getStackTrace(Throwable throwable) {
    String sep = System.getProperty("line.separator");
    StringBuilder result = new StringBuilder();
    result.append(throwable.toString());
    result.append(sep);

    for (StackTraceElement element : throwable.getStackTrace()) {
        result.append(element);
        result.append(sep);
    }
    return result.toString();
}

From source file:com.esri.gpt.catalog.gxe.GxeServlet.java

/**
 * Generates a JSON based error object./*from w  ww.j  ava2s . c  om*/
 * @param request the HTTP servlet request
 * @param response the HTTP servlet response
 * @param context the request context
 * @param msgBroker the message broker
 * @param t the exception
 * @return the JSON string
 */
private String generateJsonError(HttpServletRequest request, HttpServletResponse response,
        RequestContext context, MessageBroker msgBroker, Throwable t) {
    String sMsg = Val.chkStr(t.getMessage());
    if (sMsg.length() == 0)
        sMsg = t.toString();

    // TODO localized messages here
    if (sMsg.contains("Unrecognized metadata schema.")) {
    } else if (sMsg.contains("Unable to parse document.")) {
    } else if (sMsg.contains("Unsupported XML type.")) {
    }

    StringBuilder sb = new StringBuilder();
    sb.append("{\"error\":{");
    sb.append("\"message\": \"").append(Val.escapeStrForJson(sMsg)).append("\"");
    sb.append("}}");
    return sb.toString();
}

From source file:helma.main.Server.java

/**
  * initialize extensions/*  ww  w. j  a  v  a 2 s  . c  o  m*/
  */
private void initExtensions() {
    StringTokenizer tok = new StringTokenizer(sysProps.getProperty("extensions"), ",");
    while (tok.hasMoreTokens()) {
        String extClassName = tok.nextToken().trim();

        try {
            Class extClass = Class.forName(extClassName);
            HelmaExtension ext = (HelmaExtension) extClass.newInstance();
            ext.init(this);
            extensions.add(ext);
            logger.info("Loaded: " + extClassName);
        } catch (Throwable e) {
            logger.error("Error loading extension " + extClassName + ": " + e.toString());
        }
    }
}

From source file:com.softech.tbb.actionform.BaseForm.java

/**
 * Create an object of the specified class, throwing a runtime exception if
 * any error occurs. If an exception is not thrown, then helper is
 * guaranteed to exist./* w  w  w.ja  v  a2s  .  c  om*/
 * 
 * @param objectClass
 *            The name of the class
 * @throws IllegalArgumentException
 *             if object cannot be instantiated
 */
public Object createObject(String objectClass) {

    // Try the create
    Object object = null;
    try {
        object = Class.forName(objectClass).newInstance();
    } catch (Throwable t) {
        object = null;
        // assemble message: {class}: {exception}
        StringBuffer sb = new StringBuffer();
        sb.append(Log.CREATE_OBJECT_ERROR);
        sb.append(Log.CLASS);
        sb.append(objectClass);
        sb.append(Log.SPACE);
        sb.append(Log.ACTION_EXCEPTION);
        sb.append(t.toString());
        // throw runtime exception
        throw new IllegalArgumentException(sb.toString());
    }
    return object;

}

From source file:io.smartspaces.activity.impl.BaseActivity.java

/**
 * Log the activity configuration information to an activity config log file.
 *
 * @param logFile/*from   w w  w.  j a v a 2 s . c  o  m*/
 *          file to write the log into
 */
private void logConfiguration(String logFile) {
    try {
        StringBuilder logBuilder = new StringBuilder();
        getLog().info("Logging activity configuration to " + logFile);
        Configuration configuration = getConfiguration();
        Map<String, String> configMap = configuration.getCollapsedMap();
        TreeMap<String, String> sortedMap = new TreeMap<>(configMap);
        for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
            String value;
            try {
                value = configuration.evaluate(entry.getValue());
            } catch (Throwable e) {
                value = e.toString();
            }
            logBuilder.append(String.format("%s=%s\n", entry.getKey(), value));
        }
        File configLog = new File(getActivityFilesystem().getLogDirectory(), logFile);
        fileSupport.writeFile(configLog, logBuilder.toString());
    } catch (Throwable e) {
        logException("While logging activity configuration", e);
    }
}