Skip to content

Commit

Permalink
Merge pull request #9 from edward3h/java17
Browse files Browse the repository at this point in the history
migrate to Java 17
  • Loading branch information
edward3h committed Feb 7, 2022
2 parents b5fa6ae + 84b7fac commit 2841e03
Show file tree
Hide file tree
Showing 19 changed files with 376 additions and 520 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/gradle-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ jobs:

steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
- name: Set up JDK 17
uses: ayltai/setup-graalvm@v1
with:
java-version: 11
java-version: 17
graalvm-version: 21.3.0
- name: Grant execute permission for gradlew
run: chmod +x gradlew
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ jobs:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up JDK 11
- name: Set up JDK 17
uses: ayltai/setup-graalvm@v1
with:
java-version: 11
java-version: 17
graalvm-version: 21.3.0
- name: Grant execute permission for gradlew
run: chmod +x gradlew
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/publish_mr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ jobs:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up JDK 11
- name: Set up JDK 17
uses: ayltai/setup-graalvm@v1
with:
java-version: 11
java-version: 17
graalvm-version: 21.3.0
- name: Grant execute permission for gradlew
run: chmod +x gradlew
Expand Down
2 changes: 1 addition & 1 deletion .sdkmanrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=21.3.0.r11-grl
java=21.3.0.r17-grl
11 changes: 2 additions & 9 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,7 @@ plugins {
id("io.micronaut.application") version "3.2.0"
}

java {
toolchain {
languageVersion = JavaLanguageVersion.of(11)
vendor = JvmVendorSpec.GRAAL_VM
}
}

version = "0.3.1"
version = "0.3.2"

repositories {
mavenCentral()
Expand Down Expand Up @@ -75,7 +68,7 @@ tasks.named('test') {
}

tasks.named("dockerfile") {
baseImage = "ghcr.io/graalvm/graalvm-ce:java11-21.3.0"
baseImage = "ghcr.io/graalvm/graalvm-ce:java17-21.3.0"
instruction """RUN touch /config.yml"""
}

Expand Down
17 changes: 6 additions & 11 deletions app/src/main/java/org/ethelred/minecraft/webhook/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,11 @@
@Singleton
public class App {

public static void main(String[] args) {
// tell Micronaut to look for config in known paths of the docker image
System.setProperty(
"micronaut.config.files",
"/config.yml" // in root of docker image
public static void main(String[] args) {
// tell Micronaut to look for config in known paths of the docker image
System.setProperty(
"micronaut.config.files", "/config.yml" // in root of docker image
);
Micronaut
.build(args)
.mainClass(App.class)
.defaultEnvironments("dev")
.start();
}
Micronaut.build(args).mainClass(App.class).defaultEnvironments("dev").start();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,16 @@
@Requires(property = "mc-webhook.webhook-url")
public class BackCompatUrlSetup extends MinecraftServerEventListener {

public BackCompatUrlSetup(
BeanContext context,
ConversionService<?> conversionService,
@Property(name = "mc-webhook.webhook-url") URL url
) {
super(context, conversionService, getConfiguration(url));
}
public BackCompatUrlSetup(
BeanContext context,
ConversionService<?> conversionService,
@Property(name = "mc-webhook.webhook-url") URL url) {
super(context, conversionService, getConfiguration(url));
}

private static SenderConfiguration getConfiguration(URL url) {
var config = new SenderConfiguration();
config.setUrl(url); // defaults are ok for other properties
return config;
}
private static SenderConfiguration getConfiguration(URL url) {
var config = new SenderConfiguration();
config.setUrl(url); // defaults are ok for other properties
return config;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@
@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface ContainerId {
}
public @interface ContainerId {}
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@
@Factory
public class DefaultDocker {

@Singleton
public DockerClient docker() {
var dockerCC = DefaultDockerClientConfig
.createDefaultConfigBuilder()
.build();
var http = new ApacheDockerHttpClient.Builder()
@Singleton
public DockerClient docker() {
var dockerCC = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
var http =
new ApacheDockerHttpClient.Builder()
.dockerHost(dockerCC.getDockerHost())
.sslConfig(dockerCC.getSSLConfig())
.build();
return DockerClientImpl.getInstance(dockerCC, http);
}
return DockerClientImpl.getInstance(dockerCC, http);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,125 +24,105 @@
@Named("discord")
public class DiscordWebhookSender implements Sender {

private static final long DEFAULT_DELAY = 3_000;
private static final Logger LOGGER = LogManager.getLogger(
DiscordWebhookSender.class
);
private static final long DEFAULT_DELAY = 3_000;
private static final Logger LOGGER = LogManager.getLogger(DiscordWebhookSender.class);

private final URI webhook;
private final HttpClient client;
private final ScheduledExecutorService scheduler;
private final BlockingQueue<String> waiting;
private final URI webhook;
private final HttpClient client;
private final ScheduledExecutorService scheduler;
private final BlockingQueue<String> waiting;

@Inject
public DiscordWebhookSender(@Parameter URL webhookUrl) {
try {
this.webhook = webhookUrl.toURI();
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
this.client = HttpClient.newBuilder().build();
this.scheduler = Executors.newSingleThreadScheduledExecutor();
this.waiting = new ArrayBlockingQueue<>(64);
_scheduleNext(0L);
LOGGER.info(
"DiscordWebhookSender initialized with URL {}",
this.webhook
);
@Inject
public DiscordWebhookSender(@Parameter URL webhookUrl) {
try {
this.webhook = webhookUrl.toURI();
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
this.client = HttpClient.newBuilder().build();
this.scheduler = Executors.newSingleThreadScheduledExecutor();
this.waiting = new ArrayBlockingQueue<>(64);
_scheduleNext(0L);
LOGGER.info("DiscordWebhookSender initialized with URL {}", this.webhook);
}

private void _scheduleNext(long delay) {
LOGGER.debug("_scheduleNext({})", delay);
scheduler.schedule(
() -> {
try {
_sendMessage(waiting.take());
} catch (InterruptedException e) {
_scheduleNext(DEFAULT_DELAY);
}
},
delay,
TimeUnit.MILLISECONDS
);
}
private void _scheduleNext(long delay) {
LOGGER.debug("_scheduleNext({})", delay);
scheduler.schedule(
() -> {
try {
_sendMessage(waiting.take());
} catch (InterruptedException e) {
_scheduleNext(DEFAULT_DELAY);
}
},
delay,
TimeUnit.MILLISECONDS);
}

private void _sendMessage(String message) {
LOGGER.debug(message);
long delay = 0;
try {
// this works for Discord, not sure if it's compatible with other systems
var request = HttpRequest
.newBuilder(webhook)
.header("Content-Type", "application/json")
.POST(
HttpRequest.BodyPublishers.ofString(
String.format("{\"content\":\"%s\"}", message)
)
)
.build();
var response = client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
LOGGER.debug(response::body);
switch (response.statusCode()) {
case 401: // Unauthorized
case 403: // Forbidden
// Most likely the webhook URL is wrong and this will never succeed
System.out.printf(
"Discord response %d %s%nDouble check your webhook URL %s%nSystem will exit",
response.statusCode(),
response.body(),
webhook
);
System.exit(4);
break;
case 503: // Service Unavailable
case 429: // Rate Limit https://discord.com/developers/docs/topics/rate-limits
// Set a delay
var retryValue = response
.headers()
.firstValue("Retry-After");
delay = _delayFromHeaderValue(retryValue);
case 200:
case 204: // no content
// awesome
break;
default:
throw new IOException(
String.format(
"Unexpected response status %d%n%s",
response.statusCode(),
response.body()
)
);
}
} catch (IOException | InterruptedException e) {
// can't tell at this point whether the message was sent or not - just give up and log
LOGGER.error("Exception in _sendMessage", e);
delay = DEFAULT_DELAY;
} finally {
_scheduleNext(delay);
}
private void _sendMessage(String message) {
LOGGER.debug(message);
long delay = 0;
try {
// this works for Discord, not sure if it's compatible with other systems
var request =
HttpRequest.newBuilder(webhook)
.header("Content-Type", "application/json")
.POST(
HttpRequest.BodyPublishers.ofString(
String.format("{\"content\":\"%s\"}", message)))
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
LOGGER.debug(response::body);
switch (response.statusCode()) {
case 401: // Unauthorized
case 403: // Forbidden
// Most likely the webhook URL is wrong and this will never succeed
System.out.printf(
"Discord response %d %s%nDouble check your webhook URL %s%nSystem will exit",
response.statusCode(), response.body(), webhook);
System.exit(4);
break;
case 503: // Service Unavailable
case 429: // Rate Limit https://discord.com/developers/docs/topics/rate-limits
// Set a delay
var retryValue = response.headers().firstValue("Retry-After");
delay = _delayFromHeaderValue(retryValue);
case 200:
case 204: // no content
// awesome
break;
default:
throw new IOException(
String.format(
"Unexpected response status %d%n%s", response.statusCode(), response.body()));
}
} catch (IOException | InterruptedException e) {
// can't tell at this point whether the message was sent or not - just give up and log
LOGGER.error("Exception in _sendMessage", e);
delay = DEFAULT_DELAY;
} finally {
_scheduleNext(delay);
}
}

@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private long _delayFromHeaderValue(Optional<String> retryValue) {
if (retryValue.isPresent()) {
try {
return Long.parseLong(retryValue.get()) * 1000; // header is in seconds
} catch (NumberFormatException e) {
// TODO is date format used in this API?
LOGGER.debug(retryValue.get(), e);
}
}
return DEFAULT_DELAY;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private long _delayFromHeaderValue(Optional<String> retryValue) {
if (retryValue.isPresent()) {
try {
return Long.parseLong(retryValue.get()) * 1000; // header is in seconds
} catch (NumberFormatException e) {
// TODO is date format used in this API?
LOGGER.debug(retryValue.get(), e);
}
}
return DEFAULT_DELAY;
}

@Override
public void sendMessage(MinecraftServerEvent event, String message) {
LOGGER.debug("sendMessage({})", message.trim());
//noinspection ResultOfMethodCallIgnored
waiting.offer(message.trim());
}
@Override
public void sendMessage(MinecraftServerEvent event, String message) {
LOGGER.debug("sendMessage({})", message.trim());
//noinspection ResultOfMethodCallIgnored
waiting.offer(message.trim());
}
}
Loading

0 comments on commit 2841e03

Please sign in to comment.