Search in sources :

Example 11 with URLConnection

use of java.net.URLConnection in project hudson-2.x by hudson.

the class Launcher method parseJnlpArguments.

/**
     * Parses the connection arguments from JNLP file given in the URL.
     */
public List<String> parseJnlpArguments() throws ParserConfigurationException, SAXException, IOException, InterruptedException {
    while (true) {
        try {
            URLConnection con = slaveJnlpURL.openConnection();
            if (con instanceof HttpURLConnection && slaveJnlpCredentials != null) {
                HttpURLConnection http = (HttpURLConnection) con;
                String userPassword = slaveJnlpCredentials;
                String encoding = new String(Base64.encodeBase64(userPassword.getBytes()));
                http.setRequestProperty("Authorization", "Basic " + encoding);
            }
            con.connect();
            if (con instanceof HttpURLConnection) {
                HttpURLConnection http = (HttpURLConnection) con;
                if (http.getResponseCode() >= 400)
                    // got the error code. report that (such as 401)
                    throw new IOException("Failed to load " + slaveJnlpURL + ": " + http.getResponseCode() + " " + http.getResponseMessage());
            }
            Document dom;
            // check if this URL points to a .jnlp file
            String contentType = con.getHeaderField("Content-Type");
            if (contentType == null || !contentType.startsWith("application/x-java-jnlp-file")) {
                // load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
                try {
                    dom = loadDom(slaveJnlpURL, con);
                } catch (SAXException e) {
                    throw new IOException(slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                } catch (IOException e) {
                    throw new IOException(slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                }
            } else {
                dom = loadDom(slaveJnlpURL, con);
            }
            // exec into the JNLP launcher, to fetch the connection parameter through JNLP.
            NodeList argElements = dom.getElementsByTagName("argument");
            List<String> jnlpArgs = new ArrayList<String>();
            for (int i = 0; i < argElements.getLength(); i++) jnlpArgs.add(argElements.item(i).getTextContent());
            if (slaveJnlpCredentials != null) {
                jnlpArgs.add("-credentials");
                jnlpArgs.add(slaveJnlpCredentials);
            }
            // force a headless mode
            jnlpArgs.add("-headless");
            return jnlpArgs;
        } catch (SSLHandshakeException e) {
            if (e.getMessage().contains("PKIX path building failed")) {
                // invalid SSL certificate. One reason this happens is when the certificate is self-signed
                IOException x = new IOException("Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
                x.initCause(e);
                throw x;
            } else
                throw e;
        } catch (IOException e) {
            System.err.println("Failing to obtain " + slaveJnlpURL);
            e.printStackTrace(System.err);
            System.err.println("Waiting 10 seconds before retry");
            Thread.sleep(10 * 1000);
        // retry
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SAXException(org.xml.sax.SAXException)

Example 12 with URLConnection

use of java.net.URLConnection in project pinot by linkedin.

the class ControllerTest method getDebugInfo.

public JSONObject getDebugInfo(final String uri) throws Exception {
    final URLConnection conn = new URL(BROKER_BASE_API_URL + "/" + uri).openConnection();
    conn.setDoOutput(true);
    return getBrokerReturnJson(conn);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) URL(java.net.URL)

Example 13 with URLConnection

use of java.net.URLConnection in project pinot by linkedin.

the class ControllerTest method postQuery.

public JSONObject postQuery(String query, String brokerBaseApiUrl) throws Exception {
    final JSONObject json = new JSONObject();
    json.put("pql", query);
    json.put("trace", isTraceEnabled);
    //    json.put("debugOptions", "routingOptions=FORCE_LLC,FORCE_HLC;otherOption=foo,bar");
    final long start = System.currentTimeMillis();
    final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection();
    conn.setDoOutput(true);
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    final String reqStr = json.toString();
    writer.write(reqStr, 0, reqStr.length());
    writer.flush();
    JSONObject ret = getBrokerReturnJson(conn);
    final long stop = System.currentTimeMillis();
    LOGGER.debug("Time taken for '{}':{}ms", query, (stop - start));
    return ret;
}
Also used : JSONObject(org.json.JSONObject) OutputStreamWriter(java.io.OutputStreamWriter) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter)

Example 14 with URLConnection

use of java.net.URLConnection in project head by mifos.

the class UTF8Control method newBundle.

public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    // The below is a copy of the default implementation.
    String bundleName = toBundleName(baseName, locale);
    String resourceName = toResourceName(bundleName, "properties");
    ResourceBundle bundle = null;
    InputStream stream = null;
    if (reload) {
        URL url = loader.getResource(resourceName);
        if (url != null) {
            URLConnection connection = url.openConnection();
            if (connection != null) {
                connection.setUseCaches(false);
                stream = connection.getInputStream();
            }
        }
    } else {
        stream = loader.getResourceAsStream(resourceName);
    }
    if (stream != null) {
        try {
            // Only this line is changed to make it to read properties files as UTF-8.
            bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
        } finally {
            stream.close();
        }
    }
    return bundle;
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) ResourceBundle(java.util.ResourceBundle) PropertyResourceBundle(java.util.PropertyResourceBundle) URL(java.net.URL) URLConnection(java.net.URLConnection) PropertyResourceBundle(java.util.PropertyResourceBundle)

Example 15 with URLConnection

use of java.net.URLConnection in project c-geo by just-radovan.

the class cgeoauth method requestToken.

private void requestToken() {
    final String host = "twitter.com";
    final String pathRequest = "/oauth/request_token";
    final String pathAuthorize = "/oauth/authorize";
    final String method = "GET";
    int status = 0;
    try {
        String lineOne = null;
        HttpsURLConnection connection = null;
        try {
            final StringBuilder sb = new StringBuilder();
            final String params = cgOAuth.signOAuth(host, pathRequest, method, true, new HashMap<String, String>(), null, null);
            int code = -1;
            int retries = 0;
            do {
                // base.trustAllHosts();
                Log.d(cgSettings.tag, "https://" + host + pathRequest + "?" + params);
                final URL u = new URL("https://" + host + pathRequest + "?" + params);
                final URLConnection uc = u.openConnection();
                connection = (HttpsURLConnection) uc;
                // connection.setHostnameVerifier(base.doNotVerify);
                connection.setReadTimeout(30000);
                connection.setRequestMethod(method);
                HttpsURLConnection.setFollowRedirects(true);
                connection.setDoInput(true);
                connection.setDoOutput(false);
                final InputStream in = connection.getInputStream();
                final InputStreamReader ins = new InputStreamReader(in);
                final BufferedReader br = new BufferedReader(ins);
                while ((lineOne = br.readLine()) != null) {
                    sb.append(lineOne);
                    sb.append("\n");
                }
                code = connection.getResponseCode();
                retries++;
                Log.i(cgSettings.tag, host + ": " + connection.getResponseCode() + " " + connection.getResponseMessage());
                br.close();
                in.close();
                ins.close();
            } while (code == -1 && retries < 5);
            final String line = sb.toString();
            if (line != null && line.length() > 0) {
                final Matcher paramsMatcher1 = paramsPattern1.matcher(line);
                if (paramsMatcher1.find() == true && paramsMatcher1.groupCount() > 0) {
                    OAtoken = paramsMatcher1.group(1).toString();
                }
                final Matcher paramsMatcher2 = paramsPattern2.matcher(line);
                if (paramsMatcher2.find() == true && paramsMatcher2.groupCount() > 0) {
                    OAtokenSecret = paramsMatcher2.group(1).toString();
                }
                if (OAtoken != null && OAtoken.length() > 0 && OAtokenSecret != null && OAtokenSecret.length() > 0) {
                    final SharedPreferences.Editor prefsEdit = getSharedPreferences(cgSettings.preferences, 0).edit();
                    prefsEdit.putString("temp-token-public", OAtoken);
                    prefsEdit.putString("temp-token-secret", OAtokenSecret);
                    prefsEdit.commit();
                    try {
                        final HashMap<String, String> paramsPre = new HashMap<String, String>();
                        paramsPre.put("oauth_callback", "oob");
                        final String paramsBrowser = cgOAuth.signOAuth(host, pathAuthorize, "GET", true, paramsPre, OAtoken, OAtokenSecret);
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + host + pathAuthorize + "?" + paramsBrowser)));
                        status = 1;
                    } catch (Exception e) {
                        Log.e(cgSettings.tag, "cgeoauth.requestToken(2): " + e.toString());
                    }
                }
            }
        } catch (IOException eio) {
            Log.e(cgSettings.tag, "cgeoauth.requestToken(IO): " + eio.toString() + " ~ " + connection.getResponseCode() + ": " + connection.getResponseMessage());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoauth.requestToken(1): " + e.toString());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    } catch (Exception e2) {
        Log.e(cgSettings.tag, "cgeoauth.requestToken(3): " + e2.toString());
    }
    requestTokenHandler.sendEmptyMessage(status);
}
Also used : InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) SharedPreferences(android.content.SharedPreferences) HashMap(java.util.HashMap) InputStream(java.io.InputStream) Intent(android.content.Intent) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Aggregations

URLConnection (java.net.URLConnection)1686 URL (java.net.URL)1180 IOException (java.io.IOException)740 InputStream (java.io.InputStream)569 HttpURLConnection (java.net.HttpURLConnection)465 InputStreamReader (java.io.InputStreamReader)404 BufferedReader (java.io.BufferedReader)358 Test (org.junit.Test)206 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)202 File (java.io.File)196 MalformedURLException (java.net.MalformedURLException)190 BufferedInputStream (java.io.BufferedInputStream)119 FileOutputStream (java.io.FileOutputStream)112 OutputStream (java.io.OutputStream)112 FileInputStream (java.io.FileInputStream)111 JarURLConnection (java.net.JarURLConnection)106 ArrayList (java.util.ArrayList)92 MockResponse (okhttp3.mockwebserver.MockResponse)76 ByteArrayOutputStream (java.io.ByteArrayOutputStream)74 FileNotFoundException (java.io.FileNotFoundException)59