net.aequologica.neo.shakuntala.utils.ClientAsyncPatch Maven / Gradle / Ivy
package net.aequologica.neo.shakuntala.utils;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClientAsyncPatch {
private final static Logger log = LoggerFactory.getLogger(ClientAsyncPatch.class);
public static void main(String[] args) throws Exception {
if (args.length != 1) {
log.warn("[shakuntala] uri not given");
System.exit(1);
}
asyncPatch(URI.create(args[0]), "dugenou", "http://proxy:8080");
for (int i = 0 ; i<=12; i++) {
System.out.println(i);
Thread.sleep(4000/12);
}
}
public static int asyncPatch(final URI uri, final Object entity, final String proxy) throws IOException, InterruptedException {
int statusCode = -1;
final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
// Start the client
httpclient.start();
RequestConfig requestConfig = null;
if (proxy != null && !proxy.isEmpty()) {
URI proxyURI = URI.create(proxy);
HttpHost proxyHttpHost = new HttpHost(proxyURI.getHost(), proxyURI.getPort());
requestConfig = RequestConfig.custom()
.setProxy(proxyHttpHost)
.build();
}
final CountDownLatch latch1 = new CountDownLatch(1);
// Execute request
final HttpPatch httpPatch = new HttpPatch(uri);
if (requestConfig != null) {
httpPatch.setConfig(requestConfig);
}
StringEntity stringEntity = new StringEntity(entity.toString());
httpPatch.setEntity(stringEntity);
httpPatch.setHeader("Content-Type", "text/plain");
log.info("[shakuntala] about to send PATCH to " + uri.toString() + " with proxy " + proxy);
httpclient.execute(httpPatch, new FutureCallback() {
public void completed(final HttpResponse response2) {
latch1.countDown();
log.info("{} -> {}", httpPatch.getRequestLine(), response2.getStatusLine());
System.out.println(httpPatch.getRequestLine() + "->" + response2.getStatusLine());
}
public void failed(final Exception ex) {
latch1.countDown();
log.info("{} -> {}", httpPatch.getRequestLine(), ex.getMessage());
System.out.println(httpPatch.getRequestLine() + "->" + ex);
}
public void cancelled() {
latch1.countDown();
log.info("{} cancelled", httpPatch.getRequestLine());
System.out.println(httpPatch.getRequestLine() + " cancelled");
}
});
latch1.await();
} finally {
httpclient.close();
}
log.debug("statusCode: {}", statusCode);
return statusCode;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy