Example usage for java.lang Exception getLocalizedMessage

List of usage examples for java.lang Exception getLocalizedMessage

Introduction

In this page you can find the example usage for java.lang Exception getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:com.clavain.alerts.Methods.java

public static void sendNotifications(Alert alert) {
    Integer aid = alert.getAlert_id();

    try {//from   w  ww . ja v  a  2 s. c  om
        Connection conn = connectToDatabase(com.clavain.muninmxcd.p);
        java.sql.Statement stmt = conn.createStatement();

        // SELECT alert_contacts.id as nid, contacts.* FROM `alert_contacts` LEFT JOIN contacts ON alert_contacts.contact_id = contacts.id WHERE alert_id = 1
        ResultSet rs = stmt.executeQuery(
                "SELECT alert_contacts.id as nid, contacts.*,contacts.id AS contactId FROM `alert_contacts` LEFT JOIN contacts ON alert_contacts.contact_id = contacts.id WHERE alert_id = "
                        + aid);
        while (rs.next()) {
            Integer contact_id = rs.getInt("contactId");
            String dayField = getScheduleFieldToCheck();
            logger.info("[Notifications " + aid + "] Found " + rs.getString("contact_name"));
            if (rs.getString(dayField).equals("disabled")) {
                logger.info("[Notifications " + aid + "] " + rs.getString("contact_name")
                        + " disabled notifications for today - skipping contact");
            } else {
                String splitField = rs.getString(dayField);
                // figure out if this user got notifications enabled or disabled for the current hour and time
                String[] hours = splitField.split(";");
                long a = getStampFromTimeAndZone(hours[0], rs.getString("timezone"));
                long b = getStampFromTimeAndZone(hours[1], rs.getString("timezone"));
                long cur = (System.currentTimeMillis() / 1000L);
                // if in range send notifications
                if (a < cur && b > cur) {
                    String failTime = getHumanReadableDateFromTimeStampWithTimezone(alert.getLast_alert(),
                            rs.getString("timezone"));
                    String title = "ALERT: " + alert.getHostname() + " (" + alert.getPluginName() + ")";
                    String message = "Alert Time: " + failTime + ".   Details: " + alert.getAlertMsg();

                    String json = "";
                    if (rs.getInt("callback_active") == 1) {
                        logger.info("[Notifications " + aid + "] " + rs.getString("contact_name")
                                + " Sending Callback");
                        sendCallback(alert, rs.getString("contact_callback"));
                        updateNotificationLog(aid, contact_id,
                                "Callback executed to " + rs.getString("contact_callback"), "callback");
                    }
                    if (rs.getInt("tts_active") == 1) {
                        title = "This is a MuninMX Alert: Plugin: " + alert.getPluginName() + " on host "
                                + alert.getHostname() + " is in alert state.";
                        logger.info("[Notifications " + aid + "] " + rs.getString("contact_name")
                                + " Initiating TTS Call");
                        sendTTS(title, message, rs.getString("contact_mobile_nr"), rs.getInt("user_id"));
                        updateNotificationLog(aid, contact_id,
                                "Text2Speech Call initiated to " + rs.getString("contact_mobile_nr"), "tts");
                    }
                    if (rs.getInt("email_active") == 1) {
                        logger.info("[Notifications " + aid + "] " + rs.getString("contact_name")
                                + " Sending E-Mail");
                        String ENDL = System.getProperty("line.separator");
                        message = "Alert Time: " + failTime + "." + ENDL + ENDL + "Details:" + ENDL + ENDL
                                + alert.getAlertMsg();

                        sendMail(title, message, rs.getString("contact_email"));
                        updateNotificationLog(aid, contact_id,
                                "E-Mail send to " + rs.getString("contact_email"), "email");
                    }
                    if (rs.getInt("sms_active") == 1) {
                        title = alert.getHostname() + " reports ";
                        message = alert.getAlertMsg();

                        logger.info(
                                "[Notifications " + aid + "] " + rs.getString("contact_name") + " Sending SMS");
                        sendSMS(title, message, rs.getString("contact_mobile_nr"), rs.getInt("user_id"));
                        updateNotificationLog(aid, contact_id,
                                "SMS send to " + rs.getString("contact_mobile_nr"), "sms");
                    }
                    if (rs.getInt("pushover_active") == 1) {
                        logger.info("[Notifications " + aid + "] " + rs.getString("contact_name")
                                + " Sending Pushover Notification");
                        sendPushover(title, message, rs.getString("pushover_key"));
                        updateNotificationLog(aid, contact_id,
                                "PushOver Message send to " + rs.getString("pushover_key"), "pushover");
                    }

                } else {
                    logger.info("[Notifications " + aid + "] " + rs.getString("contact_name")
                            + " disabled notifications for this timerange - skipping contact");
                }
            }
        }
        conn.close();
    } catch (Exception ex) {
        logger.error("Error in sendNotifications for CID " + aid + " : " + ex.getLocalizedMessage());
        ex.printStackTrace();
    }
}

From source file:com.mpower.clientcollection.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString/*from   ww  w .  j  a va2  s .  co  m*/
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);
    //req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                ClientCollection.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                Header contentEncoding = entity.getContentEncoding();
                if (contentEncoding != null
                        && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING)) {
                    is = new GZIPInputStream(is);
                }
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:eu.learnpad.simulator.mon.manager.ResponseDispatcher.java

public static void NotifyMeException(String ruleMatched, String enablerName, Exception exception) {
    ConsumerProfile enablerMatched = (ConsumerProfile) requestMap.get(ruleMatched);

    ComplexEventException exceptionRaised = ComplexEventException.Factory.newInstance();
    if (exception.getCause() == null) {
        exceptionRaised.setCauseClassName("null");
    } else {/*from w  w w .j  a v  a  2s  .c  o  m*/
        exceptionRaised.setCauseClassName(exception.getCause().getClass().getName());
    }
    exceptionRaised.setClassName(exception.getClass().getName());
    exceptionRaised.setLocalizedMessage(exception.getLocalizedMessage());
    exceptionRaised.setMessage(exception.getMessage());
    exceptionRaised.setStackTrace(exception.getStackTrace().toString());

    ResponseDispatcher.sendResponse(exceptionRaised, enablerName, enablerMatched.getAnswerTopic());

    DebugMessages.print(TimeStamp.getCurrentTime(), ResponseDispatcher.class.getSimpleName(),
            "ruleMatched: " + ruleMatched + " - enablerName: " + enablerName + " - evaluationResult: "
                    + exceptionRaised.getClassName());
}

From source file:net.java.sip.communicator.impl.protocol.sip.xcap.BaseHttpXCapClient.java

/**
 * Shows an error and a short description.
 * @param ex the exception/*  w ww  . j  a  va 2 s  . co m*/
 */
static void showError(Exception ex, String title, String message) {
    try {
        if (title == null)
            title = SipActivator.getResources().getI18NString("impl.protocol.sip.XCAP_ERROR_TITLE");

        if (message == null)
            message = title + "\n" + ex.getClass().getName() + ": " + ex.getLocalizedMessage();

        if (SipActivator.getUIService() != null)
            SipActivator.getUIService().getPopupDialog().showMessagePopupDialog(message, title,
                    PopupDialog.ERROR_MESSAGE);
    } catch (Throwable t) {
        logger.error("Error for error dialog", t);
    }
}

From source file:edu.du.penrose.systems.fedoraApp.util.FedoraAppUtil.java

/**
 * Note this will give back a pid even if the context is NOT valid! This uses a FedoraAdministrator with credentials pulled from the
 * batchIngest.propertes file./*  www  . j  av a2 s.c o  m*/
 * 
 * See runBatch() notes.
        
 * @param fedoraContext
 * @param numberOfPids
 * @return array of reserved pids
 * @throws FatalException
 */
public static String[] getPIDs(String fedoraContext, NonNegativeInteger numberOfPids) throws FatalException {

    if (numberOfPids.intValue() < 1) {
        throw new FatalException("Invalid number of pids reqeuested:" + numberOfPids);
    }

    String[] pids = null;
    try {
        pids = getAdministratorUsingProgramProperiesFileCredentials().getAPIM().getNextPID(numberOfPids,
                fedoraContext);

        if (pids.length != numberOfPids.intValue()) {
            throw new Exception("Asked Fedora for " + numberOfPids + " pids but got " + pids.length + " back.");
        }
    } catch (Exception e) {
        String errorMsg = "Unable to get PID:" + e.getLocalizedMessage();
        Log logger = LogFactory
                .getLog("edu.du.penrose.systems.fedoraApp.batchIngest.bus.FedoraAppBatchIngestController");
        logger.fatal(errorMsg);
        throw new FatalException(errorMsg);
    }

    return pids;
}

From source file:edu.du.penrose.systems.fedoraApp.util.FedoraAppUtil.java

/**
 * Note this will give back a pid even if the context is NOT valid!
 * /*from  ww w.ja  v  a2 s. c  om*/
 * @param host
 * @param port
 * @param userName
 * @param password
 * @param fedoraContext
 * @param numberOfPids
 * @return
 * @throws FatalException
 */
public static String[] getPIDs(Administrator admin, String fedoraContext, NonNegativeInteger numberOfPids)
        throws FatalException {

    if (numberOfPids.intValue() < 1) {
        throw new FatalException("Invalid number of pids reqeuested:" + numberOfPids);
    }

    String[] pids = null;
    try {
        pids = admin.getAPIM().getNextPID(numberOfPids, fedoraContext);

        if (pids.length != numberOfPids.intValue()) {
            throw new Exception("Asked Fedora for " + numberOfPids + " pids but got " + pids.length + " back.");
        }
    } catch (Exception e) {
        String errorMsg = "Unable to get PID:" + e.getLocalizedMessage();
        Log logger = LogFactory
                .getLog("edu.du.penrose.systems.fedoraApp.batchIngest.bus.FedoraAppBatchIngestController");
        logger.fatal(errorMsg);
        throw new FatalException(errorMsg);
    }

    return pids;
}

From source file:cn.org.once.cstack.utils.MessageUtils.java

public static Message writeAfterThrowingApplicationMessage(Exception e, User user, String type,
        MessageSource messageSource, Locale locale) {
    Message message = new Message();
    String body = "";
    message.setType(Message.ERROR);/*from w w w  .j ava  2s.c om*/
    message.setAuthor(user);

    switch (type) {
    case "CREATE":
        body = messageSource.getMessage("app.create.error", null, locale);
        break;
    case "UPDATE":
        body = "Error update application - " + e.getLocalizedMessage();
        break;
    case "DELETE":
        body = "Error delete application - " + e.getLocalizedMessage();
        break;
    case "START":
        body = "Error start application - " + e.getLocalizedMessage();
        break;
    case "STOP":
        body = "Error stop application - " + e.getLocalizedMessage();
        break;
    case "RESTART":
        body = "Error restart application - " + e.getLocalizedMessage();
        break;

    default:
        body = "Error : unkown error";
        break;
    }
    message.setEvent(body);

    return message;
}

From source file:edu.du.penrose.systems.fedoraApp.util.FedoraAppUtil.java

/**
 * Note this will give back a pid even if the context is NOT valid!
 * //from   w  ww. ja v a  2s  .  c  om
 * @param host
 * @param port
 * @param userName
 * @param password
 * @param fedoraContext
 * @param numberOfPids
 * @return
 * @throws FatalException
 */
public static String[] getPIDs(String host, int port, String userName, String password, String fedoraContext,
        NonNegativeInteger numberOfPids) throws FatalException {

    if (numberOfPids.intValue() < 1) {
        throw new FatalException("Invalid number of pids reqeuested:" + numberOfPids);
    }

    String[] pids = null;
    try {

        pids = getAdministrator(host, port, userName, password).getAPIM().getNextPID(numberOfPids,
                fedoraContext);

        if (pids.length != numberOfPids.intValue()) {
            throw new Exception("Asked Fedora for " + numberOfPids + " pids but got " + pids.length + " back.");
        }
    } catch (Exception e) {
        String errorMsg = "Unable to get PID:" + e.getLocalizedMessage();
        Log logger = LogFactory
                .getLog("edu.du.penrose.systems.fedoraApp.batchIngest.bus.FedoraAppBatchIngestController");
        logger.fatal(errorMsg);
        throw new FatalException(errorMsg);
    }

    return pids;
}

From source file:net.mceoin.cominghome.NestUtils.java

private static void logException(Exception e, String extra) {
    String msg = "Exception";
    if ((e != null) && (e.getLocalizedMessage() != null)) {
        msg = "Exception: " + e.getLocalizedMessage();
    }//from  ww w. jav  a2 s  .  co  m
    msg += " " + extra;
    Log.e(TAG, msg);

}

From source file:edu.du.penrose.systems.fedoraApp.util.FedoraAppUtil.java

/**
 * Get THE SINGLETON MANUAL ingest administrator, THERE IS ONLY ONE, if it does not exist this function will create it.
 * /*from   w w w.j a  v  a 2  s .  c o  m*/
 * if System properties javax.net.ssl.trustStore or javax.net.ssl.trustStorePassword are not set, they are set 
 * to "\\fedora\\client\\truststore" and "tomcat" respectively.
 * 
 * @return a loged in fedora administrator
 * @throws FatalException if unable to login
 */
public static Administrator getAdministrator(String host, int port, String userName, String password)
        throws FatalException {
    try {

        if (System.getProperty("javax.net.ssl.trustStore") == null) {
            System.setProperty("javax.net.ssl.trustStore", "\\fedora\\client\\truststore"); // TBD
        }

        if (System.getProperty("javax.net.ssl.trustStorePassword") == null) {
            System.setProperty("javax.net.ssl.trustStorePassword", "tomcat"); // TBD
        }

        administratorForManualIngest = new Administrator("http", port, host, userName, password);

    } catch (Exception e) {
        throw new FatalException("Unable to get Fedora Administrator:" + e.getLocalizedMessage());
    }

    return administratorForManualIngest;
}