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.mpower.daktar.android.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//  w  w w  .ja va 2  s  .  c o m
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(final String urlString, final HttpContext localContext,
        final HttpClient httpclient, final String auth) {
    URI u = null;
    try {
        final URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
        u = url.toURI();
    } catch (final Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + "while accessing" + urlString, 0);
    }

    // set up request...
    final HttpGet req = WebUtils.createOpenRosaHttpGet(u, auth);

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

        final HttpEntity entity = response.getEntity();

        if (entity != null && (statusCode != 200 || !entity.getContentType().getValue().toLowerCase()
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML))) {
            try {
                // don't really care about the stream...
                final InputStream is = response.getEntity().getContent();
                // read to end of stream...
                final long count = 1024L;
                while (is.skip(count) == count) {
                    ;
                }
                is.close();
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }

        if (statusCode != 200) {
            final String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

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

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

        if (!entity.getContentType().getValue().toLowerCase().contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            final 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();
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                final KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
            } finally {
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (final Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (final Exception e) {
                        // no-op
                    }
                }
            }
        } catch (final Exception e) {
            e.printStackTrace();
            final String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        final Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            final StringBuilder b = new StringBuilder();
            for (final 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 (final Exception e) {
        e.printStackTrace();
        String cause;
        if (e.getCause() != null) {
            cause = e.getCause().getMessage();
        } else {
            cause = e.getMessage();
        }
        final String error = "Error: " + cause + " while accessing " + u.toString();

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

From source file:jahirfiquitiva.iconshowcase.fragments.WallpapersFragment.java

private static void setupLayout(final boolean fromTask, final Activity context, final ImageView noConnection) {

    if (WallpapersList.getWallpapersList() != null && WallpapersList.getWallpapersList().size() > 0) {
        context.runOnUiThread(new Runnable() {
            @Override// www.j a v  a 2s.  c o m
            public void run() {
                mAdapter = new WallpapersAdapter(context, new WallpapersAdapter.ClickListener() {
                    @Override
                    public void onClick(WallpapersAdapter.WallsHolder view, int position, boolean longClick) {
                        if ((longClick && !ShowcaseActivity.wallsPicker) || ShowcaseActivity.wallsPicker) {
                            final MaterialDialog dialog = new MaterialDialog.Builder(context)
                                    .content(R.string.downloading_wallpaper).progress(true, 0).cancelable(false)
                                    .show();

                            WallpaperItem wallItem = WallpapersList.getWallpapersList().get(position);

                            Glide.with(context).load(wallItem.getWallURL()).asBitmap()
                                    .into(new SimpleTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(final Bitmap resource,
                                                GlideAnimation<? super Bitmap> glideAnimation) {
                                            if (resource != null) {
                                                new ApplyWallpaper(context, dialog, resource,
                                                        ShowcaseActivity.wallsPicker, layout).execute();
                                            }
                                        }
                                    });
                        } else {
                            final Intent intent = new Intent(context, ViewerActivity.class);

                            intent.putExtra("item", WallpapersList.getWallpapersList().get(position));
                            intent.putExtra("transitionName", ViewCompat.getTransitionName(view.wall));

                            Bitmap bitmap;

                            if (view.wall.getDrawable() != null) {
                                bitmap = Utils.drawableToBitmap(view.wall.getDrawable());

                                try {
                                    String filename = "temp.png";
                                    FileOutputStream stream = context.openFileOutput(filename,
                                            Context.MODE_PRIVATE);
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                                    stream.close();
                                    intent.putExtra("image", filename);
                                } catch (Exception e) {
                                    Utils.showLog(context, "Error getting drawable " + e.getLocalizedMessage());
                                }

                                ActivityOptionsCompat options = ActivityOptionsCompat
                                        .makeSceneTransitionAnimation(context, view.wall,
                                                ViewCompat.getTransitionName(view.wall));
                                context.startActivity(intent, options.toBundle());
                            } else {
                                context.startActivity(intent);
                            }
                        }
                    }
                });

                mAdapter.setData(WallpapersList.getWallpapersList());

                mRecyclerView.setAdapter(mAdapter);

                fastScroller = (RecyclerFastScroller) layout.findViewById(R.id.rvFastScroller);

                fastScroller.attachRecyclerView(mRecyclerView);

                if (fastScroller.getVisibility() != View.VISIBLE) {
                    fastScroller.setVisibility(View.VISIBLE);
                }

                if (Utils.hasNetwork(context)) {
                    hideProgressBar();
                    noConnection.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.VISIBLE);
                    fastScroller.setVisibility(View.VISIBLE);
                    mSwipeRefreshLayout.setEnabled(false);
                    mSwipeRefreshLayout.setRefreshing(false);
                } else {
                    hideStuff(noConnection);
                }
            }
        });
    } else {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (layout != null) {
                    noConnection.setVisibility(View.GONE);
                    showProgressBar();
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    hideStuff(noConnection);
                                }
                            });
                        }
                    }, 7500);
                }
            }
        });
    }
}

From source file:edu.washington.cs.mystatus.odk.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/* w ww  .  j a  v  a2 s  .c o  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);

    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?
                MyStatus.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();
                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:com.clavain.alerts.Methods.java

public static boolean sendTTSMessage(String message, String mobile_nr) {
    boolean retval = false;

    try {/*from  w  ww . ja  v a  2 s . c o m*/
        if (p.getProperty("tts.provider").equals("smsflatrate")) {
            String key = p.getProperty("smsflatrate.key");
            String gw = p.getProperty("smsflatrate.ttsgw");

            String msg = URLEncoder.encode(message);
            URL url = new URL("http://smsflatrate.net/schnittstelle.php?key=" + key + "&to=" + mobile_nr
                    + "&voice=Dave&repeat=2&rate=1&type=" + gw + "&text=" + msg);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().equals("100")) {
                retval = true;
            }
        } else if (p.getProperty("tts.provider").equals("script")) {
            List<String> commands = new ArrayList<String>();
            // add global timeout script
            commands.add(p.getProperty("tts.script"));
            commands.add(mobile_nr);
            commands.add(message);
            ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true);
            logger.info("tts.script - Running: " + commands);
            Process p = pb.start();
            Integer rv = p.waitFor();

        }
    } catch (Exception ex) {
        retval = false;
        logger.error("sendTTSMessage Error: " + ex.getLocalizedMessage());
    }
    return retval;
}

From source file:org.koboc.collect.android.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/*  w ww  . java  2s . 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);

    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?
                Collect.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();
                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:cd.education.data.collector.android.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/*  w w  w. java 2 s  .  c  o  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?
                Collect.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:com.clavain.alerts.Methods.java

public static void sendUPNotifications(ReturnServiceCheck sc) {
    Integer cid = sc.getCid();//from   w  w w.j  a  v  a 2s .c  om
    try {
        Connection conn = connectToDatabase(com.clavain.muninmxcd.p);
        java.sql.Statement stmt = conn.createStatement();

        ResultSet rs = stmt.executeQuery(
                "SELECT notifications.id as nid, contacts.* FROM `notifications` LEFT JOIN contacts ON notifications.contact_id = contacts.id WHERE check_id = "
                        + cid);
        while (rs.next()) {
            Integer contact_id = rs.getInt("id");
            String dayField = getScheduleFieldToCheck();
            logger.info("[Check Notifications " + cid + "] Found " + rs.getString("contact_name"));
            if (rs.getString(dayField).equals("disabled")) {
                logger.info("[Check Notifications " + cid + "] " + 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 title = "Service OK: " + sc.getCheckname() + " (" + sc.getChecktype() + ")";
                    String message = "The Service is now up again.";
                    String json = "";
                    if (rs.getInt("email_active") == 1) {
                        logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                                + " Sending E-Mail");
                        sendMail(title, message, rs.getString("contact_email"));
                        updateCheckNotificationLog(cid, contact_id,
                                "UPTIME E-Mail send to " + rs.getString("contact_email"), "email");
                    }
                    if (rs.getInt("sms_active") == 1) {
                        logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                                + " Sending SMS");
                        sendSMS(title, message, rs.getString("contact_mobile_nr"), rs.getInt("user_id"));
                        updateCheckNotificationLog(cid, contact_id,
                                "UPTIME SMS send to " + rs.getString("contact_mobile_nr"), "sms");
                    }
                    if (rs.getInt("pushover_active") == 1) {
                        logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                                + " Sending Pushover Notification");
                        sendPushover(title, message, rs.getString("pushover_key"));
                        updateCheckNotificationLog(cid, contact_id,
                                "UPTIME PushOver Message send to " + rs.getString("pushover_key"), "pushover");
                    }
                } else {
                    logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                            + " disabled notifications for this timerange - skipping contact");
                }
            }
        }
    } catch (Exception ex) {
        logger.error("Error in sendUPNotifications for CID " + cid + " : " + ex.getLocalizedMessage());
    }
}

From source file:com.grameenfoundation.ictc.controllers.SaleforceIntegrationController.java

public static Document parseXmlText(InputSource input_data) {
    //get the factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {/*w  w  w. j a  v  a2s  . c o  m*/

        //Using factory get an instance of document builder
        DocumentBuilder db = dbf.newDocumentBuilder();

        //InputSource is = new InputSource();
        //is.setCharacterStream(new StringReader(data));
        //parse using builder to get DOM representation of the data
        Document doc = db.parse(input_data);
        // normalize text representation
        doc.getDocumentElement().normalize();
        System.out.println("Root element of the doc is " + doc.getDocumentElement().getNodeName());

        return doc;

    } catch (ParserConfigurationException pce) {
        System.out.println("Exception is " + pce.getLocalizedMessage());
        pce.printStackTrace();
        return null;
    } catch (SAXException se) {
        System.out.println("Exception is " + se.getLocalizedMessage());
        System.out.println("line " + se.getMessage());
        se.printStackTrace();
        return null;
    } catch (IOException ioe) {
        System.out.println("Exception is " + ioe.getLocalizedMessage());
        ioe.printStackTrace();
        return null;
    } catch (Exception ex) {
        System.out.println("Exception is " + ex.getLocalizedMessage());
        //    ioe.printStackTrace();
        return null;
    }
}

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

public static boolean sendSMSMessage(String message, String mobile_nr) {
    boolean retval = false;
    // http://smsflatrate.net/schnittstelle.php?key=ff&to=00491734631526&type=4&text=ALERT:%20Notification%20Test%20(HTTPS)%20-%20HTTP%20Critical-%20OK%20String%20not%20found
    try {/*  w  ww  .  j  a  va 2  s. co  m*/
        if (p.getProperty("sms.provider").equals("smsflatrate")) {
            String key = p.getProperty("smsflatrate.key");
            String gw = p.getProperty("smsflatrate.gw");
            if (mobile_nr.startsWith("0049")) {
                gw = p.getProperty("smsflatrate.gwde");
            }
            String msg = URLEncoder.encode(message);
            URL url = new URL("http://smsflatrate.net/schnittstelle.php?key=" + key + "&to=" + mobile_nr
                    + "&type=" + gw + "&text=" + msg);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().equals("100")) {
                retval = true;
            }
        } else if (p.getProperty("sms.provider").equals("bulksms")) {
            // http://bulksms.de:5567/eapi/submission/send_sms/2/2.0?username=ff&password=yt89hjfff98&message=Hey%20Fucker&msisdn=491734631526
            String msg = URLEncoder.encode(message);
            URL url = new URL("http://bulksms.de:5567/eapi/submission/send_sms/2/2.0?username="
                    + p.getProperty("bulksms.username") + "&password=" + p.getProperty("bulksms.password")
                    + "&message=" + msg + "&msisdn=" + mobile_nr);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().startsWith("0")) {
                retval = true;
            }
        } else if (p.getProperty("sms.provider").equals("twilio")) {
            // reformat number?
            if (mobile_nr.startsWith("00")) {
                mobile_nr = "+" + mobile_nr.substring(2, mobile_nr.length());
            } else if (mobile_nr.startsWith("0")) {
                mobile_nr = "+" + mobile_nr.substring(1, mobile_nr.length());
            }
            TwilioRestClient client = new TwilioRestClient(p.getProperty("twilio.accountsid"),
                    p.getProperty("twilio.authtoken"));
            //String msg = URLEncoder.encode(message);
            // Build the parameters 
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("To", mobile_nr));
            params.add(new BasicNameValuePair("From", p.getProperty("twilio.fromnr")));
            params.add(new BasicNameValuePair("Body", message));

            MessageFactory messageFactory = client.getAccount().getMessageFactory();
            Message tmessage = messageFactory.create(params);
            logger.info("twilio: msg send to " + mobile_nr + " sid: " + tmessage.getSid() + " status: "
                    + tmessage.getStatus() + " twilio emsg: " + tmessage.getErrorMessage());

        } else if (p.getProperty("sms.provider").equals("script")) {
            List<String> commands = new ArrayList<String>();
            // add global timeout script
            commands.add(p.getProperty("sms.script"));
            commands.add(mobile_nr);
            commands.add(message);
            ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true);
            logger.info("sms.script - Running: " + commands);
            Process p = pb.start();
            Integer rv = p.waitFor();
        }
    } catch (Exception ex) {
        retval = false;
        logger.error("sendSMSMessage Error: " + ex.getLocalizedMessage());
    }
    return retval;
}

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

public static void sendNotifications(ReturnServiceCheck sc) {
    Integer cid = sc.getCid();/*from   w ww.  ja v a2s  . com*/
    try {
        Connection conn = connectToDatabase(com.clavain.muninmxcd.p);
        java.sql.Statement stmt = conn.createStatement();

        ResultSet rs = stmt.executeQuery(
                "SELECT notifications.id as nid, contacts.* FROM `notifications` LEFT JOIN contacts ON notifications.contact_id = contacts.id WHERE check_id = "
                        + cid);
        while (rs.next()) {
            Integer contact_id = rs.getInt("id");
            String dayField = getScheduleFieldToCheck();
            logger.info("[Check Notifications " + cid + "] Found " + rs.getString("contact_name"));
            if (rs.getString(dayField).equals("disabled")) {
                logger.info("[Check Notifications " + cid + "] " + 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(sc.getDownTimeConfirmedAt(),
                            rs.getString("timezone"));
                    String title = "ALERT: " + sc.getCheckname() + " (" + sc.getChecktype() + ")";
                    String message = "Service Downtime verified @ " + failTime + ".   Details: "
                            + sc.getOutput().get(0);

                    String json = "";
                    if (rs.getInt("callback_active") == 1) {
                        logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                                + " Sending Callback");
                        sendCallback(sc, rs.getString("contact_callback"));
                        updateCheckNotificationLog(cid, contact_id,
                                "Callback executed to " + rs.getString("contact_callback"), "callback");
                    }
                    if (rs.getInt("tts_active") == 1) {
                        title = "This is a PingReports Alert: The Servicecheck: " + sc.getCheckname()
                                + " with type: " + sc.getChecktype() + " is in alert state.";
                        logger.info("[Notifications " + cid + "] " + rs.getString("contact_name")
                                + " Initiating TTS Call");
                        sendTTS(title, message, rs.getString("contact_mobile_nr"), rs.getInt("user_id"));
                        updateCheckNotificationLog(cid, contact_id,
                                "Text2Speech Call initiated to " + rs.getString("contact_mobile_nr"), "tts");
                    }
                    if (rs.getInt("email_active") == 1) {
                        logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                                + " Sending E-Mail");
                        String ENDL = System.getProperty("line.separator");
                        message = "Service Downtime verified @ " + failTime + "." + ENDL + ENDL + "Details:"
                                + ENDL + ENDL + sc.getOutput().get(0);
                        sendMail(title, message, rs.getString("contact_email"));
                        updateCheckNotificationLog(cid, contact_id,
                                "E-Mail send to " + rs.getString("contact_email"), "email");
                    }
                    if (rs.getInt("sms_active") == 1) {
                        title = sc.getCheckname() + "(" + sc.getChecktype() + ")";
                        message = sc.getOutput().get(0);
                        logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                                + " Sending SMS");
                        sendSMS(title, message, rs.getString("contact_mobile_nr"), rs.getInt("user_id"));
                        updateCheckNotificationLog(cid, contact_id,
                                "SMS send to " + rs.getString("contact_mobile_nr"), "sms");
                    }
                    if (rs.getInt("pushover_active") == 1) {
                        logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                                + " Sending Pushover Notification");
                        sendPushover(title, message, rs.getString("pushover_key"));
                        updateCheckNotificationLog(cid, contact_id,
                                "PushOver Message send to " + rs.getString("pushover_key"), "pushover");
                    }

                } else {
                    logger.info("[Check Notifications " + cid + "] " + rs.getString("contact_name")
                            + " disabled notifications for this timerange - skipping contact");
                }
            }
        }

    } catch (Exception ex) {
        logger.error("Error in sendNotifications for CID " + cid + " : " + ex.getLocalizedMessage());
        ex.printStackTrace();
    }
}