Example usage for java.net HttpURLConnection disconnect

List of usage examples for java.net HttpURLConnection disconnect

Introduction

In this page you can find the example usage for java.net HttpURLConnection disconnect.

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:jp.primecloud.auto.sdk.Requester.java

protected String request(String endpoint, Map<String, String> parameters) {
    String queryString = createQueryString(apiPath + endpoint, parameters);
    String url = this.url + apiPath + endpoint + "?" + queryString;

    log.trace("[API Request] " + url);

    HttpURLConnection connection;
    try {/*ww w.ja  v  a2s.  c o m*/
        connection = createConnection(url, options);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    try {
        int code = connection.getResponseCode();
        if (code != 200) {
            throw new RuntimeException(connection.getResponseMessage());
        }

        String body = IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8);

        log.trace("[API Response] " + body);

        return body;

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        connection.disconnect();
    }
}

From source file:org.elasticsearch.metrics.ElasticsearchReporter.java

/**
 * This index template is automatically applied to all indices which start with the index name
 * The index template simply configures the name not to be analyzed
 *//*ww w  . j  av  a  2s .co  m*/
private void checkForIndexTemplate() {
    try {
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        if (connection == null) {
            LOGGER.error("Could not connect to any configured elasticsearch instances: {}",
                    Arrays.asList(hosts));
            return;
        }
        connection.disconnect();

        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            if (putTemplateConnection == null) {
                LOGGER.error("Error adding metrics template to elasticsearch");
                return;
            }

            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != 200) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

From source file:co.cask.cdap.gateway.router.NettyRouterTestBase.java

@Test
public void testConnectionNoIdleTimeout() throws Exception {
    // even though the handler will sleep for 500ms over the configured idle timeout before responding, the connection
    // is not closed because the http request is in progress
    long timeoutMillis = TimeUnit.SECONDS.toMillis(CONNECTION_IDLE_TIMEOUT_SECS) + 500;
    URL url = new URL(resolveURI(Constants.Router.GATEWAY_DISCOVERY_NAME, "/v1/timeout/" + timeoutMillis));
    HttpURLConnection urlConnection = openURL(url);
    Assert.assertEquals(200, urlConnection.getResponseCode());
    urlConnection.disconnect();
}

From source file:com.oneops.metrics.es.ElasticsearchReporter.java

/**
 * This index template is automatically applied to all indices which start with the index name
 * The index template simply configures the name not to be analyzed
 *///from w  ww. ja  va2 s  .  c o  m
private void checkForIndexTemplate() {
    try {
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        if (connection == null) {
            LOGGER.error("Could not connect to any configured elasticsearch instances: {}",
                    Arrays.asList(hosts));
            return;
        }
        connection.disconnect();

        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != 200) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

From source file:com.boozallen.cognition.ingest.storm.bolt.geo.TwoFishesGeocodeBolt.java

/**
 * Submits a URL query string and builds a TwoFishesFeature for the result and all parents.
 *
 * @param query/*from  ww w .ja  v a2s  .c o  m*/
 * @return
 * @throws IOException
 * @throws ParseException
 */
private TwoFishesFeature[] submitQuery(String query) throws IOException, ParseException {
    URL url = new URL(query);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    if (conn.getResponseCode() != 200) {
        logger.error("Failed : HTTP error code : " + conn.getResponseCode() + ":" + url.toString());
        _failCount++;
        return null;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String jsonStr = br.readLine();
    br.close();
    conn.disconnect();

    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(jsonStr);
    JSONArray interpretations = (JSONArray) jsonObject.get("interpretations");

    if (interpretations.size() == 0) {
        //logger.warn("Twofishes unable to resolve location " + unresolvedLocation);
        _failCount++;
        return null;
    } else {
        if (interpretations.size() > 1) {
            //lat-long searches have multiple interpretations, e.g. city, county, state, country. most specific is first, so still use it.
            logger.debug("Twofishes has more than one interpretation of " + query);
        }
        JSONObject interpretation0 = (JSONObject) interpretations.get(0);

        //ArrayList of main result and parents
        ArrayList<JSONObject> features = new ArrayList<JSONObject>();
        JSONObject feature = (JSONObject) interpretation0.get("feature");

        //save main result
        features.add(feature);

        JSONArray parents = (JSONArray) interpretation0.get("parents");
        //get parents as feature JSONObjects
        for (int i = 0; i < parents.size(); i++) {
            JSONObject parentFeature = (JSONObject) parents.get(i);
            features.add(parentFeature);
        }

        //parse features and return
        TwoFishesFeature[] results = new TwoFishesFeature[features.size()];

        for (int i = 0; i < features.size(); i++) {
            JSONObject f = features.get(i);
            TwoFishesFeature result = new TwoFishesFeature();
            result.name = (String) f.get("name");
            result.countryCode = (String) f.get(CC);
            result.woeType = (long) f.get("woeType");
            JSONObject geometry = (JSONObject) f.get("geometry");
            JSONObject center = (JSONObject) geometry.get("center");
            result.lat = String.valueOf(center.get(LAT));
            result.lng = String.valueOf(center.get(LNG));
            results[i] = result;
        }

        _successCount++;
        return results;
    }

}

From source file:eu.optimis.mi.gui.server.MonitoringManagerWebServiceImpl.java

public String getIdMetricDateStrMonitoringResources(String id, String level, String metricName, String dfrom,
        String dto) {/*from  w  w  w .j a v  a 2 s  .  c  o  m*/
    String xml = new String("");

    String urlString = MMANAGER_URL + "QueryResources/date/metric/" + metricName + "/" + level + "/" + id + "/"
            + dfrom + "." + dto;
    logger.debug("Metric monitoring resource URL:" + urlString);
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/XML");

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

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        logger.debug("Output from Server... \n" + dfrom.toString());
        String li;
        while ((li = br.readLine()) != null) {
            xml = xml.concat(li);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
    return xml;
}

From source file:icevaluation.GetWikiURL.java

public String getWikiResults(String searchText, String bingAPIKey) {
    String search_results = null;
    //update key use by incrementing key use
    Integer n = keyMap.get(bingAPIKey);
    if (n == null) {
        n = 1;/*from  www  .j a  v a2 s  .c om*/
    } else {
        n = n + 1;
    }
    keyMap.put(bingAPIKey, n);

    searchText = searchText.replaceAll(" ", "%20");
    String accountKey = bingAPIKey;

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);
    URL url;
    try {
        url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27"
                + searchText + "%27&$format=JSON");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        //conn.addRequestProperty(accountKeyEnc, "Mozilla/4.76"); 
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String output = null;

        //System.out.println("Output from Server .... \n");
        //write json to string sb
        if ((output = br.readLine()) != null) {
            search_results = output;
        }

        conn.disconnect();
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return search_results;

}

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingEmptyQueryString() throws Exception {
    onRequest().havingQueryStringEqualTo("").havingQueryString(isEmptyString()).respond().withStatus(201);

    //it seems HttpClient cannot send a request with an empty query string ('?' as the last character)
    //let's test this in a more hardcore fashion
    final URL url = new URL("http://localhost:" + port() + "/?");
    final HttpURLConnection c = (HttpURLConnection) url.openConnection();

    assertThat(c.getResponseCode(), is(201));

    c.disconnect();
}

From source file:fr.gael.dhus.service.SystemService.java

/**
 * Performs a backup of Solr index.//from  w ww . ja v a2  s  . co  m
 * @param backupDirectory directory where put the backup.
 * @return true if backup is successful, otherwise false.
 */
private boolean backupSolr(final String backupDirectory) {
    StringBuilder request = new StringBuilder();
    request.append(cfgManager.getServerConfiguration().getUrl());
    request.append("/solr/dhus/replication?");
    request.append("command=backup&location=").append(backupDirectory);
    request.append("&name=").append(BACKUP_INDEX_NAME);

    try {
        URL url = new URL(request.toString());
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        InputStream input = con.getInputStream();
        StringBuilder response = new StringBuilder();
        byte[] buff = new byte[1024];
        int length;
        while ((length = input.read(buff)) != -1) {
            response.append(new String(buff, 0, length));
        }
        input.close();
        con.disconnect();
        logger.debug(response.toString());
    } catch (IOException e) {
        return Boolean.FALSE;
    }
    return Boolean.TRUE;
}

From source file:eu.optimis.mi.gui.server.MonitoringManagerWebServiceImpl.java

public List<MonitoringResource> getIdMetricDateListMonitoringResources(String id, String level,
        String metricName, String dfrom, String dto) {
    String xml = new String("");

    String urlString = MMANAGER_URL + "QueryResources/date/metric/" + metricName + "/" + level + "/" + id + "/"
            + dfrom + "." + dto;

    try {//from   ww w .jav  a  2 s  . c  o m
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/XML");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        System.out.println("Output from Server... \n" + dfrom.toString());
        String li;
        while ((li = br.readLine()) != null) {
            xml = xml.concat(li);
        }
        conn.disconnect();
    } catch (MalformedURLException e) {
        logger.debug("Could get resources from the URL:" + urlString);
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }
    XmlUtil util = new XmlUtil();
    List<MonitoringResource> list;
    if (xml != null && xml.contains("metric_name")) {
        list = util.getMonitoringRsModel(xml);
    } else {
        list = new ArrayList<MonitoringResource>();
    }
    return list;
}