下面列出了org.apache.http.client.fluent.Executor 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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<>();
}
}
@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();
}
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();
}
}
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;
}
}
@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();
}
/**
* 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");
}
/**
* 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;
}
@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");
}
}
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);
}
}
@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();
}
@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();
}
@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;
}
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);
}
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;
}
});
}
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();
}
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);
}
@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();
}
@Test
public void testHttpSessionListener() throws Exception {
TomcatServer server1 = new TomcatServer("myapp", 8080, "src/test/");
server1.start();
TomcatServer server2 = new TomcatServer("myapp", 8081, "src/test/");
server2.start();
Executor executor = Executor.newInstance();
BasicCookieStore cookieStore = new BasicCookieStore();
executor.use(cookieStore);
TestHttpSessionListener.CREATED_INVOCATION_COUNTER = 0;
TestHttpSessionListener.DESTROYED_INVOCATION_COUNTER = 0;
write(executor, "test", "1234");
TomcatServer server3 = new TomcatServer("myapp", 8082, "src/test/");
server3.start();
invalidate(executor);
Thread.sleep(500);
Assert.assertEquals(2, TestHttpSessionListener.CREATED_INVOCATION_COUNTER);
Assert.assertEquals(3, TestHttpSessionListener.DESTROYED_INVOCATION_COUNTER);
Executor.closeIdleConnections();
server1.stop();
server2.stop();
server3.stop();
}
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()));
}
}
public UserCharacter createCharacter(String name, String hash) throws IOException {
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(Request.Post(CHARACTERS_ENDPOINT)
.addHeader("Authorization", "Bearer " + Session.get().getApiToken())
.bodyString(gson.toJson(new UserCharacter(name, hash)), ContentType.APPLICATION_JSON)
).returnResponse();
if (response.getStatusLine().getStatusCode() == 200) {
return gson.fromJson(EntityUtils.toString(response.getEntity()), UserCharacter.class);
} else {
throw new IllegalStateException(String.format("Couldn't create character for hash %s: %d", hash, response.getStatusLine().getStatusCode()));
}
}
public UserCharacter updateCharacter(UserCharacter character) throws IOException {
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(Request.Put(String.format(CHARACTER_ENDPOINT, character.id))
.addHeader("Authorization", "Bearer " + Session.get().getApiToken())
.bodyString(gson.toJson(character), ContentType.APPLICATION_JSON)
).returnResponse();
if (response.getStatusLine().getStatusCode() == 200) {
return gson.fromJson(EntityUtils.toString(response.getEntity()), UserCharacter.class);
} else {
throw new IllegalStateException(String.format("Couldn't update character for id %d: %d", character.id, response.getStatusLine().getStatusCode()));
}
}
public void uploadScreenshotEvent(EventForm eventForm, ScreenshotForm form, Consumer<Boolean> callback) {
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("name", form.name)
.addTextBody("description", form.description)
.addTextBody("locationX", String.valueOf(form.locationX))
.addTextBody("locationY", String.valueOf(form.locationY))
.addTextBody("created", String.valueOf(form.created.getTime()))
.addBinaryBody("file", form.file, ContentType.create("image/png"), form.file.getName())
.build();
new Thread(socialThreadGroup, () -> {
try {
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(Request.Post(String.format(CHARACTER_SCREENSHOT_ENDPOINT, Session.get().getCharacter().id))
.addHeader("Authorization", "Bearer " + Session.get().getApiToken())
.body(entity)).returnResponse();
if (response.getStatusLine().getStatusCode() == 200) {
Map responseBody = gson.fromJson(EntityUtils.toString(response.getEntity()), Map.class);
eventForm.screenshotId = ((Number) responseBody.get("id")).longValue();
createEvent(eventForm, callback);
} else {
callback.accept(false);
}
} catch (Exception e) {
callback.accept(false);
e.printStackTrace();
}
}, String.format("screenshot-upload-%s", form.file.getName())).start();
}
public void login(String email, String password, boolean rememberMe) {
try {
SwingWorker worker = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(Request.Post(API_URL + "/token")
.bodyString(JacksonUtil.serialize(new CreateTokenRequest(email, password)), ContentType.APPLICATION_JSON)).returnResponse();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
UserToken tokenResponse = JacksonUtil.deserialize(
EntityUtils.toString(response.getEntity()),
UserToken.class);
if (loadAccount(tokenResponse.getUuid(), rememberMe, email)) {
logger.info("Logged in.");
return null;
}
}
logger.error("Invalid login, response: [" + response.toString() + "]");
getComponent().getStatusLbl().setText("Status: Invalid login");
return null;
}
};
worker.execute();
} catch (Exception e) {
logger.error("Oops.", e);
getComponent().getStatusLbl().setText("Status: Error logging in");
}
}
@Test
public void testRecreate() 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");
recreate(executor, "test", "2");
read(executor, "test", "2");
Executor.closeIdleConnections();
server.stop();
}
public static ClanInfo join(String loginName, String ingameName, String clanName, long clanId, boolean useId, ClanRank.Status status, int world) {
try {
Request request = Request.Post(API_URL + "rank/update/" + (useId ? "id" : "name"));
request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
request.bodyString(GSON.toJson(new GetOrJoinClanRequest(
clanId,
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() == HttpStatus.SC_FAILED_DEPENDENCY) {
NotificationsUtil.showNotification("Clan", "You have not yet been accepted into this clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
NotificationsUtil.showNotification("Clan", "Unable to find clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
NotificationsUtil.showNotification("Clan", "You have been banned from this clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED) {
NotificationsUtil.showNotification("Clan", "You have been denied access into this clan");
} else {
NotificationsUtil.showNotification("Clan", "Error joining clan");
}
}
return null;
} catch (IOException e) {
logger.error("Error joining clan", e);
return null;
}
}
public static ClanInfo updateRank(String loginName, String ingameName, ClanInfo clan, ClanRank.Status status, int world) {
try {
Request request = Request.Post(API_URL + "rank/update/id");
request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
request.bodyString(GSON.toJson(new GetOrJoinClanRequest(
clan.getClanId(),
loginName,
ingameName,
clan.getName(),
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() == HttpStatus.SC_FAILED_DEPENDENCY) {
NotificationsUtil.showNotification("Clan", "You have not yet been accepted into this clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
NotificationsUtil.showNotification("Clan", "Unable to find clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
NotificationsUtil.showNotification("Clan", "You have been banned from this clan");
} else {
NotificationsUtil.showNotification("Clan", "Error updating clan");
}
}
return null;
} catch (IOException e) {
logger.error("Error updating clan rank", e);
return null;
}
}
public static Content loadManifest(String folder, String owner, String repo) throws IOException {
String projecUrl = "https://api.github.com/repos/"+owner+"/"+repo;
String title = null;
log.debug("Tentative de connexion à l'url : "+projecUrl);
String githubUser = System.getProperty("zw.github_user");
String githubToken = System.getProperty("zw.github_token");
Executor executor;
if(githubUser != null && !"".equals(githubUser) && githubToken != null && !"".equals(githubToken)) {
executor = Executor
.newInstance()
.auth(new HttpHost("api.github.com"), githubUser, githubToken);
} else {
executor = Executor.newInstance();
}
String json = executor.execute(Request.Get(projecUrl)).returnContent().asString();
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(json, Map.class);
if(map.containsKey("description")) {
title = (String) map.get("description");
}
Content current = new Content("container", toSlug(title), title, Constant.DEFAULT_INTRODUCTION_FILENAME, Constant.DEFAULT_CONCLUSION_FILENAME, new ArrayList<>(), 2, "CC-BY", title, "TUTORIAL");
// read all directory
current.getChildren ().addAll (loadDirectory (folder.length () + File.separator.length (), new File(folder)));
current.setBasePath (folder);
generateMetadataAttributes(current.getFilePath());
return current;
}
/**
* Creates an empty repository (under the configured user).
* It is created as a public repository, un-initialized.
*
* @param projectName the project name (repository) to create
* @throws IOException Something went wrong (example: the repo already exists)
*/
void createEmptyRepo(String projectName) throws IOException {
Executor executor = getExecutor();
String gogsHooksConfigUrl = getGogsServer_apiUrl() + "user/repos";
Request request = Request.Post(gogsHooksConfigUrl);
if (this.gogsAccessToken != null) {
request.addHeader("Authorization", "token " + this.gogsAccessToken);
}
int result = executor
.execute(request
.bodyForm(Form.form()
.add("name", projectName)
.add("description", "API generated repository")
.add("private", "true")
.add("auto_init", "false")
.build()
)
)
.returnResponse().getStatusLine().getStatusCode();
if (result != 201) {
throw new IOException("Repository creation call did not return the expected value (returned " + result + ")");
}
}
void removeRepo(String projectName) throws IOException {
Executor executor = getExecutor();
String gogsHookConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName;
Request request = Request.Delete(gogsHookConfigUrl);
if (this.gogsAccessToken != null) {
request.addHeader("Authorization", "token " + this.gogsAccessToken);
}
int result = executor.execute(request).returnResponse().getStatusLine().getStatusCode();
if (result != 204) {
throw new IOException("Repository deletion call did not return the expected value (returned " + result + ")");
}
}
@Test
public void testWriteReadRemove() 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", "1234");
read(executor, "test", "1234");
remove(executor, "test", "null");
Executor.closeIdleConnections();
server.stop();
}