Skip to content

Commit

Permalink
Cleaned up some code - removed unused imports and made a lot of stuff…
Browse files Browse the repository at this point in the history
… final, as mentioned in #3
  • Loading branch information
JoshiCodes committed Aug 13, 2024
1 parent c35111c commit 7bdc8a8
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 51 deletions.
55 changes: 28 additions & 27 deletions src/main/java/de/joshicodes/aghpb4j/AGHPB.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
import de.joshicodes.aghpb4j.action.RestAction;
import de.joshicodes.aghpb4j.objects.AGHPBook;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

Expand Down Expand Up @@ -56,7 +57,7 @@ public RandomImageAction retrieveRandomBook() {
* @see #retrieveRandomBook(AGHPBook.BookImageType)
* @see #retrieveRandomBook(String, AGHPBook.BookImageType)
*/
public RandomImageAction retrieveRandomBook(String category) {
public RandomImageAction retrieveRandomBook(final String category) {
return retrieveRandomBook().withCategory(category);
}

Expand All @@ -70,7 +71,7 @@ public RandomImageAction retrieveRandomBook(String category) {
* @see #retrieveRandomBook(String)
* @see #retrieveRandomBook(String, AGHPBook.BookImageType)
*/
public RandomImageAction retrieveRandomBook(AGHPBook.BookImageType type) {
public RandomImageAction retrieveRandomBook(final AGHPBook.BookImageType type) {
return retrieveRandomBook().useType(type);
}

Expand All @@ -84,7 +85,7 @@ public RandomImageAction retrieveRandomBook(AGHPBook.BookImageType type) {
* @see #retrieveRandomBook(String)
* @see #retrieveRandomBook(AGHPBook.BookImageType)
*/
public RandomImageAction retrieveRandomBook(String category, AGHPBook.BookImageType type) {
public RandomImageAction retrieveRandomBook(final String category, final AGHPBook.BookImageType type) {
return retrieveRandomBook().withCategory(category).useType(type);
}

Expand All @@ -96,7 +97,7 @@ public RandomImageAction retrieveRandomBook(String category, AGHPBook.BookImageT
*/
public RestAction<ApiStatus> retrieveStatus() {
return new RestAction<>(url + "/nya", "GET", ApiStatus.class, response -> {
JsonObject json = response.getAsJsonObject();
final JsonObject json = response.getAsJsonObject();
if(!json.has("version")) {
throw new IllegalStateException("Response does not contain a version field");
}
Expand All @@ -111,15 +112,15 @@ public RestAction<ApiStatus> retrieveStatus() {
* @see <a href="https://api.devgoldy.xyz/aghpb/v1/docs#/books/All_Available_Categories_categories_get">API Documentation</a>
*/
public RestAction<List<String>> retrieveAllCategories() {
return new RestAction<List<String>>(url + "/categories", "GET", null, (response) -> {
JsonElement json = response.getAsJsonElement();
if(json == null || !json.isJsonArray()) {
return new RestAction<>(url + "/categories", "GET", null, (response) -> {
final JsonElement json = response.getAsJsonElement();
if (json == null || !json.isJsonArray()) {
throw new IllegalStateException("Response is not a JSON array");
}
JsonArray array = json.getAsJsonArray();
List<String> categories = new ArrayList<>();
for(JsonElement element : array) {
if(!element.isJsonPrimitive()) {
final JsonArray array = json.getAsJsonArray();
final List<String> categories = new ArrayList<>();
for (JsonElement element : array) {
if (!element.isJsonPrimitive()) {
throw new IllegalStateException("Element is not a JSON primitive");
}
categories.add(element.getAsString());
Expand All @@ -134,7 +135,7 @@ public RestAction<List<String>> retrieveAllCategories() {
* @param query The query to search for.
* @return A RestAction for the search.
*/
public RestAction<List<AGHPBook>> retrieveSearch(String query) {
public RestAction<List<AGHPBook>> retrieveSearch(final String query) {
return retrieveSearch(query, null, -1);
}

Expand All @@ -145,7 +146,7 @@ public RestAction<List<AGHPBook>> retrieveSearch(String query) {
* @param limit The limit of books to retrieve. Must be greater than 0.
* @return A RestAction for the search.
*/
public RestAction<List<AGHPBook>> retrieveSearch(String query, int limit) {
public RestAction<List<AGHPBook>> retrieveSearch(final String query, final int limit) {
return retrieveSearch(query, null, limit);
}

Expand All @@ -156,7 +157,7 @@ public RestAction<List<AGHPBook>> retrieveSearch(String query, int limit) {
* @param category The category to search in. Can be null.
* @return A RestAction for the search.
*/
public RestAction<List<AGHPBook>> retrieveSearch(String query, String category) {
public RestAction<List<AGHPBook>> retrieveSearch(final String query, final String category) {
return retrieveSearch(query, category, -1);
}

Expand All @@ -168,20 +169,20 @@ public RestAction<List<AGHPBook>> retrieveSearch(String query, String category)
* @param limit The limit of books to retrieve. Must be greater than 0.
* @return A RestAction for the search.
*/
public RestAction<List<AGHPBook>> retrieveSearch(String query, String category, int limit) {
public RestAction<List<AGHPBook>> retrieveSearch(final String query, final String category, final int limit) {
final String url = this.url + "/search?query=" + query + (category != null ? "&category=" + category : "") + (limit > 0 ? "&limit=" + limit : "");
return new RestAction<>(url, "GET", null, (response) -> {
JsonElement json = response.getAsJsonElement();
final JsonElement json = response.getAsJsonElement();
if(json == null || !json.isJsonArray()) {
throw new IllegalStateException("Response is not a JSON array");
}
JsonArray array = json.getAsJsonArray();
List<AGHPBook> books = new ArrayList<>();
final JsonArray array = json.getAsJsonArray();
final List<AGHPBook> books = new ArrayList<>();
for(JsonElement element : array) {
if(!element.isJsonObject()) {
continue;
}
JsonObject obj = element.getAsJsonObject();
final JsonObject obj = element.getAsJsonObject();
if(
!obj.has("search_id")
|| !obj.has("name")
Expand Down Expand Up @@ -212,7 +213,7 @@ public RestAction<List<AGHPBook>> retrieveSearch(String query, String category,
* @param book The book to retrieve.
* @return An ImageAction for the book.
*/
public ImageAction<AGHPBook> retrieveBook(AGHPBook book) {
public ImageAction<AGHPBook> retrieveBook(final AGHPBook book) {
return retrieveBook(book.searchId());
}

Expand All @@ -222,7 +223,7 @@ public ImageAction<AGHPBook> retrieveBook(AGHPBook book) {
* @param searchId The search_id of the book to retrieve.
* @return An ImageAction for the book.
*/
public ImageAction<AGHPBook> retrieveBook(int searchId) {
public ImageAction<AGHPBook> retrieveBook(final int searchId) {
return retrieveBook(searchId, AGHPBook.BookImageType.PNG);
}

Expand All @@ -232,7 +233,7 @@ public ImageAction<AGHPBook> retrieveBook(int searchId) {
* @param type The format of the book.
* @return An ImageAction for the book.
*/
public ImageAction<AGHPBook> retrieveBook(AGHPBook book, AGHPBook.BookImageType type) {
public ImageAction<AGHPBook> retrieveBook(final AGHPBook book, final AGHPBook.BookImageType type) {
return retrieveBook(book.searchId(), type);
}

Expand All @@ -242,18 +243,18 @@ public ImageAction<AGHPBook> retrieveBook(AGHPBook book, AGHPBook.BookImageType
* @param type The format of the book.
* @return An ImageAction for the book.
*/
public ImageAction<AGHPBook> retrieveBook(int searchId, AGHPBook.BookImageType type) {
public ImageAction<AGHPBook> retrieveBook(final int searchId, final AGHPBook.BookImageType type) {
final String url = this.url + "/get/id/" + searchId;
return new ImageAction<>(url, AGHPBook.class, (request) -> {
request.header("Accept", "image/" + type.name().toLowerCase());
return request;
}, response -> {
final String contentType = response.httpResponse().headers().firstValue("Content-Type").orElse(null);
if(contentType == null || !contentType.startsWith("image/")) {
JsonElement json = response.getAsJsonElement();
final JsonElement json = response.getAsJsonElement();
throw new IllegalStateException("Response is not an image! " + (json != null ? ("( " + json + " )") : ""));
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
baos.write(response.httpResponse().body());
} catch (IOException e) {
Expand All @@ -278,7 +279,7 @@ public ImageAction<AGHPBook> retrieveBook(int searchId, AGHPBook.BookImageType t
*/
public RestAction<ApiInfo> retrieveInfo() {
return new RestAction<>(url + "/info", "GET", ApiInfo.class, response -> {
JsonObject json = response.getAsJsonObject();
final JsonObject json = response.getAsJsonObject();
if(!json.has("book_count") || !json.has("api_version")) {
throw new IllegalStateException("Response does not contain bookCount or apiVersion field");
}
Expand Down
11 changes: 4 additions & 7 deletions src/main/java/de/joshicodes/aghpb4j/action/ImageAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,17 @@ public class ImageAction<T> extends RestAction<T> {

protected Function<RestResponse<byte[]>, T> responseHandler;

public ImageAction(String url, Class<T> tClass, Function<HttpRequest.Builder, HttpRequest.Builder> clientModifier, Function<RestResponse<byte[]>, T> responseHandler) {
public ImageAction(final String url, final Class<T> tClass, final Function<HttpRequest.Builder, HttpRequest.Builder> clientModifier, final Function<RestResponse<byte[]>, T> responseHandler) {
super(url, "GET", tClass, clientModifier, null);
this.responseHandler = responseHandler;
}

@Override
public T execute() {
try {
HttpClient.Builder client = build();
HttpRequest.Builder request = buildRequest();
if(clientModifier != null) {
request = clientModifier.apply(request);
}
HttpResponse<byte[]> response = sendRequest(client.build(), request.build(), HttpResponse.BodyHandlers.ofByteArray(), 3);
final HttpClient.Builder client = build();
final HttpRequest.Builder request = buildRequest();
final HttpResponse<byte[]> response = sendRequest(client.build(), request.build(), HttpResponse.BodyHandlers.ofByteArray(), 3);
return this.responseHandler.apply(new RestResponse<>(response, byte[].class));
} catch (Exception e) {
throw new RuntimeException(e);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package de.joshicodes.aghpb4j.action;

import com.google.gson.JsonElement;
import de.joshicodes.aghpb4j.objects.AGHPBook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.http.HttpRequest;
import java.util.function.Function;

public class RandomImageAction extends ImageAction<AGHPBook> {

Expand All @@ -27,7 +24,7 @@ public RandomImageAction(final String apiUrl) {
if(contentType == null || !contentType.startsWith("image/")) {
throw new IllegalStateException("Failed request to " + url + "! Response is not an image! " + "( " + response.rawBody() + " )." + " Content Type is " + contentType + ". Expected image/*.");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
baos.write(response.httpResponse().body());
} catch (IOException e) {
Expand All @@ -52,7 +49,6 @@ public RandomImageAction useType(final AGHPBook.BookImageType type) {
public RandomImageAction withCategory(final String category) {
final String cat = category != null ? ("?category=" + category) : "";
url = String.format(URL, this.initialUrl) + cat;
System.out.println("URL: " + url);
return this;
}

Expand Down
22 changes: 11 additions & 11 deletions src/main/java/de/joshicodes/aghpb4j/action/RestAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,23 @@ public class RestAction<T> {
protected Function<HttpRequest.Builder, HttpRequest.Builder> clientModifier;
protected final Function<RestResponse, T> responseHandler;

public RestAction(String url, String method, Class<T> tClass, Function<HttpRequest.Builder, HttpRequest.Builder> clientModifier, Function<RestResponse, T> responseHandler) {
public RestAction(final String url, final String method, final Class<T> tClass, final Function<HttpRequest.Builder, HttpRequest.Builder> clientModifier, final Function<RestResponse, T> responseHandler) {
this.url = url;
this.method = method;
this.tClass = tClass;
this.clientModifier = clientModifier;
this.responseHandler = responseHandler;
}

public RestAction(String url, String method, Class<T> tClass, Function<RestResponse, T> responseHandler) {
public RestAction(final String url, final String method, final Class<T> tClass, final Function<RestResponse, T> responseHandler) {
this(url, method, tClass, Function.identity(), responseHandler);
}

public RestAction(String url, String method, Class<T> tClass) {
public RestAction(final String url, final String method, final Class<T> tClass) {
this(url, method, tClass, Function.identity(), response -> null);
}

public RestAction(String url, Class<T> tClass, Function<HttpRequest.Builder, HttpRequest.Builder> clientModifier, Function<RestResponse, T> responseHandler) {
public RestAction(final String url, final Class<T> tClass, final Function<HttpRequest.Builder, HttpRequest.Builder> clientModifier, final Function<RestResponse, T> responseHandler) {
this(url, "GET", tClass, clientModifier, responseHandler);
}

Expand All @@ -62,7 +62,7 @@ public void queue() {
* @see #queue()
* @see #queue(Consumer, Consumer)
*/
public void queue(Consumer<T> success) {
public void queue(final Consumer<T> success) {
queue(success, (e) -> {
throw new RuntimeException(e);
});
Expand All @@ -78,10 +78,10 @@ public void queue(Consumer<T> success) {
* @see #queue()
* @see #queue(Consumer)
*/
public void queue(Consumer<T> success, Consumer<Throwable> failure) {
public void queue(final Consumer<T> success, final Consumer<Throwable> failure) {
CompletableFuture.runAsync(() -> {
try {
T result = execute();
final T result = execute();
if(success != null) success.accept(result);
} catch (Throwable e) {
if(failure != null) failure.accept(e);
Expand All @@ -96,9 +96,9 @@ public void queue(Consumer<T> success, Consumer<Throwable> failure) {
*/
public T execute() {
try {
HttpClient.Builder client = build();
HttpRequest.Builder request = buildRequest();
HttpResponse<String> response = sendRequest(client.build(), request.build(), HttpResponse.BodyHandlers.ofString(), 3);
final HttpClient.Builder client = build();
final HttpRequest.Builder request = buildRequest();
final HttpResponse<String> response = sendRequest(client.build(), request.build(), HttpResponse.BodyHandlers.ofString(), 3);
return responseHandler.apply(new RestResponse<>(response, String.class));
} catch (Exception e) {
throw new RuntimeException(e);
Expand All @@ -107,7 +107,7 @@ public T execute() {

protected <C> HttpResponse<C> sendRequest(HttpClient client, HttpRequest request, HttpResponse.BodyHandler<C> handler, int retries) {
try {
HttpResponse<C> response = client.send(request, handler);
final HttpResponse<C> response = client.send(request, handler);
if(response.headers().firstValue("x-ratelimit-remaining").orElse("1").equals("0")) {
// Rate limit
final long reset = Long.parseLong(response.headers().firstValue("x-ratelimit-reset").orElse("0"));
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/de/joshicodes/aghpb4j/objects/AGHPBook.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public void saveImage(File file) throws IOException {
if(file.getParentFile() != null) file.getParentFile().mkdirs();
}
if(!file.getName().endsWith(".png") && !file.getName().endsWith(".jpg") && !file.getName().endsWith(".jpeg")) throw new IllegalArgumentException("File must be a valid image file (png, jpg, jpeg).");
try (OutputStream os = new FileOutputStream(file)) {
try (final OutputStream os = new FileOutputStream(file)) {
os.write(imageBytes);
}
}
Expand Down

0 comments on commit 7bdc8a8

Please sign in to comment.