-
Notifications
You must be signed in to change notification settings - Fork 137
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
14 changed files
with
447 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import java.net.URI; | ||
import java.net.URISyntaxException; | ||
import java.net.http.HttpClient; | ||
import java.net.http.HttpRequest; | ||
import java.net.http.HttpResponse.BodyHandlers; | ||
import java.util.concurrent.CompletableFuture; | ||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Executors; | ||
|
||
public class AsyncSongLyricsRetriever { | ||
|
||
public static void getLyricsAsync(String artist, String song) { | ||
try (ExecutorService executor = Executors.newCachedThreadPool()) { | ||
HttpClient client = | ||
HttpClient.newBuilder().executor(executor).build(); // configure custom executor or use the default | ||
|
||
URI uri = new URI("https", "api.lyrics.ovh", "/v1/" + artist + "/" + song, null); | ||
System.out.println(uri); | ||
|
||
HttpRequest request = HttpRequest.newBuilder().uri(uri).build(); | ||
System.out.println("Thread calling sendAsync(): " + Thread.currentThread().getName()); | ||
|
||
CompletableFuture<String> future = client.sendAsync(request, BodyHandlers.ofString()) | ||
.thenApply(x -> { | ||
System.out.println("Thread executing thenApply(): " + Thread.currentThread().getName()); | ||
return x.body(); | ||
}); | ||
future.thenAcceptAsync(x -> { | ||
System.out.println("Thread executing thenAccept(): " + Thread.currentThread().getName()); | ||
System.out.println(x); | ||
}, executor); | ||
System.out.println("The HTTP call is fired. Performing some other work..."); | ||
|
||
// wait for the async HTTP call | ||
future.join(); | ||
|
||
// ExecutorService is AutoCloseable since Java 19, so its shutdown() method will be automatically invoked. | ||
} catch (URISyntaxException e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
|
||
public static void main(String... args) throws Exception { | ||
AsyncSongLyricsRetriever.getLyricsAsync("Adele", "Hello"); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import java.lang.reflect.Type; | ||
import java.util.List; | ||
import java.util.Map; | ||
|
||
import com.google.gson.Gson; | ||
import com.google.gson.reflect.TypeToken; | ||
|
||
public class CollectionsMain { | ||
|
||
public static void main(String[] args) { | ||
// Lists example | ||
List<Developer> devs = List.of( | ||
new Developer("Kelsey", 28, "Google, Inc"), | ||
new Developer("Wesley", 20, "Google, Inc")); | ||
|
||
Gson gson = new Gson(); | ||
String json = gson.toJson(devs); | ||
|
||
System.out.println(json); | ||
|
||
Type type = new TypeToken<List<Developer>>() { | ||
}.getType(); | ||
List<Developer> devsAgain = gson.fromJson(json, type); | ||
|
||
System.out.println(devsAgain.size()); // 2 | ||
|
||
// Maps example | ||
json = "{\"apple\":1,\"banana\":2,\"cherry\":3}"; | ||
|
||
Map<String, Integer> map = gson.fromJson(json, new TypeToken<Map<String, Integer>>() { | ||
}.getType()); | ||
|
||
System.out.println(map); // {apple=1, banana=2, cherry=3} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import com.google.gson.annotations.SerializedName; | ||
|
||
public record DevManager(String name, @SerializedName("unit") String department, int level) { | ||
// Gson's @SerializedName annotation is also supported for record components | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import com.google.gson.annotations.SerializedName; | ||
|
||
public class Developer { | ||
|
||
private String name; | ||
private int age; | ||
@SerializedName("employer") // this sets custom name to the serialized field | ||
private transient String company; // remove transient keyword to serialize | ||
|
||
public Developer(String name, int age, String company) { | ||
this.name = name; | ||
this.age = age; | ||
this.company = company; | ||
} | ||
|
||
public String getName() { | ||
return name; | ||
} | ||
|
||
public void setName(String name) { | ||
this.name = name; | ||
} | ||
|
||
public int getAge() { | ||
return age; | ||
} | ||
|
||
public void setAge(int age) { | ||
this.age = age; | ||
} | ||
|
||
public String getCompany() { | ||
return company; | ||
} | ||
|
||
public void setCompany(String company) { | ||
this.company = company; | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import java.net.URI; | ||
import java.net.http.HttpClient; | ||
import java.net.http.HttpRequest; | ||
import java.net.http.HttpResponse; | ||
import java.nio.file.Path; | ||
|
||
public class FileDownload { | ||
|
||
public static void main(String... args) throws Exception { | ||
var url = "https://www.7-zip.org/a/7z1806-x64.exe"; | ||
|
||
var client = HttpClient.newBuilder().build(); | ||
var request = HttpRequest.newBuilder().uri(URI.create(url)).build(); | ||
|
||
Path localFile = Path.of("7z.exe"); | ||
|
||
HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(localFile)); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import com.google.gson.Gson; | ||
|
||
public class FromJsonMain { | ||
|
||
public static void main(String[] args) { | ||
String json = "{\"name\": \"Wesley\", \"age\": 20 }"; | ||
|
||
Gson gson = new Gson(); | ||
Developer dev = gson.fromJson(json, Developer.class); | ||
|
||
System.out.printf("%s, %d years old, %s%n", dev.getName(), dev.getAge(), dev.getCompany()); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import com.google.gson.Gson; | ||
|
||
import java.io.FileReader; | ||
import java.io.IOException; | ||
import java.util.List; | ||
|
||
public class JsonReaderMain { | ||
|
||
public static void main(String[] args) throws IOException { | ||
Gson gson = new Gson(); | ||
|
||
FileReader reader = new FileReader("src/devs.json"); | ||
List<Developer> devs = gson.fromJson(reader, List.class); | ||
System.out.println(devs); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
import java.net.URI; | ||
import java.net.http.HttpClient; | ||
import java.net.http.HttpRequest; | ||
import java.net.http.HttpResponse.BodyHandlers; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.concurrent.CompletableFuture; | ||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Executors; | ||
|
||
public class ParallelHttpRequestsSender { | ||
|
||
private static final String WEB_SITE = "http://www.google.com"; | ||
private static final int PARALLEL_REQUESTS = 100; | ||
|
||
public long executeRequestsSync(HttpClient client, HttpRequest request) throws Exception { | ||
// send some synchronous requests and measure time | ||
long startTime = System.currentTimeMillis(); | ||
|
||
for (int i = 0; i < PARALLEL_REQUESTS; i++) { | ||
client.send(request, BodyHandlers.ofString()).body(); | ||
} | ||
|
||
return System.currentTimeMillis() - startTime; | ||
} | ||
|
||
public long executeRequestsAsync(HttpClient client, HttpRequest request) { | ||
List<CompletableFuture<String>> futures = new ArrayList<>(); | ||
|
||
// send some asynchronous requests and measure time | ||
long startTime = System.currentTimeMillis(); | ||
|
||
for (int i = 0; i < PARALLEL_REQUESTS; i++) { | ||
futures.add(client.sendAsync(request, BodyHandlers.ofString()).thenApply(x -> { | ||
System.out.println("thenApply() thread: " + Thread.currentThread().getName()); | ||
return x.body(); | ||
})); | ||
} | ||
|
||
// uncomment to dump responses to console | ||
// futures.stream().map(f -> f.join()).forEach(System.out::println); | ||
|
||
// wait for all futures to complete | ||
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join(); | ||
|
||
return System.currentTimeMillis() - startTime; | ||
} | ||
|
||
public static void main(String... args) throws Exception { | ||
try (ExecutorService executor = Executors.newCachedThreadPool()) { | ||
HttpClient client = | ||
HttpClient.newBuilder().executor(executor).build(); // configure custom executor or use the default | ||
|
||
// build a request | ||
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(WEB_SITE)).build(); | ||
|
||
var sender = new ParallelHttpRequestsSender(); | ||
|
||
long syncExecutionTime = sender.executeRequestsSync(client, request); | ||
long asyncExecutionTime = sender.executeRequestsAsync(client, request); | ||
|
||
System.out.println("Async: " + asyncExecutionTime + " Sync: " + syncExecutionTime); | ||
|
||
// ExecutorService is AutoCloseable since Java 19, so its shutdown() method will be automatically invoked. | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.InputStreamReader; | ||
import java.io.PrintWriter; | ||
import java.net.Socket; | ||
|
||
public class SimpleHttpCaller { | ||
|
||
private static final String HOST = "google.com"; | ||
private static final int HTTP_PORT = 80; | ||
private static final String HTTP_REQUEST = "GET / HTTP/1.1" + System.lineSeparator(); | ||
|
||
public static void main(String[] args) { | ||
|
||
try (Socket socket = new Socket(HOST, HTTP_PORT); | ||
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // autoflush on | ||
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { | ||
|
||
writer.println(HTTP_REQUEST); | ||
|
||
String line; | ||
while ((line = reader.readLine()) != null) { | ||
System.out.println(line); | ||
} | ||
|
||
} catch (IOException e) { | ||
throw new RuntimeException("Could not access web site", e); | ||
} | ||
|
||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import java.net.URI; | ||
import java.net.http.HttpClient; | ||
import java.net.http.HttpRequest; | ||
import java.net.http.HttpResponse.BodyHandlers; | ||
|
||
public class SyncSongLyricsRetriever { | ||
|
||
public String getLyricsSync(String artist, String song) throws Exception { | ||
HttpClient client = HttpClient.newBuilder().build(); | ||
|
||
URI uri = new URI("https", "api.lyrics.ovh", "/v1/" + artist + "/" + song, null); | ||
System.out.println(uri); | ||
|
||
HttpRequest request = HttpRequest.newBuilder().uri(uri).build(); | ||
return client.send(request, BodyHandlers.ofString()).body(); | ||
} | ||
|
||
public static void main(String... args) throws Exception { | ||
System.out.println(new SyncSongLyricsRetriever().getLyricsSync("Adele", "Hello")); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import java.net.URI; | ||
import java.net.http.HttpClient; | ||
import java.net.http.HttpRequest; | ||
import java.net.http.HttpResponse.BodyHandlers; | ||
import java.nio.file.Path; | ||
|
||
public class TextToSpeech { | ||
|
||
// signup here to get your API key: https://account.cloudmersive.com/signup | ||
private static final String API_KEY = "YOUR_API_KEY_HERE"; | ||
|
||
private static final String TEXT = | ||
"\"I must admit I was skeptical about the Modern Java Technologies course but in the end I am starting to appreciate it. \""; | ||
|
||
public static void main(String... args) throws Exception { | ||
HttpClient client = HttpClient.newHttpClient(); | ||
|
||
URI uri = new URI("https", "api.cloudmersive.com", "/speech/speak/text/basicVoice/wav", null); | ||
HttpRequest request = HttpRequest.newBuilder() | ||
.header("Apikey", API_KEY) | ||
.header("Content-Type", "application/json") | ||
.POST(HttpRequest.BodyPublishers.ofString(TEXT)) | ||
.uri(uri) | ||
.build(); | ||
|
||
client.send(request, BodyHandlers.ofFile(Path.of("speech.wav"))); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import com.google.gson.Gson; | ||
import com.google.gson.GsonBuilder; | ||
|
||
public class ToJsonMain { | ||
|
||
public static void main(String[] args) { | ||
Developer dev = new Developer("Kelsey", 28, "Google, Inc"); | ||
DevManager devManager = new DevManager("Mike", "Google AI R&D", 7); | ||
|
||
Gson gson = new Gson(); | ||
//Gson gson = new GsonBuilder().setPrettyPrinting().create(); | ||
String devJson = gson.toJson(dev); | ||
System.out.println(devJson); | ||
|
||
// Gson version 2.10 and later also supports records | ||
// Note that the & character in the department value would be replaced by default with its unicode escape, \u0026 | ||
Gson gsonNonEscaping = new GsonBuilder().disableHtmlEscaping().create(); | ||
String devManagerJson = gsonNonEscaping.toJson(devManager); | ||
System.out.println(devManagerJson); | ||
} | ||
|
||
} |
Oops, something went wrong.