Example usage for java.net MalformedURLException printStackTrace

List of usage examples for java.net MalformedURLException printStackTrace

Introduction

In this page you can find the example usage for java.net MalformedURLException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.feathercoin.wallet.feathercoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getFeathercoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;// ww w.j  a  v a  2  s.co  m
    try {
        /*          String currencies[] = {"USD", "BTC", "RUR"};
                    String urls[] = {"https://btc-e.com/api/2/ftc_btc/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_rur/ticker"};
                    for(int i = 0; i < currencies.length; ++i) {
        final String currencyCode = currencies[i];
        final URL URL = new URL(urls[i]);
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();
                
        Reader reader = null;
        try
        {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            String euros = String.format("%.4f", avg);
            // Fix things like 3,1250
            euros = euros.replace(",", ".");
            rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
            if(currencyCode.equalsIgnoreCase("BTC")) btcRate = avg;
        }
        finally
        {
            if (reader != null)
                reader.close();
        }
                    }*/
        // Handle FTC/USD special since we have to do maths
        URL URL = null;
        try {
            URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is feathercoins priced in bitcoins
            btcRate = avg;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle FTC/USD special since we have to do maths
        URL = null;
        URL = new URL("https://btc-e.com/api/2/btc_usd/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in dollars.  We want FTC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle FTC/BTC special since we have to do maths
        URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in euros.  We want FTC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:de.schildbach.wallet.worldcoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getworldcoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;//from  ww w  .j ava2  s.  c om
    try {
        /*          String currencies[] = {"USD", "BTC", "RUR"};
                    String urls[] = {"https://btc-e.com/api/2/ftc_btc/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_rur/ticker"};
                    for(int i = 0; i < currencies.length; ++i) {
        final String currencyCode = currencies[i];
        final URL URL = new URL(urls[i]);
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();
                
        Reader reader = null;
        try
        {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            String euros = String.format("%.4f", avg);
            // Fix things like 3,1250
            euros = euros.replace(",", ".");
            rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
            if(currencyCode.equalsIgnoreCase("BTC")) btcRate = avg;
        }
        finally
        {
            if (reader != null)
                reader.close();
        }
                    }*/
        // Handle WDC/USD special since we have to do maths
        URL URL = null;
        try {
            URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is worldcoins priced in bitcoins
            btcRate = avg;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle WDC/USD special since we have to do maths
        URL = null;
        URL = new URL("https://btc-e.com/api/2/btc_usd/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in dollars.  We want WDC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle WDC/BTC special since we have to do maths
        URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in euros.  We want FTC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.mpower.daktar.android.utilities.WebUtils.java

public static void addCredentials(final String username, final String password) {

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MIntel.getAppContext());
    final String scheduleUrl = prefs.getString(PreferencesActivity.KEY_SERVER_URL, null);

    String host = "";

    try {//w w w  . ja v  a2 s .com
        host = new URL(URLDecoder.decode(scheduleUrl, "utf-8")).getHost();
    } catch (final MalformedURLException e) {
        e.printStackTrace();
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    addCredentials(username, password, host);
}

From source file:de.uzk.hki.da.sb.restfulService.FileUtil.java

/**
 * <p><em>Title: </em></p>
 * <p>Description: Method to strip file name from url</p>
 * // ww  w .  ja v a  2  s .  c  o m
 * @param url
 * @return 
 */
public static String getRemoteFileName(String url) {
    URL rUrl = null;
    ;
    try {
        rUrl = new URL(url);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String rFilePath = rUrl.getPath();
    String rFileName = rUrl.getPath().substring(rFilePath.lastIndexOf("/"));
    return rFileName;
}

From source file:com.clevertrail.mobile.viewtrail.Object_TrailArticle.java

private static int loadTrailArticle_helper(Activity activity, String sTrailName) {

    String sResponseLine = "";
    //sanity check
    if (sTrailName == null || sTrailName == "")
        return R.string.error_notrailname;

    //connect to clevertrail.com to get trail article
    HttpURLConnection urlConnection = null;
    try {/*from w ww  .j  a  v a 2  s . c o m*/
        String requestURL = String.format("http://clevertrail.com/ajax/handleGetArticleJSONByName.php?name=%s",
                Uri.encode(sTrailName));

        URL url = new URL(requestURL);
        urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        BufferedReader r = new BufferedReader(new InputStreamReader(in));

        //trail article in json format
        sResponseLine = r.readLine();

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return R.string.error_contactingclevertrail;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        // could not connect to clevertrail.com
        e.printStackTrace();
        return R.string.error_contactingclevertrail;
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

    JSONObject json = null;
    try {
        if (sResponseLine != "")
            json = new JSONObject(sResponseLine);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return R.string.error_corrupttrailinfo;
    }

    //now that we have the latest trail information, mark it as unsaved
    Object_TrailArticle.bSaved = false;

    // if json is null, we might not have internet activity so check saved
    // files
    if (json == null) {
        Database_SavedTrails db = new Database_SavedTrails(activity);
        db.openToRead();
        String jsonString = db.getJSONString(sTrailName);
        try {
            json = new JSONObject(jsonString);

            // if we found the json object in the db, mark it as saved
            if (json != null) {
                Object_TrailArticle.bSaved = true;
            }

        } catch (JSONException e) {
            return R.string.error_corrupttrailinfo;
        }
        db.close();
    }

    if (json != null) {
        Object_TrailArticle.createFromJSON(sTrailName, json);
        Object_TrailArticle.jsonText = sResponseLine;

        //after loading the data, launch the activity to actually view the trail
        Intent i = new Intent(mActivity, Activity_ViewTrail.class);
        mActivity.startActivity(i);

        return 0;
    }
    return R.string.error_corrupttrailinfo;
}

From source file:com.ushahidi.android.app.net.MainHttpClient.java

public static String SendMultiPartData(String URL, MultipartEntity postData) throws IOException {

    Log.d(CLASS_TAG, "PostFileUpload(): upload file to server.");

    // Dipo Fix/*from  w  ww  .  j  a  v a2s. c o m*/
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (postData != null) {
            Log.i(CLASS_TAG, "PostFileUpload(): ");
            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(postData);

            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                InputStream serverInput = respEntity.getContent();

                return GetText(serverInput);

            }
        }

    } catch (MalformedURLException ex) {
        Log.d(CLASS_TAG, "PostFileUpload(): MalformedURLException");
        ex.printStackTrace();
        return "";
        // fall through and return false
    } catch (Exception ex) {
        return "";
    }
    return "";
}

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

public static final String createServerHost() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ClientCollection.getAppContext());
    String scheduleUrl = prefs.getString(PreferencesActivity.KEY_SERVER_URL,
            ClientCollection.getAppContext().getResources().getString(R.string.url));

    String host = "";

    try {/*w  w w  .ja va 2 s .  c  o  m*/
        host = new URL(URLDecoder.decode(scheduleUrl, "utf-8")).getHost();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return host;
}

From source file:com.aware.ui.Plugins_Manager.java

/**
* Downloads and compresses image for optimized icon caching
* @param image_url/*from  w  ww.j  av a  2s . com*/
* @return
*/
public static byte[] cacheImage(String image_url, Context sContext) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = sContext.getResources().openRawResource(R.raw.aware);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework);
        sKeyStore.load(inStream, "awareframework".toCharArray());
        inStream.close();

        sKeyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(sKeyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        //Fetch image now that we recognise SSL
        URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https
        HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection();
        image_connection.setSSLSocketFactory(context.getSocketFactory());

        InputStream in_stream = image_connection.getInputStream();
        Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);

        return output.toByteArray();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.ushahidi.android.app.net.MainHttpClient.java

/**
 * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid
 * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no
 * data, 8 - api disabled, 9 - no task found, 10 - json is wrong
 *//*from   w w w  .ja  v  a 2  s  . com*/
public static int PostFileUpload(String URL, HashMap<String, String> params) throws IOException {
    Log.d(CLASS_TAG, "PostFileUpload(): upload file to server.");

    entity = new MultipartEntity();
    // Dipo Fix
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (params != null) {

            entity.addPart("task", new StringBody(params.get("task")));
            entity.addPart("incident_title",
                    new StringBody(params.get("incident_title"), Charset.forName("UTF-8")));
            entity.addPart("incident_description",
                    new StringBody(params.get("incident_description"), Charset.forName("UTF-8")));
            entity.addPart("incident_date", new StringBody(params.get("incident_date")));
            entity.addPart("incident_hour", new StringBody(params.get("incident_hour")));
            entity.addPart("incident_minute", new StringBody(params.get("incident_minute")));
            entity.addPart("incident_ampm", new StringBody(params.get("incident_ampm")));
            entity.addPart("incident_category", new StringBody(params.get("incident_category")));
            entity.addPart("latitude", new StringBody(params.get("latitude")));
            entity.addPart("longitude", new StringBody(params.get("longitude")));
            entity.addPart("location_name",
                    new StringBody(params.get("location_name"), Charset.forName("UTF-8")));
            entity.addPart("person_first",
                    new StringBody(params.get("person_first"), Charset.forName("UTF-8")));
            entity.addPart("person_last", new StringBody(params.get("person_last"), Charset.forName("UTF-8")));
            entity.addPart("person_email",
                    new StringBody(params.get("person_email"), Charset.forName("UTF-8")));

            if (!TextUtils.isEmpty(params.get("filename"))) {
                File file = new File(params.get("filename"));
                if (file.exists()) {
                    entity.addPart("incident_photo[]", new FileBody(new File(params.get("filename"))));
                }
            }

            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                InputStream serverInput = respEntity.getContent();
                return Util.extractPayloadJSON(GetText(serverInput));

            }
        }

    } catch (MalformedURLException ex) {
        Log.d(CLASS_TAG, "PostFileUpload(): MalformedURLException");
        ex.printStackTrace();
        return 11;
        // fall through and return false
    } catch (IllegalArgumentException ex) {
        Log.e(CLASS_TAG, ex.toString());
        //invalid URI
        return 12;
    } catch (IOException e) {
        Log.e(CLASS_TAG, e.toString());
        //timeout
        return 13;
    }
    return 10;
}

From source file:edu.ucsb.eucalyptus.admin.server.EucalyptusManagement.java

private static String getExternalIpAddress() {
    String ipAddr = null;//  ww w.j  a v  a 2  s.co  m
    HttpClient httpClient = new HttpClient();
    //support for http proxy
    if (HttpServerBootstrapper.httpProxyHost != null && (HttpServerBootstrapper.httpProxyHost.length() > 0)) {
        String proxyHost = HttpServerBootstrapper.httpProxyHost;
        if (HttpServerBootstrapper.httpProxyPort != null
                && (HttpServerBootstrapper.httpProxyPort.length() > 0)) {
            int proxyPort = Integer.parseInt(HttpServerBootstrapper.httpProxyPort);
            httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        } else {
            httpClient.getHostConfiguration().setProxyHost(new ProxyHost(proxyHost));
        }
    }
    // Use Rightscale's "whoami" service
    GetMethod method = new GetMethod("https://my.rightscale.com/whoami?api_version=1.0&cloud=0");
    Integer timeoutMs = new Integer(3 * 1000); // TODO: is this working?
    method.getParams().setSoTimeout(timeoutMs);

    try {
        httpClient.executeMethod(method);
        String str = "";
        InputStream in = method.getResponseBodyAsStream();
        byte[] readBytes = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = in.read(readBytes)) > 0) {
            str += new String(readBytes, 0, bytesRead);
        }
        Matcher matcher = Pattern.compile(".*your ip is (.*)").matcher(str);
        if (matcher.find()) {
            ipAddr = matcher.group(1);
        }

    } catch (MalformedURLException e) {
        LOG.warn("Malformed URL exception: " + e.getMessage());
        e.printStackTrace();

    } catch (IOException e) {
        LOG.warn("I/O exception: " + e.getMessage());
        e.printStackTrace();

    } finally {
        method.releaseConnection();
    }

    return ipAddr;
}