Search in sources :

Example 36 with HttpURLConnection

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

the class TableViewsTest method testTableNotFound.

@Test(dataProvider = "stateProvider")
public void testTableNotFound(String state) throws IOException, JSONException {
    ControllerRequestURLBuilder requestBuilder = ControllerRequestURLBuilder.baseUrl(CONTROLLER_BASE_API_URL);
    String url = requestBuilder.forTableView("UNKNOWN_TABLE", state, null);
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    assertEquals(connection.getResponseCode(), 404);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ControllerRequestURLBuilder(com.linkedin.pinot.controller.helix.ControllerRequestURLBuilder) URL(java.net.URL) Test(org.testng.annotations.Test) ControllerTest(com.linkedin.pinot.controller.helix.ControllerTest)

Example 37 with HttpURLConnection

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

the class ControllerTest method sendDeleteRequest.

public static String sendDeleteRequest(String urlString) throws IOException {
    final long start = System.currentTimeMillis();
    final URL url = new URL(urlString);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("DELETE");
    conn.connect();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    final long stop = System.currentTimeMillis();
    LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start));
    return sb.toString();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) URL(java.net.URL)

Example 38 with HttpURLConnection

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

the class MifosExecutableWARBasicTest method testExecutableWARStartup.

@Test
public void testExecutableWARStartup() throws IOException, InterruptedException {
    // maven-dependency-plugin (see pom.xml) copied it:
    final File warFile = new File("target/dependency/mifos.war");
    assertTrue(warFile.toString() + " does not exist", warFile.exists());
    int httpPort = 4847;
    // Give it max. 5 min to start-up
    Long timeOut = 5 * 60 * 1000L;
    // Could have used http://commons.apache.org/exec/ instead here, but this seemed easier:
    long startTime = System.currentTimeMillis();
    final String execWARFilePath = warFile.getAbsolutePath();
    final String port = Integer.toString(httpPort);
    List<String> args = new ArrayList<String>();
    args.add("java");
    args.add("-jar");
    args.add("-Xmx512M");
    args.add("-XX:MaxPermSize=256m");
    if (System.getProperty("os.name").toLowerCase().contains("mac")) {
        args.add("-d32");
    }
    args.add(execWARFilePath);
    args.add(port);
    final ProcessBuilder processBuilder = new ProcessBuilder(args);
    processBuilder.redirectErrorStream(true);
    Process p = processBuilder.start();
    URL url = new URL("http://localhost:" + httpPort + "/mifos");
    // Now either wait until the server is up on httpPort OR timeOut is reached
    boolean keepGoing = true;
    InputStream is = p.getInputStream();
    do {
        // Pipe process output to console
        while (is.available() > 0) {
            System.out.write(is.read());
        }
        // Check if the server is up and running
        try {
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            int r = con.getResponseCode();
            if (r == 200 || r == 302) {
                // Yeah, we're up and running! So shutdown now.
                p.destroy();
                keepGoing = false;
            }
        } catch (ConnectException e) {
        // Oh well; not ready yet, never mind, ignore it and move on.
        }
        // Has the server died on it's own already may be?
        try {
            int exitValue = p.exitValue();
            if (exitValue != 0) {
                fail("Server Process died (unexpectedly), return code: " + exitValue);
            }
        } catch (IllegalThreadStateException e) {
        // Great, it's still running; so move on.
        }
        // Have we hit time out?
        if (System.currentTimeMillis() - startTime > timeOut) {
            p.destroy();
            fail("Giving up after " + timeOut + "ms; as Server Process is still not responding on " + url);
        }
        // Now have a rest before trying again
        Thread.sleep(1000);
    } while (keepGoing);
}
Also used : InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) File(java.io.File) ConnectException(java.net.ConnectException) Test(org.junit.Test)

Example 39 with HttpURLConnection

use of java.net.HttpURLConnection in project cordova-plugin-local-notifications by katzer.

the class AssetUtil method getUriFromRemote.

/**
     * Uri from remote located content.
     *
     * @param path
     *      Remote address
     *
     * @return
     *      Uri of the downloaded file
     */
private Uri getUriFromRemote(String path) {
    File file = getTmpFile();
    if (file == null) {
        Log.e("Asset", "Missing external cache dir");
        return Uri.EMPTY;
    }
    try {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        connection.setRequestProperty("Connection", "close");
        connection.setConnectTimeout(5000);
        connection.connect();
        InputStream input = connection.getInputStream();
        FileOutputStream outStream = new FileOutputStream(file);
        copyFile(input, outStream);
        outStream.flush();
        outStream.close();
        return Uri.fromFile(file);
    } catch (MalformedURLException e) {
        Log.e("Asset", "Incorrect URL");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Log.e("Asset", "Failed to create new File from HTTP Content");
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Asset", "No Input can be created from http Stream");
        e.printStackTrace();
    }
    return Uri.EMPTY;
}
Also used : StrictMode(android.os.StrictMode) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL)

Example 40 with HttpURLConnection

use of java.net.HttpURLConnection in project Android-ReactiveLocation by mcharmas.

the class FallbackReverseGeocodeObservable method alternativeReverseGeocodeQuery.

/**
     * This function fetches a list of addresses for the set latitude, longitude and maxResults properties from the
     * Google Geocode API (http://maps.googleapis.com/maps/api/geocode).
     *
     * @return List of addresses
     * @throws IOException   In case of network problems
     * @throws JSONException In case of problems while parsing the json response from google geocode API servers
     */
private List<Address> alternativeReverseGeocodeQuery() throws IOException, JSONException {
    URL url = new URL(String.format(Locale.ENGLISH, "http://maps.googleapis.com/maps/api/geocode/json?" + "latlng=%1$f,%2$f&sensor=true&language=%3$s", latitude, longitude, locale.getLanguage()));
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    StringBuilder stringBuilder = new StringBuilder();
    List<Address> outResult = new ArrayList<>();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        // Root json response object
        JSONObject jsonRootObject = new JSONObject(stringBuilder.toString());
        // No results status
        if ("ZERO_RESULTS".equalsIgnoreCase(jsonRootObject.getString("status"))) {
            return Collections.emptyList();
        }
        // Other non-OK responses status
        if (!"OK".equalsIgnoreCase(jsonRootObject.getString("status"))) {
            throw new RuntimeException("Wrong API response");
        }
        // Process results
        JSONArray results = jsonRootObject.getJSONArray("results");
        for (int i = 0; i < results.length() && i < maxResults; i++) {
            Address address = new Address(Locale.getDefault());
            String addressLineString = "";
            JSONObject sourceResult = results.getJSONObject(i);
            JSONArray addressComponents = sourceResult.getJSONArray("address_components");
            // Assemble address by various components
            for (int ac = 0; ac < addressComponents.length(); ac++) {
                String longNameVal = addressComponents.getJSONObject(ac).getString("long_name");
                String shortNameVal = addressComponents.getJSONObject(ac).getString("short_name");
                JSONArray acTypes = addressComponents.getJSONObject(ac).getJSONArray("types");
                String acType = acTypes.getString(0);
                if (!TextUtils.isEmpty(longNameVal)) {
                    if (acType.equalsIgnoreCase("street_number")) {
                        if (TextUtils.isEmpty(addressLineString)) {
                            addressLineString = longNameVal;
                        } else {
                            addressLineString += " " + longNameVal;
                        }
                    } else if (acType.equalsIgnoreCase("route")) {
                        if (TextUtils.isEmpty(addressLineString)) {
                            addressLineString = longNameVal;
                        } else {
                            addressLineString = longNameVal + " " + addressLineString;
                        }
                    } else if (acType.equalsIgnoreCase("sublocality")) {
                        address.setSubLocality(longNameVal);
                    } else if (acType.equalsIgnoreCase("locality")) {
                        address.setLocality(longNameVal);
                    } else if (acType.equalsIgnoreCase("administrative_area_level_2")) {
                        address.setSubAdminArea(longNameVal);
                    } else if (acType.equalsIgnoreCase("administrative_area_level_1")) {
                        address.setAdminArea(longNameVal);
                    } else if (acType.equalsIgnoreCase("country")) {
                        address.setCountryName(longNameVal);
                        address.setCountryCode(shortNameVal);
                    } else if (acType.equalsIgnoreCase("postal_code")) {
                        address.setPostalCode(longNameVal);
                    }
                }
            }
            // Try to get the already formatted address
            String formattedAddress = sourceResult.getString("formatted_address");
            if (!TextUtils.isEmpty(formattedAddress)) {
                String[] formattedAddressLines = formattedAddress.split(",");
                for (int ia = 0; ia < formattedAddressLines.length; ia++) {
                    address.setAddressLine(ia, formattedAddressLines[ia].trim());
                }
            } else if (!TextUtils.isEmpty(addressLineString)) {
                // If that fails use our manually assembled formatted address
                address.setAddressLine(0, addressLineString);
            }
            // Finally add address to resulting set
            outResult.add(address);
        }
    } finally {
        urlConnection.disconnect();
    }
    return Collections.unmodifiableList(outResult);
}
Also used : Address(android.location.Address) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.JSONObject) BufferedReader(java.io.BufferedReader)

Aggregations

HttpURLConnection (java.net.HttpURLConnection)3831 URL (java.net.URL)2447 IOException (java.io.IOException)1634 InputStream (java.io.InputStream)1082 InputStreamReader (java.io.InputStreamReader)692 Test (org.junit.Test)650 BufferedReader (java.io.BufferedReader)573 OutputStream (java.io.OutputStream)466 MalformedURLException (java.net.MalformedURLException)372 URLConnection (java.net.URLConnection)248 HashMap (java.util.HashMap)216 OutputStreamWriter (java.io.OutputStreamWriter)208 Map (java.util.Map)199 Gson (com.google.gson.Gson)190 ByteArrayOutputStream (java.io.ByteArrayOutputStream)186 ArrayList (java.util.ArrayList)168 ExecutionException (java.util.concurrent.ExecutionException)161 File (java.io.File)159 AsyncTask (android.os.AsyncTask)158 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)157