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:com.lucidtechnics.blackboard.util.JavascriptingUtil.java

public void loadScript(String _scriptResource) {
    try {//ww  w. j av a  2s. co m
        if (Context.getCurrentContext() == null) {
            throw new RuntimeException(
                    "Cannot use loadScript outside of the scope of a call to executeScript.  A context must be present.");
        }

        try {
            compileScript(_scriptResource).exec(Context.getCurrentContext(), getScope());
        } catch (Throwable t) {
            t.printStackTrace();
            throw new RuntimeException(
                    "Unable to execute script: " + _scriptResource + " for this reason: " + t.toString(), t);
        }
    } catch (Throwable t) {
        t.printStackTrace();
        log.error(t.toString());
        throw new RuntimeException(t);
    }
}

From source file:com.lucidtechnics.blackboard.util.Jsr223ScriptingUtil.java

public Object executeScript(String[] _scriptResources) {
    ScriptContext scriptContext = getScriptEngine().getContext();

    Object result = null;/*from   ww w.j  av a  2s .com*/

    int i = 0;

    try {
        for (String key : getBindingsMap().keySet()) {
            scriptContext.setAttribute(key, getBindingsMap().get(key), ScriptContext.ENGINE_SCOPE);
        }

        for (i = 0; i < _scriptResources.length; i++) {
            CompiledScript script = compileScript(_scriptResources[i]);

            if (script != null) {
                result = script.eval(scriptContext);
            } else {
                result = getScriptEngine().eval(new InputStreamReader(findScript(_scriptResources[i])),
                        scriptContext);
            }
        }
    } catch (Throwable t) {
        throw new RuntimeException(
                "Unable to execute script: " + _scriptResources[i] + " for this reason: " + t.toString(), t);
    }

    return result;
}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.mqtt.MQTTPublisher.java

public void run() {
    try {//from w  w  w .  j av  a  2s.c om
        log.debug("Starting Thread: " + threadName);
        this.publish(topic, qos, message.getBytes());
    } catch (Throwable e) {
        log.error(e.toString());
        e.printStackTrace();
    } finally {
        log.debug("Finishing Thread: " + threadName);
    }
}

From source file:org.sakuli.exceptions.SakuliExceptionHandler.java

/**
 * @return true if the exception have been already processed by Sakuli
 *///  www .  j  av a  2s  .  co m
public boolean isAlreadyProcessed(Throwable e) {
    String message = e.getMessage() != null ? e.getMessage() : e.toString();
    return message.contains(RhinoAspect.ALREADY_PROCESSED) || message.contains(("Logging exception:"))
            || processedExceptions.contains(e);
}

From source file:hudson.plugins.active_directory.docker.TheFlintstonesTest.java

private List<String> captureLogMessages(int size) {
    final List<String> logMessages = new ArrayList<>(size);
    Logger logger = Logger.getLogger("");
    logger.setLevel(Level.ALL);//from ww w . j  a  v a  2s.  c om

    RingBufferLogHandler ringHandler = new RingBufferLogHandler(size) {

        final Formatter f = new SimpleFormatter(); // placeholder instance for what should have been a static method perhaps

        @Override
        public synchronized void publish(LogRecord record) {
            super.publish(record);
            String message = f.formatMessage(record);
            Throwable x = record.getThrown();
            logMessages.add(message == null && x != null ? x.toString() : message);
        }
    };
    logger.addHandler(ringHandler);

    return logMessages;
}

From source file:com.streamsets.datacollector.antennadoctor.engine.AntennaDoctorEngine.java

public AntennaDoctorEngine(AntennaDoctorContext context, List<AntennaDoctorRuleBean> rules) {
    ImmutableList.Builder<RuntimeRule> builder = ImmutableList.builder();

    Map<String, Object> namespaces = new HashMap<>();
    namespaces.put("collection", CollectionEL.class);
    namespaces.put("file", FileEL.class);

    // Main engine used to evaluate all expressions and templates
    engine = new JexlBuilder().cache(512).strict(true).silent(false).debug(true).namespaces(namespaces)
            .create();/* ww w  .  ja  va2 s  .  co  m*/
    templateEngine = engine.createJxltEngine();

    // Context for preconditions
    JexlContext jexlContext = new MapContext();
    jexlContext.set("version", new Version(context.getBuildInfo().getVersion()));
    jexlContext.set("sdc", new SdcJexl(context));

    // Evaluate each rule to see if it's applicable to this runtime (version, stage libs, ...)
    for (AntennaDoctorRuleBean ruleBean : rules) {
        LOG.trace("Loading rule {}", ruleBean.getUuid());

        // We're running in SDC and currently only in STAGE 'mode', other modes will be added later
        if (ruleBean.getEntity() == null || !ruleBean.getEntity().isOneOf(AntennaDoctorRuleBean.Entity.STAGE,
                AntennaDoctorRuleBean.Entity.REST)) {
            continue;
        }

        // Reset the variables that the rule is keeping
        jexlContext.set("context", new HashMap<>());

        for (String precondition : ruleBean.getPreconditions()) {
            try {
                LOG.trace("Evaluating precondition: {}", precondition);
                if (!evaluateCondition(precondition, jexlContext)) {
                    LOG.trace("Precondition {} failed, skipping rule {}", precondition, ruleBean.getUuid());
                    continue;
                }
            } catch (Throwable e) {
                LOG.error("Precondition {} failed, skipping rule {}: {}", precondition, ruleBean.getUuid(),
                        e.toString(), e);
                continue;
            }
        }

        // All checks passed, so we will accept this rule
        builder.add(new RuntimeRule(ruleBean));
    }

    this.rules = builder.build();
    LOG.info("Loaded new Antenna Doctor engine with {} rules", this.rules.size());
}

From source file:fr.openwide.talendalfresco.alfresco.XmlContentImporterResultHandler.java

public void nodeError(String nodeName, NodeRef parentNodeRef, String typeInfo, Throwable t) {
    String namePath = getNamePath(parentNodeRef) + contentImporterBinding.clientPathDelimiter + nodeName;
    String errMsg = (t == null) ? "" : ((t.getMessage() == null) ? t.toString() : t.getMessage());
    logger.trace("error on " + namePath, t);
    try {/*from   w w  w.  ja v  a2  s .  c  o  m*/
        xmlWriter.writeStartElement(RestConstants.RES_IMPORT_ERROR);
        xmlWriter.writeAttribute(RestConstants.RES_IMPORT_NAMEPATH, namePath);
        xmlWriter.writeAttribute(RestConstants.RES_IMPORT_MESSAGE, errMsg);
        xmlWriter.writeAttribute(RestConstants.RES_IMPORT_DATE, dateFormat.format(new Date()));

        // now tracing detailed info :
        if (typeInfo != null) {
            xmlWriter.writeAttribute(RestConstants.RES_IMPORT_DOCTYPE, typeInfo);
        }
        xmlWriter.writeEndElement();
    } catch (XMLStreamException e) {
        logger.error("Unable to write error XML result for " + namePath, e);
    }
}

From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java

/**download methods*/

@Override//w  ww. j av  a 2 s  . c om
protected byte[] downloadFile() {
    this.setRunning(true);
    byte[] result = null;
    InputStream is = null;
    ByteArrayOutputStream bas = null;
    String url = this.getURL();
    PLFileDownloaderListener listener = this.getListener();
    boolean hasListener = (listener != null);
    int responseCode = -1;
    long startTime = System.currentTimeMillis();
    // HttpClient instance
    HttpClient client = new HttpClient();
    // Method instance
    HttpMethod method = new GetMethod(url);
    // Method parameters
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android");
    methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false));
    try {
        // Execute the method
        responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK)
            throw new IOException(method.getStatusText());
        // Get content length
        Header header = method.getRequestHeader("Content-Length");
        long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1);
        if (this.isRunning()) {
            if (hasListener)
                listener.didBeginDownload(url, startTime);
        } else
            throw new PLRequestInvalidatedException(url);
        // Get response body as stream
        is = method.getResponseBodyAsStream();
        bas = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int length = 0, total = 0;
        // Read stream
        while ((length = is.read(buffer)) != -1) {
            if (this.isRunning()) {
                bas.write(buffer, 0, length);
                total += length;
                if (hasListener)
                    listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f));
            } else
                throw new PLRequestInvalidatedException(url);
        }
        if (total == 0)
            throw new IOException("Request data has invalid size (0)");
        // Get data
        if (this.isRunning()) {
            result = bas.toByteArray();
            if (hasListener)
                listener.didEndDownload(url, result, System.currentTimeMillis() - startTime);
        } else
            throw new PLRequestInvalidatedException(url);
    } catch (Throwable e) {
        if (this.isRunning()) {
            PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            if (hasListener)
                listener.didErrorDownload(url, e.toString(), responseCode, result);
        }
    } finally {
        if (bas != null) {
            try {
                bas.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        // Release the connection
        method.releaseConnection();
    }
    this.setRunning(false);
    return result;
}

From source file:byps.BInputJson.java

@Override
public Object load() throws BException {
    if (log.isDebugEnabled())
        log.debug("load(");
    Object root = null;//  w  w w  .  ja  v  a 2 s .c  o  m

    if (log.isDebugEnabled())
        log.debug("header=" + header);
    if (header.messageId == 0) {
        header.read(bbuf.buf);
    }

    Object jsonMessageObj = header.messageObject;
    if (jsonMessageObj == null)
        throw new BException(BExceptionC.CORRUPT, "Missing message data.");
    if (!(jsonMessageObj instanceof BJsonObject))
        throw new BException(BExceptionC.CORRUPT, "Message data must be a JSON object.");
    BJsonObject jsonMessage = (BJsonObject) jsonMessageObj;

    Object headerObj = jsonMessage.get("header");
    if (log.isDebugEnabled())
        log.debug("headerObj=" + headerObj);
    if (headerObj == null)
        throw new BException(BExceptionC.CORRUPT, "Missing message header.");
    if (!(headerObj instanceof BJsonObject))
        throw new BException(BExceptionC.CORRUPT, "Message header must be a JSON object.");

    Object objectTableObj = jsonMessage.get("objectTable");
    if (log.isDebugEnabled())
        log.debug("objectTableObj=" + objectTableObj);
    if (objectTableObj != null) {
        if (!(objectTableObj instanceof BJsonObject))
            throw new BException(BExceptionC.CORRUPT, "Object table must be a JSON object.");
        objectTable = (BJsonObject) objectTableObj;

        Object objNull = objectTable.get(0);
        if (objNull != null)
            throw new BException(BExceptionC.CORRUPT, "First object table element must be null.");

        root = deserializeObject(null, 1, null, 0);
        if (log.isDebugEnabled())
            log.debug("root=" + root);

        if (header.error != 0) {
            Throwable ex = (Throwable) root;
            if (ex instanceof BException)
                throw (BException) ex;
            throw new BException(header.error, ex.toString(), ex);
        }
    }

    if (log.isDebugEnabled())
        log.debug(")load");
    return root;
}

From source file:my.home.lehome.service.SendMsgIntentService.java

private void dispatchCommand(final Intent intent) {
    String cmd = intent.getStringExtra("cmdString");
    String servelURL = intent.getStringExtra("serverUrl");
    String deviceID = intent.getStringExtra("deviceID");
    boolean local = intent.getBooleanExtra("local", false);
    Log.d(TAG, "dispatch cmd:" + cmd + " | servelURL:" + servelURL + " | deviceID:" + deviceID + " | local:"
            + local);/*  w ww .  ja  va  2s.  c  o m*/

    final Context context = getApplicationContext();
    if (local) {
        if (TextUtils.isEmpty(servelURL)) {
            saveAndNotify(intent, CommandRequest.getJsonStringResponse(400,
                    context.getString(R.string.msg_local_saddress_not_set)));
        }
    } else {
        if (TextUtils.isEmpty(deviceID)) {
            saveAndNotify(intent,
                    CommandRequest.getJsonStringResponse(400, context.getString(R.string.msg_no_deviceid)));
        }
        if (TextUtils.isEmpty(servelURL)) {
            saveAndNotify(intent, CommandRequest.getJsonStringResponse(400,
                    context.getString(R.string.msg_saddress_not_set)));
        }
    }
    RequestFuture<String> future = RequestFuture.newFuture();
    CommandRequest request = new CommandRequest(local ? Request.Method.POST : Request.Method.GET, // diff
            servelURL, cmd, future, future);
    mRequestQueue.add(request);
    try {
        String response = future.get(request.getTimeoutMs() + 10000, TimeUnit.MILLISECONDS);
        Log.d(TAG, "get cmd response:" + response);
        saveAndNotify(intent, CommandRequest.getJsonStringResponse(200, response));
    } catch (ExecutionException e) {
        Throwable error = e.getCause();
        Log.d(TAG, "get cmd error:" + error.toString());

        String errorString = context.getString(R.string.error_unknown);
        int errorCode = 400;
        if (error instanceof ServerError) {
            errorString = context.getString(R.string.chat_error_conn);
            errorCode = 400;
        } else if (error instanceof TimeoutError) {
            errorString = context.getString(R.string.chat_error_http_error);
            errorCode = 400;
        } else if (error instanceof ParseError) {
            errorString = context.getString(R.string.chat_error_http_error);
            errorCode = 400;
        } else if (error instanceof NoConnectionError) {
            errorString = context.getString(R.string.chat_error_no_connection_error);
            errorCode = 400;
        }
        saveAndNotify(intent, CommandRequest.getJsonStringResponse(errorCode, errorString));
    } catch (TimeoutException e) {
        saveAndNotify(intent,
                CommandRequest.getJsonStringResponse(400, context.getString(R.string.chat_error_http_error)));
    } catch (Exception e) {
        future.cancel(true);
        e.printStackTrace();
        //            saveAndNotify(intent,
        //                    CommandRequest.getJsonStringResponse(
        //                            400,
        //                            context.getString(R.string.error_internal)
        //                    ));
    }
}