org.apache.http.client.fluent.Executor Java Examples

The following examples show how to use org.apache.http.client.fluent.Executor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClanService.java    From 07kit with GNU General Public License v3.0 9 votes vote down vote up
public static ClanInfo create(String loginName, String ingameName, String clanName, ClanRank.Status status, int world) {
    try {
        Request request = Request.Post(API_URL + "create");
        request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
        request.bodyString(GSON.toJson(new CreateUpdateClanRequest(loginName, ingameName, clanName, status, world)),
                ContentType.APPLICATION_JSON);

        HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return GSON.fromJson(new String(bytes), ClanInfo.class);
            } else if (response.getStatusLine().getStatusCode() == 302) {
                NotificationsUtil.showNotification("Clan", "That clan name is taken");
            } else {
                NotificationsUtil.showNotification("Clan", "Error creating clan");
            }
        }
        return null;
    } catch (IOException e) {
        logger.error("Error creating clan", e);
        return null;
    }
}
 
Example #2
Source File: RedissonSessionManagerTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdate() throws Exception {
    // start the server at http://localhost:8080/myapp
    TomcatServer server = new TomcatServer("myapp", 8080, "src/test/");
    server.start();

    Executor executor = Executor.newInstance();
    
    write(executor, "test", "1");
    read(executor, "test", "1");
    write(executor, "test", "2");
    read(executor, "test", "2");
    
    Executor.closeIdleConnections();
    server.stop();
}
 
Example #3
Source File: StreamingAnalyticsServiceV2.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
@Override
protected List<File> downloadArtifacts(CloseableHttpClient httpclient, JsonArray artifacts) {
    final List<File> files = new ArrayList<>();
    for (JsonElement ae : artifacts) {
        JsonObject artifact = ae.getAsJsonObject();
        if (!artifact.has("download"))
            continue;
        
        String name = jstring(artifact, "name");
        String url = jstring(artifact, "download");
       
        // Don't fail the submit if we fail to download the sab(s).
        try {
            File target = new File(name);
            StreamsRestUtils.getFile(Executor.newInstance(httpclient), getAuthorization(), url, target);
            files.add(target);
        } catch (IOException e) {
            TRACE.warning("Failed to download sab: " + name + " : " + e.getMessage());
        }
    }
    return files;
}
 
Example #4
Source File: RedissonSessionManagerTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateTwoServers() throws Exception {
    TomcatServer server1 = new TomcatServer("myapp", 8080, "src/test/");
    server1.start();

    Executor executor = Executor.newInstance();
    BasicCookieStore cookieStore = new BasicCookieStore();
    executor.use(cookieStore);
    
    write(executor, "test", "1234");

    TomcatServer server2 = new TomcatServer("myapp", 8081, "src/test/");
    server2.start();

    read(8081, executor, "test", "1234");
    read(executor, "test", "1234");
    write(executor, "test", "324");
    read(8081, executor, "test", "324");
    
    Executor.closeIdleConnections();
    server1.stop();
    server2.stop();
}
 
Example #5
Source File: CompletedOfferRecorder.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
private void processQueue() {
	Request next = requestQueue.poll();
	while (next != null) {
		try {
			HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(next).returnResponse();
			if (response != null) {
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					logger.info("Processed request [" + next.toString() + "]");
				} else {
					logger.error("Error processing request queue got rsponse [" + response.toString() + "]");
				}
			}
		} catch (IOException e) {
			logger.error("Error processing request queue", e);
		}
		next = requestQueue.poll();
	}
}
 
Example #6
Source File: StandaloneAuthenticator.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
private void refreshAuth(Executor executor, JsonObject config) throws IOException {
    Request post = Request.Post(securityUrl)
            .addHeader("Authorization", RestUtils.createBasicAuth(userName, password))
            .addHeader("Accept", ContentType.APPLICATION_JSON.getMimeType())
            .bodyString(AUDIENCE_STREAMS, ContentType.APPLICATION_JSON);

    JsonObject resp = RestUtils.requestGsonResponse(executor, post);
    String token = jstring(resp, ACCESS_TOKEN);
    serviceAuth = token == null ? null : RestUtils.createBearerAuth(token);
    if (resp.has(EXPIRE_TIME)) {
        JsonElement je = resp.get(EXPIRE_TIME);
        // Response is in seconds since epoch, and docs say the min
        // for the service is 30s, so give a 10s of slack if we can
        expire = je.isJsonNull() ? 0 : Math.max(0, je.getAsLong() - 10) * MS;
    } else {
        // Short expiry (same as python)
        expire = System.currentTimeMillis() + 4 * 60 * MS;
    }

    // Update config
    config.addProperty(SERVICE_TOKEN, token);
    config.addProperty(SERVICE_TOKEN_EXPIRE, expire);
}
 
Example #7
Source File: RedissonSessionManagerTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateTwoServers() throws Exception {
    TomcatServer server1 = new TomcatServer("myapp", 8080, "src/test/");
    server1.start();

    Executor executor = Executor.newInstance();
    BasicCookieStore cookieStore = new BasicCookieStore();
    executor.use(cookieStore);
    
    write(executor, "test", "1234");

    TomcatServer server2 = new TomcatServer("myapp", 8081, "src/test/");
    server2.start();

    read(8081, executor, "test", "1234");
    read(executor, "test", "1234");
    write(executor, "test", "324");
    read(8081, executor, "test", "324");
    
    Executor.closeIdleConnections();
    server1.stop();
    server2.stop();
}
 
Example #8
Source File: HttpsTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
public void hello() throws IOException, GeneralSecurityException {
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
            .build();
    try (CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLContext(sslContext)
            .build()) {

        String response = Executor.newInstance(httpClient)
                .execute(Request.Get("https://localhost:8443/"))
                .returnContent().asString();
        assertThat(response).contains("Hello on port 8443, secure: true");
    }
}
 
Example #9
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
static File getFile(Executor executor, String auth, String url, File file) throws IOException {
    return rawStreamingGet(executor, auth, url, new InputStreamConsumer<File>() {

        @Override
        public void consume(InputStream is) throws IOException {
            try {
                Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
            catch(IOException ioe) {
                if (file.delete()) {
                    TRACE.fine("downloaded fragment " + file + " deleted");
                }
                throw ioe;
            }
        }

        @Override
        public File getResult() {
            return file;
        }
    });
}
 
Example #10
Source File: RedissonSessionManagerTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
public void testExpiration() throws Exception {
    TomcatServer server1 = new TomcatServer("myapp", 8080, "src/test/");
    server1.start();

    Executor executor = Executor.newInstance();
    BasicCookieStore cookieStore = new BasicCookieStore();
    executor.use(cookieStore);
    
    write(executor, "test", "1234");

    TomcatServer server2 = new TomcatServer("myapp", 8081, "src/test/");
    server2.start();

    Thread.sleep(30000);
    
    read(8081, executor, "test", "1234");

    Thread.sleep(40000);
    
    executor.use(cookieStore);
    read(executor, "test", "1234");
    
    Executor.closeIdleConnections();
    server1.stop();
    server2.stop();
}
 
Example #11
Source File: PriceLookup.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
public static List<PriceInfo> search(String term, int limit) {
	try {
		Request request = Request.Get(API_URL + "search?term=" + URLEncoder.encode(term, "UTF-8") + "&limit=" + limit);
		request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());

		HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
		if (response != null) {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				byte[] bytes = EntityUtils.toByteArray(response.getEntity());
				return GSON.fromJson(new String(bytes), PRICE_INFO_LIST_TYPE);
			}
		}
		return new ArrayList<>();
	} catch (IOException | CacheLoader.InvalidCacheLoadException e) {
		e.printStackTrace();
		return new ArrayList<>();
	}
}
 
Example #12
Source File: StreamsBuildService.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
static BuildService of(Function<Executor,String> authenticator, JsonObject serviceDefinition,
        boolean verify) throws IOException {

    String buildServiceEndpoint = jstring(object(serviceDefinition, "connection_info"), "serviceBuildEndpoint");
    String buildServicePoolsEndpoint = jstring(object(serviceDefinition, "connection_info"), "serviceBuildPoolsEndpoint");
    // buildServicePoolsEndpoint is null when "connection_info" JSON element has no "serviceBuildPoolsEndpoint"
    if (authenticator instanceof StandaloneAuthenticator) {
        if (buildServiceEndpoint == null) {
            buildServiceEndpoint = Util.getenv(Util.STREAMS_BUILD_URL);
        }
        if (!buildServiceEndpoint.endsWith(STREAMS_BUILD_PATH)) {
            // URL was user-provided root of service, add the path
            URL url = new URL(buildServiceEndpoint);
            URL buildsUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), STREAMS_BUILD_PATH);
            buildServiceEndpoint = buildsUrl.toExternalForm();
        }
        return StreamsBuildService.of(authenticator, buildServiceEndpoint, verify);
    }
    return new StreamsBuildService(buildServiceEndpoint, buildServicePoolsEndpoint, authenticator, verify);
}
 
Example #13
Source File: RedissonSessionManagerTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdate() throws Exception {
    // start the server at http://localhost:8080/myapp
    TomcatServer server = new TomcatServer("myapp", 8080, "src/test/");
    server.start();

    Executor executor = Executor.newInstance();
    
    write(executor, "test", "1");
    read(executor, "test", "1");
    write(executor, "test", "2");
    read(executor, "test", "2");
    
    Executor.closeIdleConnections();
    server.stop();
}
 
Example #14
Source File: BaseParser.java    From substitution-schedule-parser with Mozilla Public License 2.0 6 votes vote down vote up
BaseParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) {
    this.scheduleData = scheduleData;
    this.cookieProvider = cookieProvider;
    this.cookieStore = new BasicCookieStore();
    this.colorProvider = new ColorProvider(scheduleData);
    this.encodingDetector = new UniversalDetector(null);
    this.debuggingDataHandler = new NoOpDebuggingDataHandler();
    this.sardine = null;

    try {
        SSLConnectionSocketFactory sslsf = getSslConnectionSocketFactory(scheduleData);

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD).build())
                .setUserAgent(
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36")
                .build();
        this.executor = Executor.newInstance(httpclient).use(cookieStore);
    } catch (GeneralSecurityException | JSONException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: GogsConfigHandler.java    From gogs-webhook-plugin with MIT License 6 votes vote down vote up
/**
 * Get Access token of the user.
 *
 * @return an access token of the user
 */
public String getGogsAccessToken() {
    String resp;
    String sha1 = null;
    Executor executor = getExecutor();
    try {
        resp = executor.execute(
                Request.Get(this.getGogsUrl() + "/api/v1/users/" + this.gogsServer_user + "/tokens")
        ).returnContent().toString();
        JSONArray jsonArray = JSONArray.fromObject(resp);
        if (!jsonArray.isEmpty()) {
            sha1 = ((JSONObject) jsonArray.get(0)).getString("sha1");
        }
    } catch (IOException e) { }
    return sha1;
}
 
Example #16
Source File: RedissonSessionManagerTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdate() throws Exception {
    // start the server at http://localhost:8080/myapp
    TomcatServer server = new TomcatServer("myapp", 8080, "src/test/");
    server.start();

    Executor executor = Executor.newInstance();
    
    write(executor, "test", "1");
    read(executor, "test", "1");
    write(executor, "test", "2");
    read(executor, "test", "2");
    
    Executor.closeIdleConnections();
    server.stop();
}
 
Example #17
Source File: GogsConfigHandler.java    From gogs-webhook-plugin with MIT License 6 votes vote down vote up
/**
 * Creates a web hook in Gogs with the passed json configuration string
 *
 * @param jsonCommand A json buffer with the creation command of the web hook
 * @param projectName the project (owned by the user) where the webHook should be created
 * @throws IOException something went wrong
 */
int createWebHook(String jsonCommand, String projectName) throws IOException {

    String gogsHooksConfigUrl = getGogsServer_apiUrl()
            + "repos/" + this.gogsServer_user
            + "/" + projectName + "/hooks";

    Executor executor = getExecutor();
    Request request = Request.Post(gogsHooksConfigUrl);

    if (gogsAccessToken != null) {
        request.addHeader("Authorization", "token " + gogsAccessToken);
    }

    String result = executor
            .execute(request.bodyString(jsonCommand, ContentType.APPLICATION_JSON))
            .returnContent().asString();
    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( result );
    return jsonObject.getInt("id");
}
 
Example #18
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON response to an HTTP GET call
 * 
 * @param executor HTTP client executor to use for call
 * @param auth Authentication header contents, or null
 * @param inputString
 *            REST call to make
 * @return response from the inputString
 * @throws IOException
 */
static JsonObject getGsonResponse(Executor executor, String auth, String inputString)
        throws IOException {
    TRACE.fine("HTTP GET: " + inputString);
    Request request = Request.Get(inputString).useExpectContinue();

    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }

    return requestGsonResponse(executor, request);
}
 
Example #19
Source File: RedissonSessionManagerTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpiration() throws Exception {
    TomcatServer server1 = new TomcatServer("myapp", 8080, "src/test/");
    server1.start();

    Executor executor = Executor.newInstance();
    BasicCookieStore cookieStore = new BasicCookieStore();
    executor.use(cookieStore);
    
    write(executor, "test", "1234");

    TomcatServer server2 = new TomcatServer("myapp", 8081, "src/test/");
    server2.start();

    Thread.sleep(30000);
    
    read(8081, executor, "test", "1234");

    Thread.sleep(40000);
    
    executor.use(cookieStore);
    read(executor, "test", "1234");
    
    Executor.closeIdleConnections();
    server1.stop();
    server2.stop();
}
 
Example #20
Source File: BuildService.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
public static BuildService ofServiceDefinition(JsonObject serviceDefinition,
        boolean verify) throws IOException {
    String name = jstring(serviceDefinition, "service_name");
    Function<Executor,String> authenticator;
    if (name == null) {
        authenticator = StandaloneAuthenticator.of(serviceDefinition);
    } else {
        authenticator = ICP4DAuthenticator.of(serviceDefinition);
    }

    return StreamsBuildService.of(authenticator, serviceDefinition, verify);
}
 
Example #21
Source File: StreamsBuildService.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
static BuildService of(Function<Executor,String> authenticator, String buildServiceEndpoint,
        boolean verify) throws IOException {

    if (buildServiceEndpoint == null) {
        buildServiceEndpoint = Util.getenv(Util.STREAMS_BUILD_URL);
        if (!buildServiceEndpoint.endsWith(STREAMS_BUILD_PATH)) {
            // URL was user-provided root of service, add the path
            URL url = new URL(buildServiceEndpoint);
            URL buildsUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), STREAMS_BUILD_PATH);
            buildServiceEndpoint = buildsUrl.toExternalForm();
        }
    }
    return new StreamsBuildService(buildServiceEndpoint, null, authenticator, verify);
}
 
Example #22
Source File: RestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON response to an HTTP GET call
 * 
 * @param executor HTTP client executor to use for call
 * @param auth Authentication header contents, or null
 * @param inputString
 *            REST call to make
 * @return response from the inputString
 * @throws IOException
 */
static JsonObject getGsonResponse(Executor executor, String auth, String url)
        throws IOException {
    TRACE.fine("HTTP GET: " + url);
    Request request = Request.Get(url).useExpectContinue();
    
    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }
    
    return requestGsonResponse(executor, request);
}
 
Example #23
Source File: LoginHandlerTest.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testBasicAuth() throws JSONException, IOException, CredentialInvalidException {
    stubBasicAuth();
    Executor exec = newExecutor();

    LoginHandler handler = new LoginHandler(dataBasic, correct, null);
    handler.handleLogin(exec, null);

    // loading page should succeed
    int status = exec.execute(Request.Get(baseurl + "/index.html")).returnResponse().getStatusLine()
            .getStatusCode();
    assertEquals(200, status);
}
 
Example #24
Source File: UnfollowRedirectTest.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotFollowRedirect() throws Exception {
    wireMockRule.stubFor(get("/redirect").willReturn(permanentRedirect("http://localhost:" + wireMockRule.port() + "/final")));

    HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();

    Request request = Request.Get("http://localhost:8082/api/redirect");
    Response response = Executor.newInstance(client).execute(request);
    HttpResponse returnResponse = response.returnResponse();

    assertEquals(HttpStatus.SC_MOVED_PERMANENTLY, returnResponse.getStatusLine().getStatusCode());

    wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/redirect")));
    wireMockRule.verify(0, getRequestedFor(urlPathEqualTo("/final")));
}
 
Example #25
Source File: LoginHandlerTest.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testPostAuthFormData() throws JSONException, IOException, CredentialInvalidException {
    stubPostAuthFormData();
    Executor exec = newExecutor();

    LoginHandler handler = new LoginHandler(dataPostFormData, correct, null);
    handler.handleLogin(exec, null);

    // loading page should succeed
    String content = exec.execute(Request.Get(baseurl + "/index.html")).returnContent().asString();
    assertEquals("content", content);
}
 
Example #26
Source File: LoginHandlerTest.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Test(expected = CredentialInvalidException.class)
public void testPostAuthFailCheckText() throws JSONException, IOException, CredentialInvalidException {
    stubPostAuth();
    Executor exec = newExecutor();

    LoginHandler handler = new LoginHandler(dataPostCheckText, wrong, null);
    handler.handleLogin(exec, null); // should throw CredentialInvalidException
}
 
Example #27
Source File: LoginHandlerTest.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testPostAuthFail() throws JSONException, IOException, CredentialInvalidException {
    stubPostAuth();
    Executor exec = newExecutor();

    LoginHandler handler = new LoginHandler(dataPost, wrong, null);
    handler.handleLogin(exec, null);

    // loading page should fail
    String content = exec.execute(Request.Get(baseurl + "/index.html")).returnContent().asString();
    assertEquals("please login", content);
}
 
Example #28
Source File: LoginHandlerTest.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Test(expected = CredentialInvalidException.class)
public void testBasicAuthFailUrl() throws JSONException, IOException, CredentialInvalidException {
    stubBasicAuth();
    Executor exec = newExecutor();

    LoginHandler handler = new LoginHandler(dataBasicUrl, wrong, null);
    handler.handleLogin(exec, null);
}
 
Example #29
Source File: LoginHandlerTest.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testBasicAuthFail() throws JSONException, IOException, CredentialInvalidException {
    stubBasicAuth();
    Executor exec = newExecutor();

    LoginHandler handler = new LoginHandler(dataBasic, wrong, null);
    handler.handleLogin(exec, null);

    // loading page should succeed
    int status = exec.execute(Request.Get(baseurl + "/index.html")).returnResponse().getStatusLine()
            .getStatusCode();
    assertEquals(401, status);
}
 
Example #30
Source File: SocialService.java    From 07kit with GNU General Public License v3.0 5 votes vote down vote up
public UserCharacter getCharacter(String hash) throws IOException {
    HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(Request.Get(CHARACTERS_ENDPOINT + "?hash=" + hash)
            .addHeader("Authorization", "Bearer " + Session.get().getApiToken())
    ).returnResponse();
    if (response.getStatusLine().getStatusCode() == 200) {
        return gson.fromJson(EntityUtils.toString(response.getEntity()), UserCharacter.class);
    } else if (response.getStatusLine().getStatusCode() == 404) {
        return null;
    } else {
        throw new IllegalStateException(String.format("Couldn't retrieve character for hash %s: %d", hash, response.getStatusLine().getStatusCode()));
    }
}