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:gov.nih.nci.nbia.StandaloneDMV1.java

private static List<String> connectAndReadFromURL(URL url, String fileName) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override//from  w  ww .j  av  a  2s.  c  o  m
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair("serverjnlpfileloc", fileName));
        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        // int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("Response code for requesting datda file: " +
        // responseCode);
        InputStream inputStream = response.getEntity().getContent();
        data = IOUtils.readLines(inputStream);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}

From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java

/**
 * ?//  www  .ja v a 2s .  co m
 * @param postUrl ?
 * @param param ?
 * @param method 
 * @return null
 */
public static String request(String postUrl, String param, String method) {
    URL url;
    try {
        url = new URL(postUrl);

        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30000); // ??)
        conn.setReadTimeout(30000); // ????)
        conn.setDoOutput(true); // post??http?truefalse
        conn.setDoInput(true); // ?httpUrlConnectiontrue
        conn.setUseCaches(false); // Post ?
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestMethod(method);// "POST"GET
        conn.setRequestProperty("Content-Length", param.length() + "");
        String encode = "utf-8";
        OutputStreamWriter out = null;
        out = new OutputStreamWriter(conn.getOutputStream(), encode);
        out.write(param);
        out.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        // ??
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line = "";
        StringBuffer strBuf = new StringBuffer();
        while ((line = in.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        in.close();
        out.close();
        return strBuf.toString();
    } catch (MalformedURLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:com.nwn.NwnFileHandler.java

/**
 * Downloads file from given url/*  ww  w.ja v a2s. c  o  m*/
 * @param fileUrl String of url to download
 * @param dest Location on system where file should be downloaded
 * @return True if download success, False if download failed
 */
public static boolean downloadFile(String fileUrl, String dest) {
    try {
        URL url = new URL(fileUrl);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(dest);
        String fileSizeString = url.openConnection().getHeaderField("Content-Length");
        double fileSize = Double.parseDouble(fileSizeString);
        byte[] buffer = new byte[1024];
        int count;
        double bytesDownloaded = 0.0;
        while ((count = bis.read(buffer, 0, 1024)) != -1) {
            bytesDownloaded += count;
            fis.write(buffer, 0, count);

            int downloadStatus = (int) ((bytesDownloaded / fileSize) * 100);

            System.out.println("Downloading " + fileUrl + " to " + dest + " " + downloadStatus + "%");
        }
        fis.close();
        bis.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        return false;
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        return false;
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.immopoly.android.helper.WebHelper.java

public static JSONObject getHttpData(URL url, boolean signed, Context context) throws JSONException {
    JSONObject obj = null;/*  w  ww  . j  a v  a 2 s .  c om*/
    if (Settings.isOnline(context)) {
        HttpURLConnection request;
        try {

            request = (HttpURLConnection) url.openConnection();

            request.addRequestProperty("User-Agent",
                    "immopoly android client " + ImmopolyActivity.getStaticVersionInfo());
            request.addRequestProperty("Accept-Encoding", "gzip");
            if (signed)
                OAuthData.getInstance(context).consumer.sign(request);
            request.setConnectTimeout(SOCKET_TIMEOUT);

            request.connect();
            String encoding = request.getContentEncoding();

            InputStream in;
            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                in = new GZIPInputStream(request.getInputStream());
            } else {
                in = new BufferedInputStream(request.getInputStream());
            }
            String s = readInputStream(in);
            JSONTokener tokener = new JSONTokener(s);
            obj = new JSONObject(tokener);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthMessageSignerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return obj;
}

From source file:com.ecarride.App.java

public static JSONArray loadJson(String url) throws JSONException {
    StringBuilder json = new StringBuilder();
    try {/* w ww.ja v  a  2 s. c  o m*/
        URL urlObject = new URL(url);
        URLConnection uc = urlObject.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));

        String inputLine = null;
        //         int count = 0;
        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
            /*if (count++ <= 2)
               System.out.println(inputLine);*/
        }
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new JSONArray(json.toString());
}

From source file:org.LinuxdistroCommunity.android.client.NetworkUtilities.java

public static String getAuthToken(String server, String code) {

    String token = null;/* w ww  .j av  a2s.  co  m*/

    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_CODE, code));
    params.add(new BasicNameValuePair(PARAM_CLIENT_SECRET, CLIENT_SECRET));

    InputStream is = null;
    URL auth_token_url;
    try {
        auth_token_url = getRequestURL(server, PATH_OAUTH_ACCESS_TOKEN, params);
        Log.i(TAG, auth_token_url.toString());

        HttpURLConnection conn = (HttpURLConnection) auth_token_url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response_code = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response_code);
        is = conn.getInputStream();

        // parse token_response as JSON to get the token out
        String str_response = readStreamToString(is, 500);
        Log.d(TAG, str_response);
        JSONObject response = new JSONObject(str_response);
        token = response.getString("access_token");

    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // Makes sure that the InputStream is closed after the app is
        // finished using it.
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Log.i(TAG, token);
    return token;
}

From source file:com.cws.esolutions.core.listeners.CoreServiceInitializer.java

/**
 * Initializes the core service in a standalone mode - used for applications outside of a container or when
 * run as a standalone jar.//from   www .  ja  va  2 s  . c o m
 *
 * @param configFile - The service configuration file to utilize
 * @param logConfig - The logging configuration file to utilize
 * @param loadSecurity - Flag to start security
 * @param startConnections - Flag to start connections
 * @throws CoreServiceException @{link com.cws.esolutions.core.exception.CoreServiceException}
 * if an exception occurs during initialization
 */
public static void initializeService(final String configFile, final String logConfig,
        final boolean loadSecurity, final boolean startConnections) throws CoreServiceException {
    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfig secConfig = null;
    CoreConfigurationData configData = null;
    SecurityConfigurationData secConfigData = null;

    if (loadSecurity) {
        secConfigData = SecurityServiceBean.getInstance().getConfigData();
        secConfig = secConfigData.getSecurityConfig();
    }

    final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("coreConfigFile")
            : configFile;
    final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("coreLogConfig")
            : logConfig;

    try {
        try {
            DOMConfigurator.configure(Loader.getResource(loggingConfig));
        } catch (NullPointerException npx) {
            try {
                DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL());
            } catch (NullPointerException npx1) {
                System.err.println("Unable to load logging configuration. No logging enabled!");
                System.err.println("");
                npx1.printStackTrace();
            }
        }

        xmlURL = CoreServiceInitializer.class.getClassLoader().getResource(serviceConfig);

        if (xmlURL == null) {
            // try loading from the filesystem
            xmlURL = FileUtils.getFile(configFile).toURI().toURL();
        }

        context = JAXBContext.newInstance(CoreConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL);

        CoreServiceInitializer.appBean.setConfigData(configData);

        if (startConnections) {
            Map<String, DataSource> dsMap = CoreServiceInitializer.appBean.getDataSources();

            if (DEBUG) {
                DEBUGGER.debug("dsMap: {}", dsMap);
            }

            if (dsMap == null) {
                dsMap = new HashMap<String, DataSource>();
            }

            for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                if (!(dsMap.containsKey(mgr.getDsName()))) {
                    StringBuilder sBuilder = new StringBuilder()
                            .append("connectTimeout=" + mgr.getConnectTimeout() + ";")
                            .append("socketTimeout=" + mgr.getConnectTimeout() + ";")
                            .append("autoReconnect=" + mgr.getAutoReconnect() + ";")
                            .append("zeroDateTimeBehavior=convertToNull");

                    if (DEBUG) {
                        DEBUGGER.debug("StringBuilder: {}", sBuilder);
                    }

                    BasicDataSource dataSource = new BasicDataSource();
                    dataSource.setDriverClassName(mgr.getDriver());
                    dataSource.setUrl(mgr.getDataSource());
                    dataSource.setUsername(mgr.getDsUser());
                    dataSource.setConnectionProperties(sBuilder.toString());
                    dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getSalt(),
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            configData.getAppConfig().getEncoding()));
                    if (DEBUG) {
                        DEBUGGER.debug("BasicDataSource: {}", dataSource);
                    }

                    dsMap.put(mgr.getDsName(), dataSource);
                }
            }

            if (DEBUG) {
                DEBUGGER.debug("dsMap: {}", dsMap);
            }

            CoreServiceInitializer.appBean.setDataSources(dsMap);
        }
    } catch (JAXBException jx) {
        jx.printStackTrace();
        throw new CoreServiceException(jx.getMessage(), jx);
    } catch (MalformedURLException mux) {
        mux.printStackTrace();
        throw new CoreServiceException(mux.getMessage(), mux);
    }
}

From source file:com.openkm.openmeetings.service.RestService.java

/**
 * call/* w w  w  . j a va  2s  . c  om*/
 * 
 * @param request
 * @param param
 * @return
 * @throws Exception
 */
public static List<Element> callList(String request, Object param) throws Exception {
    HttpClient client = new HttpClient();
    GetMethod method = null;
    try {
        method = new GetMethod(getEncodetURI(request).toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    int statusCode = 0;
    try {
        statusCode = client.executeMethod(method);
    } catch (HttpException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    } catch (IOException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    }

    switch (statusCode) {
    case 200: // OK
        break;
    case 400:
        throw new Exception(
                "Bad request. The parameters passed to the service did not match as expected. The Message should tell you what was missing or incorrect.");
    case 403:
        throw new Exception(
                "Forbidden. You do not have permission to access this resource, or are over your rate limit.");
    case 503:
        throw new Exception(
                "Service unavailable. An internal problem prevented us from returning data to you.");
    default:
        throw new Exception("Your call to OpenMeetings! Web Services returned an unexpected  HTTP status of: "
                + statusCode);
    }

    InputStream rstream = null;
    try {
        rstream = method.getResponseBodyAsStream();
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("No Response Body");
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    SAXReader reader = new SAXReader();
    Document document = null;
    String line;
    try {
        while ((line = br.readLine()) != null) {
            document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new Exception("UnsupportedEncodingException by SAXReader");
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("IOException by SAXReader in REST Service");
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new Exception("DocumentException by SAXReader in REST Service");
    } finally {
        br.close();
    }

    Element root = document.getRootElement();
    List<Element> elementList = new ArrayList<Element>();

    for (@SuppressWarnings("unchecked")
    Iterator<Element> it = root.elementIterator(); it.hasNext();) {
        Element item = it.next();
        if (item.getNamespacePrefix() == "soapenv") {
            throw new Exception(item.getData().toString());
        }
        elementList.add(item);
    }

    return elementList;
}

From source file:com.openkm.openmeetings.service.RestService.java

/**
 * call// w ww .ja  va 2s  .  c  o  m
 * 
 * @param request
 * @param param
 * @return
 * @throws Exception
 */
public static Map<String, Element> callMap(String request, Object param) throws Exception {
    HttpClient client = new HttpClient();
    GetMethod method = null;
    try {
        method = new GetMethod(getEncodetURI(request).toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    int statusCode = 0;
    try {
        statusCode = client.executeMethod(method);
    } catch (HttpException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    } catch (IOException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    }

    switch (statusCode) {
    case 200: // OK
        break;
    case 400:
        throw new Exception(
                "Bad request. The parameters passed to the service did not match as expected. The Message should tell you what was missing or incorrect.");
    case 403:
        throw new Exception(
                "Forbidden. You do not have permission to access this resource, or are over your rate limit.");
    case 503:
        throw new Exception(
                "Service unavailable. An internal problem prevented us from returning data to you.");
    default:
        throw new Exception("Your call to OpenMeetings! Web Services returned an unexpected  HTTP status of: "
                + statusCode);
    }

    InputStream rstream = null;
    try {
        rstream = method.getResponseBodyAsStream();
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("No Response Body");
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    SAXReader reader = new SAXReader();
    Document document = null;
    String line;
    try {
        while ((line = br.readLine()) != null) {
            document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new Exception("UnsupportedEncodingException by SAXReader");
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("IOException by SAXReader in REST Service");
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new Exception("DocumentException by SAXReader in REST Service");
    } finally {
        br.close();
    }

    Element root = document.getRootElement();
    Map<String, Element> elementMap = new LinkedHashMap<String, Element>();

    for (@SuppressWarnings("unchecked")
    Iterator<Element> it = root.elementIterator(); it.hasNext();) {
        Element item = it.next();
        if (item.getNamespacePrefix() == "soapenv") {
            throw new Exception(item.getData().toString());
        }
        String nodeVal = item.getName();
        elementMap.put(nodeVal, item);
    }

    return elementMap;
}

From source file:jp.co.nssol.h5.test.selenium.base.H5TestCase.java

/**
 * webdrier_config.xml?testPageUrl????????????
 *
 * @param url//from  ww  w .java  2  s.  c  o  m
 */
protected static void show(String relativeUrl) {
    try {
        final URL url = new URL(new URL(TEST_PAGE_URL), relativeUrl);

        new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver d) {
                d.get(url.toString());
                return d.getCurrentUrl().equals(url.toString());
            }

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