Skip to content

Commit

Permalink
Support Java 8 in the core library
Browse files Browse the repository at this point in the history
  • Loading branch information
Pixaurora committed Jul 12, 2024
1 parent ba32887 commit 04cedba
Show file tree
Hide file tree
Showing 13 changed files with 67 additions and 24 deletions.
2 changes: 1 addition & 1 deletion subprojects/core/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
plugins {
id("kit_tunes.java.17") // TODO: Switch to kit_tunes.java.08
id("kit_tunes.java.08")
id("kit_tunes.base")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ public abstract class Constants {
public static final String MOD_VERSION;
public static final String HOMEPAGE;

public static final Path SCROBBLER_CACHE_PATH = QuiltLoader.getCacheDir()
.resolve(Path.of(Constants.MOD_ID, "scrobblers.json"));
public static final Path SCROBBLER_CACHE_PATH = QuiltLoader.getCacheDir().resolve(Constants.MOD_ID)
.resolve("scrobblers.json");

static {
ModContainer mod = QuiltLoader.getModContainer(MOD_ID).get(); // Should never be null, since we're running from
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.pixaurora.kit_tunes.impl;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
Expand All @@ -20,7 +21,7 @@ public class KitTunes {
public static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID);

public static final ConfigManager<ScrobblerCache> SCROBBLER_CACHE = new ConfigManager<>(
Constants.SCROBBLER_CACHE_PATH, ScrobblerCache.class, () -> new ScrobblerCache(List.of()));
Constants.SCROBBLER_CACHE_PATH, ScrobblerCache.class, () -> new ScrobblerCache(Arrays.asList()));

public static final MinecraftUICompat UI_LAYER = ServiceLoading.loadJustOneOrThrow(MinecraftUICompat.class);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package net.pixaurora.kit_tunes.impl.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.function.Consumer;
import java.util.function.Supplier;

Expand Down Expand Up @@ -48,7 +51,7 @@ private boolean configLocationWritable() {
}

private T load() throws IOException, JsonParseException {
String configData = Files.readString(this.savePath);
BufferedReader configData = Files.newBufferedReader(this.savePath, StandardCharsets.UTF_8);

return Serialization.serializer().fromJson(configData, this.configClass);
}
Expand All @@ -57,7 +60,7 @@ private boolean save(T config) {
String result = Serialization.serializer().toJson(config, this.configClass);

try {
Files.writeString(this.savePath, result);
Files.write(this.savePath, result.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);

return true;
} catch (IOException exception) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,14 @@

import net.pixaurora.kit_tunes.impl.config.DualSerializer;

public record DispatchGroup<A extends SpecifiesType<A>, T extends DispatchType<A>>(String typeName, List<T> types) {
public class DispatchGroup<A extends SpecifiesType<A>, T extends DispatchType<A>> {
private final String typeName;
private final List<T> types;

public DispatchGroup(String typeName, List<T> types) {
this.typeName = typeName;
this.types = types;
}

public <G> T lookupBy(String lookupType, Function<T, G> getter, G lookupObject) {
Optional<T> foundType = this.types.stream().filter(type -> getter.apply(type).equals(lookupObject)).findFirst();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,19 @@ public static <T> T runOrThrow(ErroringSupplier<T> action) throws UnhandledKitTu
}
}

public static void runOrThrow(ErroringRunnable action) throws UnhandledKitTunesException {
try {
action.run();
} catch (Throwable e) {
throw new UnhandledKitTunesException(e);
}
}

public static interface ErroringSupplier<T> {
public T run() throws Throwable;
}

public static interface ErroringRunnable {
public void run() throws Throwable;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public void onTrackEnd(TrackEndEvent event) {
.execute(scrobblers -> scrobblers.completeScrobbling(new ScrobbledTrack(track, progress)));
} else {
KitTunes.LOGGER.info("Skipping scrobbling " + track.name() + " because it only played for "
+ progress.amountPlayed().toSeconds() + " seconds!");
+ (float) progress.amountPlayed().toMillis() / 1000 + " seconds!");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
Expand All @@ -13,6 +14,7 @@
import java.util.Map;

import net.pixaurora.kit_tunes.impl.Constants;
import net.pixaurora.kit_tunes.impl.KitTunes;
import net.pixaurora.kit_tunes.impl.error.UnhandledKitTunesException;

public class HttpHelper {
Expand All @@ -36,6 +38,19 @@ public static Map<String, String> defaultHeaders() {
return headers;
}

public static void logResponse(InputStream data) throws IOException {
StringBuilder builder = new StringBuilder();

int c = data.read();
while (c != -1) {
builder.append((char) c);

c = data.read();
}

KitTunes.LOGGER.info("Received response: " + builder.toString());
}

private static InputStream handleRequest(String method, String endpoint, Map<String, String> queryParameters)
throws IOException {
URL url = new URL(endpoint + createQuery(queryParameters));
Expand All @@ -53,6 +68,8 @@ private static InputStream handleRequest(String method, String endpoint, Map<Str
connection.setFixedLengthStreamingMode(0);
}

connection.getContentLength();

if (connection.getResponseCode() == 200) {
return connection.getInputStream();
} else {
Expand All @@ -63,8 +80,13 @@ private static InputStream handleRequest(String method, String endpoint, Map<Str
private static String createQuery(Map<String, String> queryParameters) {
List<String> query = new ArrayList<>(queryParameters.size());

for (var parameter : queryParameters.entrySet()) {
query.add(parameter.getKey() + "=" + URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8));
for (Map.Entry<String, String> parameter : queryParameters.entrySet()) {
try {
query.add(parameter.getKey() + "="
+ URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8.toString()));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Should never happen, URL encoding is hard-coded.", e);
}
}

return query.size() == 0 ? "" : "?" + String.join("&", query);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class XMLHelper {
private static final DocumentBuilder BUILDER = createBuilder();

public static DocumentBuilder createBuilder() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newDefaultInstance();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package net.pixaurora.kit_tunes.impl.scrobble;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import net.pixaurora.kit_tunes.impl.KitTunes;
import net.pixaurora.kit_tunes.impl.error.KitTunesException;
import net.pixaurora.kit_tunes.impl.error.ScrobblerParsingException;
import net.pixaurora.kit_tunes.impl.error.UnhandledKitTunesException;
Expand Down Expand Up @@ -84,17 +84,15 @@ public void completeScrobbling(ScrobbleInfo track) throws KitTunesException {
private void handleScrobbling(Map<String, String> args) throws KitTunesException {
InputStream responseBody = HttpHelper.post(ROOT_API_URL, args);

String body = UnhandledKitTunesException.runOrThrow(() -> new String(responseBody.readAllBytes()));

KitTunes.LOGGER.info(body);
UnhandledKitTunesException.runOrThrow(() -> HttpHelper.logResponse(responseBody));
}

private static Map<String, String> addSignature(Map<String, String> parameters) {
var sortedParameters = new ArrayList<>(parameters.entrySet());
sortedParameters.sort(Comparator.comparing(entry -> entry.getKey()));
List<Map.Entry<String, String>> sortedParameters = parameters.entrySet().stream()
.sorted(Comparator.comparing(entry -> entry.getKey())).collect(Collectors.toList());

String regularSignature = "";
for (var parameter : sortedParameters) {
for (Map.Entry<String, String> parameter : sortedParameters) {
regularSignature += parameter.getKey() + parameter.getValue();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package net.pixaurora.kit_tunes.impl.scrobble;

import java.util.List;
import java.util.Arrays;

import net.pixaurora.kit_tunes.impl.config.dispatch.DispatchGroup;
import net.pixaurora.kit_tunes.impl.config.dispatch.SpecifiesType;
import net.pixaurora.kit_tunes.impl.error.KitTunesException;

public interface Scrobbler extends SimpleScrobbler, SpecifiesType<Scrobbler> {
public static final DispatchGroup<Scrobbler, ScrobblerType<? extends Scrobbler>> TYPES = new DispatchGroup<>(
"scrobbler", List.of(LastFMScrobbler.TYPE));
"scrobbler", Arrays.asList(LastFMScrobbler.TYPE));

public static final int SETUP_PORT = 19686;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public class ScrobblerSetup<T extends Scrobbler> {

public ScrobblerSetup(SetupServer server, ScrobblerType<T> scrobblerType, long timeout, TimeUnit unit) {
this.server = server;
this.awaitedScrobbler = server.awaitedToken().orTimeout(timeout, unit)
.whenComplete((token, error) -> server.cleanup()).thenApply(token -> {
this.awaitedScrobbler = server.awaitedToken().whenComplete((token, error) -> server.cleanup())
.thenApply(token -> {
return scrobblerType.setupMethod().createScrobbler(token);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import net.pixaurora.kit_tunes.impl.ui.text.Component;

public interface MinecraftClient {
private static MinecraftUICompat impl() {
static MinecraftUICompat impl() {
return KitTunes.UI_LAYER;
}

Expand Down

0 comments on commit 04cedba

Please sign in to comment.