Skip to content

Commit

Permalink
refactor: use single Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
MC-XiaoHei committed Jun 21, 2024
1 parent 2590a3e commit 3c639f7
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 45 deletions.
45 changes: 21 additions & 24 deletions java21/src/main/java/launchwrapper/LaunchClassLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.JarURLConnection;
Expand All @@ -51,14 +49,13 @@
import java.util.jar.Manifest;

import static java.util.Objects.requireNonNull;
import static org.leavesmc.leavesclip.Leavesclip.LOGGER;

public class LaunchClassLoader extends URLClassLoader {
private static final Logger logger = LoggerFactory.getLogger("LaunchWrapper");

static {
/* Use this, if you encounter weird issues */
if (!Boolean.getBoolean("legacy.dontRegisterLCLAsParallelCapable")) {
logger.debug("Registering LaunchClassLoader as parallel capable");
LOGGER.debug("Registering LaunchClassLoader as parallel capable");
ClassLoader.registerAsParallelCapable();
}
}
Expand Down Expand Up @@ -146,9 +143,9 @@ public LaunchClassLoader(URL[] sources, ClassLoader parent) {
Files.walk(DUMP_PATH).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
}
Files.createDirectories(DUMP_PATH);
logger.info("DEBUG_SAVE Enabled, saving all classes to \"{}\"", DUMP_PATH);
LOGGER.info("DEBUG_SAVE Enabled, saving all classes to \"{}\"", DUMP_PATH);
} catch (IOException e) {
logger.warn("Failed to set up DEBUG_SAVE", e);
LOGGER.warn("Failed to set up DEBUG_SAVE", e);
}
}
}
Expand All @@ -167,7 +164,7 @@ public void registerTransformer(@NotNull String transformerClassName) {
if (transformer instanceof IClassNameTransformer && renameTransformer == null)
renameTransformer = (IClassNameTransformer) transformer;
} catch (Exception e) {
logger.warn("A critical problem occurred registering the transformer class {}", transformerClassName, e);
LOGGER.warn("A critical problem occurred registering the transformer class {}", transformerClassName, e);
}
}

Expand Down Expand Up @@ -217,7 +214,7 @@ public Class<?> findClass(final String name) throws ClassNotFoundException {
transformedClass = runTransformers(untransformedName, transformedName, classData);
} catch (Exception e) {
if (DEBUG)
logger.trace("Exception encountered while transformimg class {}", name, e);
LOGGER.trace("Exception encountered while transformimg class {}", name, e);
}

// If transformer chain provides no class data, mark given class name invalid and throw CNFE
Expand All @@ -231,7 +228,7 @@ public Class<?> findClass(final String name) throws ClassNotFoundException {
try {
saveTransformedClass(transformedClass, transformedName);
} catch (IOException e) {
logger.warn("Failed to save class {}", transformedName, e);
LOGGER.warn("Failed to save class {}", transformedName, e);
}
}

Expand All @@ -258,11 +255,11 @@ public Class<?> findClass(final String name) throws ClassNotFoundException {
pkg = definePackage(packageName, manifest, jarURLConnection.getJarFileURL());
} else {
if (pkg.isSealed() && !pkg.isSealed(jarURLConnection.getJarFileURL())) {
logger.error("The jar file {} is trying to seal already secured path {}",
LOGGER.error("The jar file {} is trying to seal already secured path {}",
jarFile.getName(),
packageName);
} else if (isSealed(packageName, manifest)) {
logger.error("The jar file {} has a security seal for path {}, but that path is defined and not secure",
LOGGER.error("The jar file {} has a security seal for path {}, but that path is defined and not secure",
jarFile.getName(),
packageName);
}
Expand All @@ -283,7 +280,7 @@ public Class<?> findClass(final String name) throws ClassNotFoundException {
);
} else if (pkg.isSealed()) {
URL url = urlConnection != null ? urlConnection.getURL() : null;
logger.error("The URL {} is defining elements for sealed path {}", url, packageName);
LOGGER.error("The URL {} is defining elements for sealed path {}", url, packageName);
}
}
}
Expand All @@ -303,7 +300,7 @@ public Class<?> findClass(final String name) throws ClassNotFoundException {
return clazz;
} catch (Exception e) {
invalidClasses.add(name);
if (DEBUG) logger.trace("Exception encountered attempting classloading of {}", name, e);
if (DEBUG) LOGGER.trace("Exception encountered attempting classloading of {}", name, e);
throw new ClassNotFoundException(name, e);
}
}
Expand Down Expand Up @@ -417,17 +414,17 @@ public Set<String> getTransformerExclusions() {
String resourcePath = name.replace('.', '/').concat(".class");
URL classResource = findResource(resourcePath);
if (classResource == null) {
if (DEBUG) logger.trace("Failed to find class resource {}", resourcePath);
if (DEBUG) LOGGER.trace("Failed to find class resource {}", resourcePath);
negativeResourceCache.add(name);
return null;
}
try (InputStream classStream = classResource.openStream()) {
if (DEBUG) logger.trace("Loading class {} from resource {}", name, classResource);
if (DEBUG) LOGGER.trace("Loading class {} from resource {}", name, classResource);
byte[] data = requireNonNull(readFully(classStream));
resourceCache.put(name, data);
return data;
} catch (Exception e) {
if (DEBUG) logger.trace("Failed to load class {} from resource {}", name, classResource);
if (DEBUG) LOGGER.trace("Failed to load class {} from resource {}", name, classResource);
negativeResourceCache.add(name);
return null;
}
Expand All @@ -453,7 +450,7 @@ public void clearNegativeEntries(@NotNull Set<String> entriesToClear) {

return os.toByteArray();
} catch (Throwable t) {
logger.warn("Problem reading stream fully", t);
LOGGER.warn("Problem reading stream fully", t);
return null;
}
}
Expand All @@ -468,15 +465,15 @@ private void saveTransformedClass(byte @NotNull [] data, @NotNull String transfo
Files.createDirectories(classFile);

if (Files.exists(classFile)) {
logger.warn("Transformed class \"{}\" already exists! Deleting old class", transformedName);
LOGGER.warn("Transformed class \"{}\" already exists! Deleting old class", transformedName);
Files.delete(classFile);
}

try (OutputStream output = Files.newOutputStream(classFile, StandardOpenOption.CREATE_NEW)) {
logger.debug("Saving transformed class \"{}\" to \"{}\"", transformedName, classFile);
LOGGER.debug("Saving transformed class \"{}\" to \"{}\"", transformedName, classFile);
output.write(data);
} catch (IOException ex) {
logger.warn("Could not save transformed class \"{}\"", transformedName, ex);
LOGGER.warn("Could not save transformed class \"{}\"", transformedName, ex);
}
}

Expand Down Expand Up @@ -515,18 +512,18 @@ private URLConnection findCodeSourceConnectionFor(@NotNull String name) {

private byte @Nullable [] runTransformers(@NotNull String name, @NotNull String transformedName, byte @Nullable [] basicClass) {
if (DEBUG_FINER)
logger.trace("Beginning transform of {{} ({})} Start Length: {}", name, transformedName, basicClass != null ? basicClass.length : 0);
LOGGER.trace("Beginning transform of {{} ({})} Start Length: {}", name, transformedName, basicClass != null ? basicClass.length : 0);

for (final IClassTransformer transformer : transformers) {
final String transName = transformer.getClass().getName();

if (DEBUG_FINER)
logger.trace("Before Transformer {{} ({})} {}: {}", name, transformedName, transName, basicClass != null ? basicClass.length : 0);
LOGGER.trace("Before Transformer {{} ({})} {}: {}", name, transformedName, transName, basicClass != null ? basicClass.length : 0);

basicClass = transformer.transform(name, transformedName, basicClass);

if (DEBUG_FINER)
logger.trace("After Transformer {{} ({})} {}: {}", name, transformedName, transName, basicClass != null ? basicClass.length : 0);
LOGGER.trace("After Transformer {{} ({})} {}: {}", name, transformedName, transName, basicClass != null ? basicClass.length : 0);
}
return basicClass;
}
Expand Down
16 changes: 8 additions & 8 deletions java21/src/main/java/org/leavesmc/leavesclip/AutoUpdate.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class AutoUpdate {
import static org.leavesmc.leavesclip.Leavesclip.LOGGER;

public class AutoUpdate {
public static String autoUpdateCorePath;
public static String autoUpdateDir = "auto_update";
public static boolean useAutoUpdateJar = false;
private static final Logger logger = LoggerFactory.getLogger("AutoUpdate");


public static void init() {
File workingDirFile = new File(autoUpdateDir);

Expand All @@ -36,21 +36,21 @@ public static void init() {
autoUpdateCorePath = firstLine;
File jarFile = new File(autoUpdateCorePath);
if (!jarFile.isFile() || !jarFile.exists()) {
logger.warn("The specified server core: {} does not exist. Using the original jar!", autoUpdateCorePath);
LOGGER.warn("The specified server core: {} does not exist. Using the original jar!", autoUpdateCorePath);
return;
}

useAutoUpdateJar = true;

if (!detectionLeavesclipVersion(autoUpdateCorePath)) {
logger.warn("Leavesclip version detection in server core: {} failed. Using the original jar!", autoUpdateCorePath);
LOGGER.warn("Leavesclip version detection in server core: {} failed. Using the original jar!", autoUpdateCorePath);
useAutoUpdateJar = false;
return;
}

logger.info("Using server core: {} provide by Leavesclip-Auto-Update", autoUpdateCorePath);
LOGGER.info("Using server core: {} provide by Leavesclip-Auto-Update", autoUpdateCorePath);
} catch (IOException e) {
logger.error(e.getLocalizedMessage(), e);
LOGGER.error(e.getLocalizedMessage(), e);
}
}

Expand Down Expand Up @@ -102,7 +102,7 @@ public static InputStream getResourceAsStream(String jarPath, String name) {
throw new IOException(name + " not found in our jar or in the " + jarPath);
}
} catch (IOException e) {
logger.error(e.getLocalizedMessage(), e);
LOGGER.error(e.getLocalizedMessage(), e);
}
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static java.nio.file.StandardOpenOption.WRITE;
import static org.leavesmc.leavesclip.Leavesclip.LOGGER;

record DownloadContext(byte[] hash, URL url, String fileName) {

Expand Down Expand Up @@ -49,16 +50,15 @@ public void download(final Path outputDir) throws IOException {
}
Files.deleteIfExists(outputFile);

System.out.println("Downloading " + this.fileName);
LOGGER.info("Downloading " + this.fileName);

try (
final ReadableByteChannel source = Channels.newChannel(this.url.openStream());
final FileChannel fileChannel = FileChannel.open(outputFile, CREATE, WRITE, TRUNCATE_EXISTING)
) {
fileChannel.transferFrom(source, 0, Long.MAX_VALUE);
} catch (final IOException e) {
System.err.println("Failed to download " + this.fileName);
e.printStackTrace();
LOGGER.error("Failed to download {}", this.fileName, e);
System.exit(1);
}

Expand Down
16 changes: 8 additions & 8 deletions java21/src/main/java/org/leavesmc/leavesclip/Leavesclip.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import java.util.*;

public final class Leavesclip {
private static final Logger logger = LoggerFactory.getLogger("Leavesclip");
public static final Logger LOGGER = LoggerFactory.getLogger("Leavesclip");
private static final String DEFAULT_TWEAK = "org.spongepowered.asm.launch.MixinTweaker";
public static LaunchClassLoader classLoader;
public static Map<String, Object> blackboard = new HashMap<>();
Expand All @@ -36,7 +36,7 @@ public static void main(final String[] args) {

private Leavesclip(final String[] args) {
if (Path.of("").toAbsolutePath().toString().contains("!")) {
logger.error("Leavesclip may not run in a directory containing '!'. Please rename the affected folder.");
LOGGER.error("Leavesclip may not run in a directory containing '!'. Please rename the affected folder.");
System.exit(1);
}

Expand Down Expand Up @@ -92,14 +92,14 @@ private Leavesclip(final String[] args) {
final String tweakName = it.next();
// Safety check - don't reprocess something we've already visited
if (visitedTweakerNames.contains(tweakName)) {
logger.warn("Tweak class name {} has already been visited -- skipping", tweakName);
LOGGER.warn("Tweak class name {} has already been visited -- skipping", tweakName);
// remove the tweaker from the stack otherwise it will create an infinite loop
it.remove();
continue;
} else {
visitedTweakerNames.add(tweakName);
}
logger.info("Loading tweak class name {}", tweakName);
LOGGER.info("Loading tweak class name {}", tweakName);

// Ensure we allow the tweak class to load with the parent classloader
classLoader.getClassLoaderExclusions().add(tweakName.substring(0, tweakName.lastIndexOf('.')));
Expand All @@ -111,7 +111,7 @@ private Leavesclip(final String[] args) {
it.remove();
// If we haven't visited a tweaker yet, the first will become the 'primary' tweaker
if (primaryTweaker == null) {
logger.info("Using primary tweak class name {}", tweakName);
LOGGER.info("Using primary tweak class name {}", tweakName);
primaryTweaker = tweaker;
}
}
Expand All @@ -122,7 +122,7 @@ private Leavesclip(final String[] args) {
// Now, iterate all the tweakers we just instantiated
while (!pendingTweakers.isEmpty()) {
final ITweaker tweaker = pendingTweakers.removeFirst();
logger.info("Calling tweak class {}", tweaker.getClass().getName());
LOGGER.info("Calling tweak class {}", tweaker.getClass().getName());
tweaker.acceptOptions(options.valuesOf(nonOption));
tweaker.injectIntoClassLoader(classLoader);
allTweakers.add(tweaker);
Expand All @@ -137,12 +137,12 @@ private Leavesclip(final String[] args) {
}

final String mainClassName = findMainClass();
logger.info("Starting {}", mainClassName);
LOGGER.info("Starting {}", mainClassName);

final Thread runThread = getServerMainThread(args, argumentList, mainClassName);
runThread.start();
} catch (Exception e) {
logger.error("Unable to launch", e);
LOGGER.error("Unable to launch", e);
System.exit(1);
}
}
Expand Down
6 changes: 4 additions & 2 deletions java21/src/main/java/org/leavesmc/leavesclip/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import static org.leavesmc.leavesclip.Leavesclip.LOGGER;

class Util {

private Util() {
Expand Down Expand Up @@ -107,9 +109,9 @@ private static int getHexValue(final char c) {
}

static RuntimeException fail(final String message, final Throwable err) {
System.err.println(message);
LOGGER.error(message);
if (err != null) {
err.printStackTrace();
LOGGER.error("Error", err);
}
System.exit(1);
throw new InternalError();
Expand Down

0 comments on commit 3c639f7

Please sign in to comment.