Skip to content

Commit 474add2

Browse files
author
arbhard2
committed
Embedded HttpClient Project
1 parent babb4ef commit 474add2

11 files changed

Lines changed: 438 additions & 0 deletions

File tree

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Exercise for Java Advanced Concepts
2+
3+
* Collection
4+
* Generics
5+
* Multithreading
6+
* HttpClient
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.ab.httpclient.advanced;
2+
3+
import java.net.URI;
4+
import java.net.http.HttpClient;
5+
import java.time.Duration;
6+
import java.util.concurrent.CompletableFuture;
7+
import java.util.concurrent.CompletionStage;
8+
import java.util.concurrent.CountDownLatch;
9+
10+
import static java.net.http.WebSocket.*;
11+
12+
/**
13+
* @author Arpit Bhardwaj
14+
*/
15+
public class WebSocket {
16+
private static final int msgCount = 5;
17+
public static void main(String[] args) throws InterruptedException {
18+
CountDownLatch receiveLatch = new CountDownLatch(msgCount);
19+
20+
CompletableFuture<java.net.http.WebSocket> webSocketCompletableFuture = HttpClient.newHttpClient()
21+
.newWebSocketBuilder()
22+
.connectTimeout(Duration.ofSeconds(3))
23+
.buildAsync(URI.create("ws://echo.websocket.org"), new EchoListener(receiveLatch));
24+
25+
webSocketCompletableFuture.thenAccept(webSocket -> {
26+
webSocket.request(msgCount);
27+
for (int i = 0; i < msgCount; i++) {
28+
webSocket.sendText("Message " + i, true);
29+
}
30+
});
31+
32+
receiveLatch.await();
33+
}
34+
35+
private static class EchoListener implements Listener {
36+
CountDownLatch receiveLatch;
37+
public EchoListener(CountDownLatch receiveLatch) {
38+
this.receiveLatch = receiveLatch;
39+
}
40+
41+
@Override
42+
public void onOpen(java.net.http.WebSocket webSocket) {
43+
System.out.println("Web Socket Opened");
44+
}
45+
46+
@Override
47+
public CompletionStage<?> onText(java.net.http.WebSocket webSocket, CharSequence data, boolean last) {
48+
System.out.println("onText " + data);
49+
receiveLatch.countDown();
50+
return null;
51+
}
52+
}
53+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.ab.httpclient.configuration;
2+
3+
import java.io.IOException;
4+
import java.net.CookieManager;
5+
import java.net.CookiePolicy;
6+
import java.net.URI;
7+
import java.net.http.HttpClient;
8+
import java.net.http.HttpRequest;
9+
import java.net.http.HttpResponse;
10+
11+
/**
12+
* @author Arpit Bhardwaj
13+
*/
14+
public class CookieDemo {
15+
public static void main(String[] args) throws IOException, InterruptedException {
16+
CookieManager cm = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
17+
var httpClient = HttpClient.newBuilder().cookieHandler(cm).build();
18+
HttpRequest httpRequest = HttpRequest.newBuilder(URI.create("https://www.google.com")).build();
19+
httpClient.send(httpRequest, HttpResponse.BodyHandlers.discarding());
20+
21+
System.out.println(cm.getCookieStore().getURIs());
22+
System.out.println(cm.getCookieStore().getCookies());
23+
}
24+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.ab.httpclient.configuration;
2+
3+
import java.io.IOException;
4+
import java.net.URI;
5+
import java.net.http.HttpClient;
6+
import java.net.http.HttpRequest;
7+
import java.net.http.HttpResponse;
8+
import java.nio.file.Files;
9+
import java.nio.file.Path;
10+
import java.time.Duration;
11+
import java.util.List;
12+
import java.util.concurrent.CompletableFuture;
13+
import java.util.stream.Collectors;
14+
15+
/**
16+
* @author Arpit Bhardwaj
17+
*/
18+
public class HttpClientConfig {
19+
private static HttpClient httpClient;
20+
21+
public static void main(String[] args) throws IOException {
22+
23+
httpClient = HttpClient.newBuilder()
24+
.connectTimeout(Duration.ofSeconds(3))
25+
.followRedirects(HttpClient.Redirect.NORMAL)
26+
.build();
27+
28+
List<CompletableFuture<String>> collectCompletableFutureList = Files.lines(Path.of("urls.txt"))
29+
.map(HttpClientConfig::validateLink)
30+
.collect(Collectors.toList());
31+
32+
collectCompletableFutureList.stream()
33+
.map(CompletableFuture::join)
34+
.forEach(System.out::println);
35+
36+
}
37+
38+
private static CompletableFuture<String> validateLink(String link) {
39+
HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(link))
40+
.timeout(Duration.ofSeconds(5))
41+
.GET()
42+
.build();
43+
44+
CompletableFuture<HttpResponse<Void>> httpResponseCompletableFuture = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.discarding());
45+
CompletableFuture<String> stringCompletableFuture = httpResponseCompletableFuture.thenApply(HttpClientConfig::responseToString)
46+
.exceptionally(throwable -> String.format("Exception Occurred : %s -> %s", link, false));
47+
return stringCompletableFuture;
48+
}
49+
50+
private static String responseToString(HttpResponse<Void> httpResponse) {
51+
int status = httpResponse.statusCode();
52+
boolean success = status >= 200 && status <= 299;
53+
return String.format("%s -> %s (status: %s)", httpResponse.uri(), success, status);
54+
}
55+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.ab.httpclient.configuration;
2+
3+
import javax.net.ssl.SSLContext;
4+
import javax.net.ssl.SSLParameters;
5+
import java.io.IOException;
6+
import java.net.*;
7+
import java.net.http.HttpClient;
8+
import java.net.http.HttpRequest;
9+
import java.net.http.HttpResponse;
10+
import java.security.NoSuchAlgorithmException;
11+
12+
/**
13+
* @author Arpit Bhardwaj
14+
*/
15+
public class Security {
16+
public static void main(String[] args) throws IOException, InterruptedException, NoSuchAlgorithmException {
17+
18+
SSLParameters parameters = new SSLParameters(
19+
new String[]{ "TLSv1.2"},
20+
new String[]{ "TLS_AES_128_GCM_SHA256"}
21+
);
22+
HttpClient httpClient = HttpClient.newBuilder()
23+
.sslContext(SSLContext.getDefault())
24+
.sslParameters(parameters)
25+
.proxy(
26+
ProxySelector.of(new InetSocketAddress("proxyserver.com",8080))
27+
//ProxySelector.getDefault()
28+
)
29+
.authenticator(new Authenticator(){
30+
@Override
31+
protected PasswordAuthentication getPasswordAuthentication() {
32+
return new PasswordAuthentication("username","password".toCharArray());
33+
//return super.getPasswordAuthentication();
34+
}
35+
})
36+
.build();
37+
38+
HttpRequest httpRequest = HttpRequest.newBuilder(URI.create("https://www.google.com")).build();
39+
httpClient.send(httpRequest, HttpResponse.BodyHandlers.discarding());
40+
41+
}
42+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.ab.httpclient.linkvalidator;
2+
3+
import java.io.IOException;
4+
import java.net.URI;
5+
import java.net.http.HttpClient;
6+
import java.net.http.HttpRequest;
7+
import java.net.http.HttpResponse;
8+
import java.nio.file.Files;
9+
import java.nio.file.Path;
10+
import java.util.List;
11+
import java.util.concurrent.CompletableFuture;
12+
import java.util.stream.Collectors;
13+
14+
/**
15+
* @author Arpit Bhardwaj
16+
*/
17+
public class LinkValidatorAsync {
18+
private static HttpClient httpClient;
19+
public static void main(String[] args) throws IOException {
20+
httpClient = HttpClient.newHttpClient();
21+
/*Files.lines(Path.of("urls.txt"))
22+
.map(LinkValidatorAsync::validateLink)
23+
.forEach(System.out::println);*/
24+
25+
List<CompletableFuture<String>> collectCompletableFutureList = Files.lines(Path.of("urls.txt"))
26+
.map(LinkValidatorAsync::validateLink)
27+
.collect(Collectors.toList());
28+
collectCompletableFutureList.stream()
29+
.map(CompletableFuture::join)
30+
.forEach(System.out::println);
31+
32+
}
33+
34+
private static CompletableFuture<String> validateLink(String link) {
35+
HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(link)).GET().build();
36+
37+
/*try {
38+
HttpResponse<Void> httpResponse = httpClient.send(httpRequest,HttpResponse.BodyHandlers.discarding());
39+
return responseToString(httpResponse);
40+
} catch (IOException | InterruptedException e) {
41+
return String.format("%s -> %s",link,false);
42+
}*/
43+
CompletableFuture<HttpResponse<Void>> httpResponseCompletableFuture = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.discarding());
44+
CompletableFuture<String> stringCompletableFuture = httpResponseCompletableFuture.thenApply(LinkValidatorAsync::responseToString)
45+
.exceptionally(throwable -> String.format("Exception Occurred : %s -> %s", link, false));
46+
return stringCompletableFuture;
47+
}
48+
49+
private static String responseToString(HttpResponse<Void> httpResponse) {
50+
int status = httpResponse.statusCode();
51+
boolean success = status >= 200 && status <= 299;
52+
return String.format("%s -> %s (status: %s)",httpResponse.uri(),success,status);
53+
}
54+
55+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.ab.httpclient.linkvalidator;
2+
3+
import java.io.IOException;
4+
import java.net.URI;
5+
import java.net.http.HttpClient;
6+
import java.net.http.HttpRequest;
7+
import java.net.http.HttpResponse;
8+
import java.nio.file.Files;
9+
import java.nio.file.Path;
10+
11+
/**
12+
* @author Arpit Bhardwaj
13+
*/
14+
public class LinkValidatorSync {
15+
private static HttpClient httpClient;
16+
public static void main(String[] args) throws IOException {
17+
httpClient = HttpClient.newHttpClient();
18+
Files.lines(Path.of("urls.txt"))
19+
.map(LinkValidatorSync::validateLink)
20+
.forEach(System.out::println);
21+
22+
}
23+
24+
private static String validateLink(String link) {
25+
HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(link)).GET().build();
26+
27+
try {
28+
HttpResponse<Void> httpResponse = httpClient.send(httpRequest,HttpResponse.BodyHandlers.discarding());
29+
return responseToString(httpResponse);
30+
} catch (IOException | InterruptedException e) {
31+
e.printStackTrace();
32+
return String.format("%s -> %s",link,false);
33+
34+
}
35+
}
36+
37+
private static String responseToString(HttpResponse<Void> httpResponse) {
38+
int status = httpResponse.statusCode();
39+
boolean success = status >= 200 && status <= 299;
40+
return String.format("%s -> %s (status: %s)",httpResponse.uri(),success,status);
41+
}
42+
43+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.ab.httpclient.rest;
2+
3+
import javax.script.*;
4+
import java.io.*;
5+
import java.net.*;
6+
7+
/**
8+
* @author Arpit Bhardwaj
9+
*/
10+
public class DrawnMatches {
11+
public static void main(String[] args) throws IOException {
12+
System.out.println(getNumDraws(2011));
13+
}
14+
15+
public static int getNumDraws(int year) throws IOException {
16+
final String endpoint = "https://jsonmock.hackerrank.com/api/football_matches?year=" + year;
17+
final int maxScore = 10;
18+
int totalNumDraws = 0;
19+
20+
for (int score = 0; score <= maxScore; score++) {
21+
totalNumDraws += getTotalNumDraws(String.format(endpoint + "&team1goals=%d&team2goals=%d",
22+
score,
23+
score));
24+
}
25+
return totalNumDraws;
26+
}
27+
28+
private static int getTotalNumDraws(String request) throws IOException {
29+
URL url = new URL(request);
30+
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
31+
httpURLConnection.setRequestMethod("GET");
32+
httpURLConnection.setConnectTimeout(120000);
33+
httpURLConnection.setReadTimeout(120000);
34+
httpURLConnection.addRequestProperty("Content-Type", "application/json");
35+
36+
int status = httpURLConnection.getResponseCode();
37+
InputStream in = (status < 200 || status > 299) ?
38+
httpURLConnection.getErrorStream() : httpURLConnection.getInputStream();
39+
40+
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
41+
String responseLine;
42+
StringBuffer responseContent = new StringBuffer();
43+
44+
while ((responseLine = reader.readLine()) != null){
45+
responseContent.append(responseLine);
46+
}
47+
48+
reader.close();
49+
httpURLConnection.disconnect();
50+
51+
ScriptEngineManager manager = new ScriptEngineManager();
52+
ScriptEngine engine = manager.getEngineByName("javascript");
53+
String script = "var obj = JSON.parse('"+responseContent+"');";
54+
script += "var total = obj.total;";
55+
56+
try {
57+
engine.eval(script);
58+
} catch (ScriptException e) {
59+
e.printStackTrace();
60+
}
61+
62+
if (engine.get("total") == null){
63+
throw new RuntimeException("Cannot retrieve data from server");
64+
}
65+
return (int) engine.get("total");
66+
}
67+
}

0 commit comments

Comments
 (0)