Copy cat > /tmp/Lab11.java << 'JAVAEOF'
import java.net.http.*;
import java.net.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.io.IOException;
public class Lab11 {
public static void main(String[] args) throws Exception {
System.out.println("=== HttpClient Configuration ===\n");
var client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(5))
.build();
System.out.println("Version: " + client.version());
System.out.println("Timeout: " + client.connectTimeout());
// Build GET request
var getReq = HttpRequest.newBuilder()
.uri(URI.create("https://api.innozverse.com/products"))
.header("X-API-Key", "inz_dr_chen")
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(10))
.GET().build();
System.out.println("\nGET " + getReq.uri());
System.out.println("Headers: " + getReq.headers().map());
// Build POST request
String body = "{\"product_id\":1,\"quantity\":2,\"email\":\"[email protected] \"}";
var postReq = HttpRequest.newBuilder()
.uri(URI.create("https://api.innozverse.com/orders"))
.header("X-API-Key", "inz_dr_chen")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
System.out.println("\nPOST " + postReq.uri());
System.out.println("Method: " + postReq.method());
// JSON parsing (no deps)
System.out.println("\n=== JSON Parsing ===");
String[] responses = {
"{\"id\":1,\"name\":\"Surface Pro\",\"price\":\"864.00\",\"stock\":\"15\"}",
"{\"order_id\":\"1001\",\"status\":\"confirmed\",\"total\":\"1728.00\"}"
};
for (var json : responses) {
var parsed = parseJson(json);
System.out.println(" " + parsed);
}
// Retry with exponential backoff
System.out.println("\n=== Retry with Backoff ===");
int maxRetries = 3;
String result = retry(maxRetries, attempt -> {
if (attempt < 2) throw new IOException("Transient error (attempt " + attempt + ")");
return "{\"status\":\"ok\",\"attempt\":" + attempt + "}";
});
System.out.println(" Success: " + result);
// Parallel async requests
System.out.println("\n=== Parallel Async Requests ===");
var executor = Executors.newFixedThreadPool(3);
var paths = List.of("/products/1", "/products/2", "/products/3");
var futures = paths.stream().map(path ->
CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(50); } catch (InterruptedException e) {}
return "GET " + path + " -> 200 {\"id\":" + path.split("/")[2] + "}";
}, executor)).toList();
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
futures.forEach(f -> System.out.println(" " + f.join()));
executor.shutdown();
// Response handling
System.out.println("\n=== Response Status Categories ===");
record Response(int status, String body) {
boolean isSuccess() { return status >= 200 && status < 300; }
boolean isClientError() { return status >= 400 && status < 500; }
boolean isServerError() { return status >= 500; }
String category() {
return isSuccess() ? "SUCCESS" : isClientError() ? "CLIENT_ERR" : "SERVER_ERR";
}
}
for (var r : List.of(new Response(200, "OK"), new Response(201, "Created"),
new Response(401, "Unauthorized"), new Response(404, "Not Found"),
new Response(503, "Unavailable"))) {
System.out.printf(" %d %-15s -> %s%n", r.status(), r.body(), r.category());
}
}
static Map<String, String> parseJson(String json) {
var result = new LinkedHashMap<String, String>();
var stripped = json.trim().replaceAll("^\\{|\\}$", "");
for (var kv : stripped.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)")) {
var parts = kv.trim().split(":", 2);
if (parts.length == 2) {
result.put(parts[0].trim().replaceAll("\"", ""),
parts[1].trim().replaceAll("^\"|\"$", ""));
}
}
return result;
}
@FunctionalInterface interface ThrowingSupplier<T> { T get(int attempt) throws Exception; }
static <T> T retry(int max, ThrowingSupplier<T> fn) throws Exception {
for (int attempt = 1; attempt <= max; attempt++) {
try { return fn.get(attempt); }
catch (Exception e) {
System.out.println(" Attempt " + attempt + " failed: " + e.getMessage());
if (attempt < max) {
long delay = (long) Math.pow(2, attempt) * 100L;
System.out.println(" Retry in " + delay + "ms...");
Thread.sleep(delay);
} else throw e;
}
}
throw new IllegalStateException("unreachable");
}
}
JAVAEOF
docker run --rm -v /tmp/Lab11.java:/tmp/Lab11.java zchencow/innozverse-java:latest sh -c "javac /tmp/Lab11.java -d /tmp && java -cp /tmp Lab11"