Skip to content

Added .class to LogManager #128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -20,7 +21,11 @@ public static List<File> getClassesInClassPath() {
String[] classpathEntries = classpath.split(File.pathSeparator);
for (String entry : classpathEntries) {
File file = new File(entry);
classes.addAll(getClasses(file));
try {
classes.addAll(getClasses(file));
} catch (IOException ignore) {
/* Ignore */
}
}
return classes;
}
Expand Down Expand Up @@ -48,21 +53,44 @@ public static String getClassName(File file) throws IOException {
return className;
}

private static List<File> getClasses(File file) {
List<File> classes = new ArrayList<>();
private static List<File> getClasses(File file) throws IOException {
List<File> classFiles = new ArrayList<>();
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
classes.addAll(getClasses(f));
}
classFiles.addAll(getClassesFromDirectory(file));
} else if (isJarFile(file)) {
classFiles.addAll(getClassesFromJar(file));
} else if (file.getName().endsWith(".class")) {
classFiles.add(file);
}
return classFiles;
}

private static List<File> getClassesFromDirectory(File directory) throws IOException {
List<File> classFiles = new ArrayList<>();
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
classFiles.addAll(getClasses(file));
}
} else {
if (file.getName().endsWith(".class")) {
classes.add(file);
}
return classFiles;
}

private static List<File> getClassesFromJar(File jarFile) throws IOException {
List<File> classFiles = new ArrayList<>();
try (
FileInputStream fis = new FileInputStream(jarFile);
ZipInputStream zip = new ZipInputStream(fis)
) {
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
File tempFile = extractClassFileFromJar(zip, entry.getName());
classFiles.add(tempFile);
}
}
}
return classes;
return classFiles;
}

private static boolean isJarFile(File file) {
Expand All @@ -76,4 +104,20 @@ private static String extractClassName(DataInputStream dis) throws IOException {
private static String extractClassName(ZipInputStream zip) throws IOException {
return new ClassFile(new DataInputStream(zip)).getName();
}

private static File extractClassFileFromJar(
ZipInputStream zip,
String entryName
) throws IOException {
File tempFile = File.createTempFile(entryName.replace('/', '_'), ".class");
tempFile.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = zip.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
return tempFile;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import org.apache.logging.log4j.Logger;

public class EventListenerValidator {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(EventListenerValidator.class);
private static final Map<Class<? extends Annotation>, String[]> EXPECTED_PARAM_TYPES_MAP =
new HashMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import org.apache.logging.log4j.Logger;

public class ListenerLoader {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(ListenerLoader.class);
private final EventListenerValidator eventListenerValidator = new EventListenerValidator();
private final List<Object> eventListeners;

Expand All @@ -23,16 +23,20 @@ public ListenerLoader(List<Object> eventListeners) {
}
}

public void loadListeners() throws Exception {
public void loadListeners() {
List<File> classes = ClassFileUtil.getClassesInClassPath();
for (File classFile : classes) {
Class<?> clazz = Class.forName(ClassFileUtil.getClassName(classFile));
if (clazz.isAnnotationPresent(EventListener.class)) {
if (validateListener(clazz)) {
registerListener(clazz);
} else {
LOGGER.error("{} failed validation", clazz.getName());
try {
Class<?> clazz = Class.forName(ClassFileUtil.getClassName(classFile));
if (clazz.isAnnotationPresent(EventListener.class)) {
if (validateListener(clazz)) {
registerListener(clazz);
} else {
LOGGER.error("{} failed validation", clazz.getName());
}
}
} catch (Exception ignore) {
/* Ignore */
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class DiscordRequestDispatcher implements Runnable {
? System.getProperty("DISCORD_BASE_URL")
: "https://discord.com/api";

private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(DiscordRequestDispatcher.class);
private final HttpClient httpClient;
private final BlockingQueue<DiscordRequestBuilder> queue;
private final String botToken;
Expand Down
16 changes: 7 additions & 9 deletions core/src/main/java/com/javadiscord/jdi/core/Discord.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.javadiscord.jdi.core;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
Expand All @@ -27,7 +26,7 @@
import org.apache.logging.log4j.Logger;

public class Discord {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(Discord.class);
private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool();
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final String WEBSITE = "https://javadiscord.com/";
Expand Down Expand Up @@ -102,19 +101,18 @@ public Discord(String botToken, IdentifyRequest identifyRequest, Cache cache) {
this.identifyRequest = identifyRequest;
this.cache = cache;
if (annotationLibPresent()) {
LOGGER.info("Annotation lib is present, loading annotations listeners...");
loadAnnotations();
}
}

private boolean annotationLibPresent() {
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
for (String entry : classpathEntries) {
if (entry.endsWith("annotations-1.0.0.jar")) {
return true;
}
try {
Class.forName("com.javadiscord.jdi.core.processor.ListenerLoader");
return true;
} catch (Exception e) {
return false;
}
return false;
}

private void loadAnnotations() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import org.apache.logging.log4j.Logger;

public class GatewayEventListener implements GatewayObserver {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(GatewayEventListener.class);
private final Discord discord;

public GatewayEventListener(Discord discord) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
import org.apache.logging.log4j.Logger;

public class GatewayEventListenerAnnotations implements GatewayObserver {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER =
LogManager.getLogger(GatewayEventListenerAnnotations.class);
public static final Map<EventType, String> EVENT_TYPE_ANNOTATIONS = new HashMap<>();

static {
Expand Down
7 changes: 7 additions & 0 deletions example/echo-bot/build.gradle
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
plugins {
id 'java'
id 'application'
id 'com.github.johnrengelman.shadow' version '8.1.1'
}

application {
mainClass = 'com.javadiscord.jdi.example.Main'
}

dependencies {}

shadowJar {
archiveBaseName.set('example-bot')
archiveClassifier.set('')
archiveVersion.set('')
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import org.apache.logging.log4j.Logger;

public class WebSocketHandler implements Handler<WebSocket> {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(WebSocketHandler.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Map<Integer, GatewayOperationHandler> OPERATION_HANDLER = new HashMap<>();
private final ConnectionMediator connectionMediator;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import org.apache.logging.log4j.Logger;

public class WebSocketManager {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(WebSocketManager.class);
private final GatewaySetting gatewaySetting;
private final IdentifyRequest identifyRequest;
private final Vertx vertx;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import org.apache.logging.log4j.Logger;

public class WebSocketRetryHandler {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(WebSocketRetryHandler.class);
private final Vertx vertx;
private final AtomicInteger attempts;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
import org.apache.logging.log4j.Logger;

public class EventCodecHandler implements GatewayOperationHandler {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(EventCodecHandler.class);
private static final Map<EventType, EventDecoder<?>> EVENT_DECODERS = new HashMap<>();
private static final Map<EventType, EventHandler<?>> EVENT_HANDLERS = new HashMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import org.apache.logging.log4j.Logger;

public class ResumeEventHandler implements EventHandler<ResumeEvent> {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(ResumeEventHandler.class);

@Override
public void handle(ResumeEvent message, ConnectionMediator connectionMediator, Cache cache) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import org.apache.logging.log4j.Logger;

public class HeartbeatService {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(HeartbeatService.class);
private static final ScheduledExecutorService EXECUTOR_SERVICE =
Executors.newScheduledThreadPool(2);
private final ConnectionMediator connectionMediator;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import org.apache.logging.log4j.Logger;

public class HelloOperationHandler implements GatewayOperationHandler {
private static final Logger LOGGER = LogManager.getLogger();
private static final Logger LOGGER = LogManager.getLogger(HelloOperationHandler.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final HeartbeatService heartbeatService;

Expand Down
Loading