Search in sources :

Example 21 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project felix by apache.

the class SessionHandlingTest method testSessionAttributes.

@Test
public void testSessionAttributes() throws Exception {
    setupContext("test1", "/");
    setupContext("test2", "/");
    setupLatches(2);
    setupServlet("foo", new String[] { "/foo" }, 1, "test1");
    setupServlet("bar", new String[] { "/bar" }, 2, "test2");
    assertTrue(initLatch.await(5, TimeUnit.SECONDS));
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(new BasicCookieStore()).build();
    JsonObject json;
    // session should not be available
    // check for foo servlet
    json = getJSONResponse(httpclient, "/foo");
    assertFalse(json.getBoolean("session"));
    // check for bar servlet
    json = getJSONResponse(httpclient, "/bar");
    assertFalse(json.getBoolean("session"));
    // create session for  context of servlet foo
    // check session and session attribute
    json = getJSONResponse(httpclient, "/foo?create=true");
    assertTrue(json.getBoolean("session"));
    assertEquals("test1", json.getString("value"));
    final String sessionId1 = json.getString("sessionId");
    assertNotNull(sessionId1);
    final String hashCode1 = json.getString("hashCode");
    assertNotNull(hashCode1);
    // check session for servlet bar (= no session)
    json = getJSONResponse(httpclient, "/bar");
    assertFalse(json.getBoolean("session"));
    // another request to servlet foo, still the same
    json = getJSONResponse(httpclient, "/foo");
    assertTrue(json.getBoolean("session"));
    assertEquals("test1", json.getString("value"));
    assertEquals(sessionId1, json.getString("sessionId"));
    // create session for second context
    json = getJSONResponse(httpclient, "/bar?create=true");
    assertTrue(json.getBoolean("session"));
    assertEquals("test2", json.getString("value"));
    final String sessionId2 = json.getString("sessionId");
    assertNotNull(sessionId2);
    final String hashCode2 = json.getString("hashCode");
    assertNotNull(hashCode2);
    assertFalse(hashCode2.equals(hashCode1));
    // and context foo is untouched
    json = getJSONResponse(httpclient, "/foo");
    assertTrue(json.getBoolean("session"));
    assertEquals("test1", json.getString("value"));
    assertEquals(sessionId1, json.getString("sessionId"));
    // invalidate session for foo context
    json = getJSONResponse(httpclient, "/foo?destroy=true");
    assertFalse(json.getBoolean("session"));
    // bar should be untouched
    json = getJSONResponse(httpclient, "/bar");
    assertTrue(json.getBoolean("session"));
    assertEquals("test2", json.getString("value"));
    assertEquals(sessionId2, json.getString("sessionId"));
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) JsonObject(javax.json.JsonObject) Test(org.junit.Test)

Example 22 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project open-kilda by telstra.

the class Mininet method simpleGet.

/**
 * Simple Http Get.
 *
 * @param path the path
 * @return the CloseableHttpResponse
 * @throws URISyntaxException the URI syntax exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MininetException the MininetException
 */
public CloseableHttpResponse simpleGet(String path) throws URISyntaxException, IOException, MininetException {
    URI uri = new URIBuilder().setScheme("http").setHost(mininetServerIP.toString()).setPort(mininetServerPort.getPort()).setPath(path).build();
    CloseableHttpClient client = HttpClientBuilder.create().build();
    RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT_MS).setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS).setSocketTimeout(CONNECTION_TIMEOUT_MS).build();
    HttpGet request = new HttpGet(uri);
    request.setConfig(config);
    request.addHeader("Content-Type", "application/json");
    CloseableHttpResponse response = client.execute(request);
    if (response.getStatusLine().getStatusCode() >= 300) {
        throw new MininetException(String.format("failure - received a %d for %s.", response.getStatusLine().getStatusCode(), request.getURI().toString()));
    }
    return response;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 23 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project open-kilda by telstra.

the class Mininet method simplePost.

/**
 * Simple Http Post.
 *
 * @param path the path
 * @param payload the payload
 * @return the closeable http response
 * @throws URISyntaxException the URI syntax exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MininetException the MininetException
 */
public CloseableHttpResponse simplePost(String path, String payload) throws URISyntaxException, IOException, MininetException {
    URI uri = new URIBuilder().setScheme("http").setHost(mininetServerIP.toString()).setPort(mininetServerPort.getPort()).setPath(path).build();
    CloseableHttpClient client = HttpClientBuilder.create().build();
    RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT_MS).setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS).setSocketTimeout(CONNECTION_TIMEOUT_MS).build();
    HttpPost request = new HttpPost(uri);
    request.setConfig(config);
    request.addHeader("Content-Type", "application/json");
    request.setEntity(new StringEntity(payload));
    CloseableHttpResponse response = client.execute(request);
    if (response.getStatusLine().getStatusCode() >= 300) {
        throw new MininetException(String.format("failure - received a %d for %s.", response.getStatusLine().getStatusCode(), request.getURI().toString()));
    }
    return response;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 24 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project swift by luastar.

the class HttpClientUtils method get.

public static String get(String url, int timeout, String charset, Map<String, String> headMap) {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        HttpGet httpGet = new HttpGet(url);
        // 超时设置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();
        httpGet.setConfig(requestConfig);
        // head设置
        if (headMap != null && !headMap.isEmpty()) {
            for (Map.Entry<String, String> entry : headMap.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }
        httpclient = createHttpClient(url);
        long start = System.currentTimeMillis();
        response = httpclient.execute(httpGet);
        long end = System.currentTimeMillis();
        int status = response.getStatusLine().getStatusCode();
        logger.info("请求url:{},结果状态:{},耗时:{}毫秒。", url, status, ((end - start)));
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity, charset) : null;
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
        org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpclient);
    }
    return null;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CertificateException(java.security.cert.CertificateException)

Example 25 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project opennms by OpenNMS.

the class GrafanaDashletConfigurationWindow method getGrafanaDashboards.

private Map<String, String> getGrafanaDashboards() throws GrafanaDashletException {
    /**
     * Loading the required properties...
     */
    final String grafanaApiKey = System.getProperty("org.opennms.grafanaBox.apiKey", "");
    final String grafanaProtocol = System.getProperty("org.opennms.grafanaBox.protocol", "http");
    final String grafanaHostname = System.getProperty("org.opennms.grafanaBox.hostname", "localhost");
    final int grafanaPort = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.port", "3000"));
    final int grafanaConnectionTimeout = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.connectionTimeout", "500"));
    final int grafanaSoTimeout = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.soTimeout", "500"));
    if (!"".equals(grafanaApiKey) && !"".equals(grafanaHostname) && !"".equals(grafanaProtocol) && ("http".equals(grafanaProtocol) || "https".equals(grafanaProtocol))) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(grafanaConnectionTimeout).setSocketTimeout(grafanaSoTimeout).build();
            final URI uri = new URIBuilder().setScheme(grafanaProtocol).setHost(grafanaHostname).setPort(grafanaPort).setPath("/api/search/").build();
            final HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(requestConfig);
            /**
             * Adding the API key...
             */
            httpGet.setHeader("Authorization", "Bearer " + grafanaApiKey);
            final Map<String, String> resultSet = new TreeMap<>();
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    /**
                     * Fill the result set...
                     */
                    final String responseString = IOUtils.toString(httpEntity.getContent(), StandardCharsets.UTF_8.name());
                    if (!Strings.isNullOrEmpty(responseString)) {
                        try {
                            final JSONArray arr = new JSONObject("{dashboards:" + responseString + "}").getJSONArray("dashboards");
                            for (int i = 0; i < arr.length(); i++) {
                                resultSet.put(arr.getJSONObject(i).getString("title"), arr.getJSONObject(i).getString("uri"));
                            }
                        } catch (JSONException e) {
                            throw new GrafanaDashletException(e.getMessage());
                        }
                    }
                }
            }
            return resultSet;
        } catch (Exception e) {
            throw new GrafanaDashletException(e.getMessage());
        }
    } else {
        throw new GrafanaDashletException("Invalid configuration");
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) TreeMap(java.util.TreeMap) URI(java.net.URI) JSONException(org.json.JSONException) URIBuilder(org.apache.http.client.utils.URIBuilder) JSONObject(org.json.JSONObject) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Aggregations

RequestConfig (org.apache.http.client.config.RequestConfig)344 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)146 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)97 HttpGet (org.apache.http.client.methods.HttpGet)94 IOException (java.io.IOException)78 HttpEntity (org.apache.http.HttpEntity)67 HttpPost (org.apache.http.client.methods.HttpPost)65 HttpResponse (org.apache.http.HttpResponse)60 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)55 URI (java.net.URI)46 StringEntity (org.apache.http.entity.StringEntity)43 Map (java.util.Map)41 Test (org.junit.Test)41 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)33 HttpHost (org.apache.http.HttpHost)32 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)32 HttpClient (org.apache.http.client.HttpClient)31 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)27 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)24 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)24