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.ct855.util.HttpsClientUtil.java

public static String testIt(String https_url, Map<String, String> map, String method)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL url;//from ww  w.  j av  a2  s .c o m
    try {

        url = new URL(https_url);

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        con.setRequestMethod(method);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            con.setRequestProperty(entry.getKey(), entry.getValue());
        }

        con.setSSLSocketFactory(ssf);
        //dumpl all cert info
        //print_https_cert(con);
        //dump all the content
        return print_content(con);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.tinyhydra.botd.GoogleOperations.java

public static List<JavaShop> GetShops(Handler handler, Location currentLocation, String placesApiKey) {
    // Use google places to get all the shops within '500' (I believe meters is the default measurement they use)
    // make a list of JavaShops and pass it to the ListView adapter
    List<JavaShop> shopList = new ArrayList<JavaShop>();
    try {//from  w ww  .j av a 2 s  . co  m
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        int accuracy = Math.round(currentLocation.getAccuracy());
        if (accuracy < 500)
            accuracy = 500;
        request.setURI(URI.create("https://maps.googleapis.com/maps/api/place/search/json?location="
                + currentLocation.getLatitude() + "," + currentLocation.getLongitude() + "&radius=" + accuracy
                + "&types=" + URLEncoder.encode("cafe|restaurant|food", "UTF-8")
                + "&keyword=coffee&sensor=true&key=" + placesApiKey));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }

        JSONObject predictions = new JSONObject(sb.toString());
        // Google passes back a status string. if we screw up, it won't say "OK". Alert the user.
        String jstatus = predictions.getString("status");
        if (jstatus.equals("ZERO_RESULTS")) {
            Utils.PostToastMessageToHandler(handler, "No shops found in your area.", Toast.LENGTH_SHORT);
            return shopList;
        } else if (!jstatus.equals("OK")) {
            Utils.PostToastMessageToHandler(handler, "Error retrieving local shops.", Toast.LENGTH_SHORT);
            return shopList;
        }

        // This section may fail if there's no results, but we'll just display an empty list.
        //TODO: alert the user and cancel the dialog if this fails
        JSONArray ja = new JSONArray(predictions.getString("results"));

        for (int i = 0; i < ja.length(); i++) {
            JSONObject jo = (JSONObject) ja.get(i);
            shopList.add(new JavaShop(jo.getString("name"), jo.getString("id"), "", jo.getString("reference"),
                    jo.getString("vicinity")));
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return shopList;
}

From source file:com.firegnom.valkyrie.util.PacksHelper.java

/**
 * Packs avilable.//from w w  w  . ja v a2  s  . co  m
 *
 * @param path the path
 * @return true, if successful
 */
public static boolean packsAvilable(String path) {
    Download packsDownload;
    try {
        packsDownload = new Download(new URL("http://valkyrie.firegnom.com/data/packs.json"), path, true);
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
        return false;
    }
    if (!packsDownload.download()) {
        return false;
    }
    File packs = new File(path + "packs.json");
    JSONObject packsjson;

    try {
        packsjson = new JSONObject(Util.convertStreamToString(new FileInputStream(packs)));
        JSONArray packsArray = packsjson.getJSONArray("install");
        for (int i = 0; i < packsArray.length(); i++) {
            String pack = packsArray.getString(i);
            if (!new File(path + pack + ".json").exists()) {
                return true;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return false;
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesRetriever.java

private static JSONObject retrieveTimeSeriesGET(String urlString, long startEpoch, long endEpoch, String metric,
        HashMap<String, String> tags, boolean showTSUIDs) {

    urlString = urlString + API_METHOD;//from w w w  .java  2  s  .  co  m
    String result = "";

    StringBuilder builder = new StringBuilder();

    builder.append("?start=");
    builder.append(startEpoch);
    builder.append("&end=");
    builder.append(endEpoch);
    builder.append("&show_tsuids=");
    builder.append(showTSUIDs);
    builder.append("&m=sum:");
    builder.append(metric);

    if (tags != null) {
        builder.append("{");

        Iterator<Entry<String, String>> entries = tags.entrySet().iterator();
        while (entries.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry entry = (Map.Entry) entries.next();
            builder.append((String) entry.getKey());
            builder.append("=");
            builder.append((String) entry.getValue());
            if (entries.hasNext()) {
                builder.append(",");
            }
        }
        builder.append("}");
    }

    try {
        HttpURLConnection httpConnection = TimeSeriesUtility
                .openHTTPConnectionGET(urlString + builder.toString());
        result = TimeSeriesUtility.readHttpResponse(httpConnection);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (OpenTSDBException e) {
        e.printStackTrace();
        result = String.valueOf(e.responseCode);
    }
    return TimeSeriesUtility.makeResponseJSONObject(result);
}

From source file:com.doculibre.constellio.solr.context.SolrCoreContext.java

public static synchronized void init() {
    if (mainSolrServer == null) {
        try {//  ww w  . j av a2  s  . c o m
            mainSolrServer = new CloudSolrServer(ConstellioSpringUtils.getZooKeeperAddress());
            mainSolrServer.setZkClientTimeout(ConstellioSpringUtils.getZooKeeperClientTimeout());
            mainSolrServer.setZkConnectTimeout(ConstellioSpringUtils.getZooKeeperConTimeout());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    initCores();

    if (zkClient == null) {
        zkClient = new SolrZkClient(ConstellioSpringUtils.getZooKeeperAddress(),
                ConstellioSpringUtils.getZooKeeperClientTimeout(),
                ConstellioSpringUtils.getZooKeeperConTimeout(), new OnReconnect() {
                    @Override
                    public void command() {
                    }
                });
    }
}

From source file:org.broadinstitute.gatk.utils.help.ForumAPIUtils.java

private static String httpPost(String data, String URL) {
    try {/*from   w  ww.j a v  a 2  s. c o  m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(URL);

        StringEntity input = new StringEntity(data);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output = "";
        String line;
        System.out.println("Output from Server .... \n");
        while ((line = br.readLine()) != null) {
            output += (line + '\n');
            System.out.println(line);
        }

        br.close();
        httpClient.getConnectionManager().shutdown();
        return output;

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
    return null;
}

From source file:net.securnetwork.itebooks.downloader.EbookDownloader.java

private static int getLastEbookIndex() {
    try {/*from   w  w  w.  j av  a  2s  .c  om*/
        Source sourceHTML = new Source(new URL(BASE_URL));
        List<Element> allTDs = sourceHTML.getAllElements(HTMLElementName.TD);
        for (Element td : allTDs) {
            List<Element> innerH2s = td.getAllElements(HTMLElementName.H2);
            if (!innerH2s.isEmpty() && "Last Upload Ebooks".equalsIgnoreCase( //$NON-NLS-1$
                    innerH2s.get(0).getTextExtractor().toString())) {
                // Found interesting section
                List<Element> allTDElements = td.getAllElements(HTMLElementName.TD);
                Element lastEbookLink = allTDElements.get(0).getAllElements(HTMLElementName.A).get(0);
                String lastEbookRelativeHref = lastEbookLink.getAttributeValue("href"); //$NON-NLS-1$
                StringTokenizer tokenizer = new StringTokenizer(lastEbookRelativeHref, "/"); //$NON-NLS-1$
                for (int i = 1; i < tokenizer.countTokens(); i++) {
                    tokenizer.nextToken();
                }
                return Integer.parseInt(tokenizer.nextToken());
            }

        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return MAX_EBOOK_INDEX;
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

public static void doDelete(String urls, String token) {
    URL url = null;/*from   w  w w  .j a  v a2 s  .co  m*/
    try {
        url = new URL(urls);
    } catch (MalformedURLException exception) {
        exception.printStackTrace();
    }
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        if (!Global.isEmpty(token)) {
            httpURLConnection.setRequestProperty("X-Auth-Token", token);
        }
        httpURLConnection.setRequestMethod("DELETE");
        logger.info("#####====" + httpURLConnection.getResponseCode());
    } catch (IOException e) {
        logger.error("Exception", e);
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
}

From source file:com.baidu.cafe.local.NetworkUtils.java

/**
 * download via a url/*from w  w w .  jav  a 2  s  .  c  o  m*/
 * 
 * @param url
 * @param outputStream
 *            openFileOutput("networktester.download",
 *            Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE)
 */
public static void httpDownload(String url, OutputStream outputStream) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
        httpClient.execute(new HttpGet(url)).getEntity().writeTo(outputStream);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:au.com.tyo.sn.shortener.GooGl.java

private static String post(String url) {
    HttpURLConnection httpcon = null;

    try {//  w ww  .  j  a v a2 s  .c o m
        httpcon = (HttpURLConnection) ((new URL(GOO_GL_REQUEST_URL).openConnection()));

        httpcon.setDoOutput(true);
        httpcon.setRequestProperty("Content-Type", "application/json");
        httpcon.setRequestProperty("Accept", "application/json");
        httpcon.setRequestMethod("POST");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    byte[] outputBytes = { 0 };
    OutputStream os = null;
    InputStream is = null;
    BufferedReader in = null;
    StringBuilder text = new StringBuilder();

    try {
        outputBytes = ("{'longUrl': \"" + url + "\"}").getBytes("UTF-8");
        httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length));
        httpcon.connect();
        os = httpcon.getOutputStream();
        os.write(outputBytes);
        is = httpcon.getInputStream();
        in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        if (in != null) {
            // get page text
            String line;

            while ((line = in.readLine()) != null) {
                text.append(line);
                text.append("\n");
            }
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
            if (in != null)
                in.close();
        } catch (IOException e) {
        }
    }

    return text.toString();
}