Revert "Merge pull request #533 from s0cks/feature/log-appender"

This reverts commit 26ce237d89, reversing
changes made to 3064469d6a.
This commit is contained in:
Ryan Dowling 2022-07-18 18:08:53 +10:00
parent 0ee7a905f4
commit fab0b235ad
No known key found for this signature in database
GPG key ID: 5539FCDB88950EFD
107 changed files with 1532 additions and 1769 deletions

View file

@ -1,20 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="delegatedBuild" value="true" />
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
</GradleProjectSettings>
</option>
</GradleProjectSettings>
</option>
</component>
</component>
</project>

View file

@ -54,11 +54,6 @@ import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.text.DefaultEditorKit;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.core.config.Configurator;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.builders.HTMLBuilder;
@ -74,11 +69,11 @@ import com.atlauncher.gui.TrayMenu;
import com.atlauncher.gui.dialogs.SetupDialog;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.InstanceManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.PackManager;
import com.atlauncher.network.ErrorReporting;
import com.atlauncher.themes.ATLauncherLaf;
import com.atlauncher.utils.Java;
import com.atlauncher.utils.LoggingUtils;
import com.atlauncher.utils.OS;
import com.atlauncher.utils.Utils;
import com.formdev.flatlaf.extras.FlatInspector;
@ -101,8 +96,6 @@ import oshi.software.os.OperatingSystem;
* application is launched.
*/
public class App {
private static final Logger LOG = LogManager.getLogger();
public static String[] PASSED_ARGS;
/**
@ -133,10 +126,10 @@ public class App {
public static boolean discordInitialized = false;
/**
* This allows skipping the setup Dialog on first run. This is mainly used for
* This allows skipping the setup dialog on first run. This is mainly used for
* automation tests. It can be skipped with the below command line argument.
* <p/>
* --skip-setup-Dialog
* --skip-setup-dialog
*/
public static boolean skipSetupDialog = false;
@ -266,7 +259,6 @@ public class App {
* @param args all the arguments passed in from the command line
*/
public static void main(String[] args) {
LoggingUtils.redirectSystemOutLogs();
PASSED_ARGS = args;
// Parse all the command line arguments
@ -284,10 +276,10 @@ public class App {
setupOSSpecificThings();
try {
LOG.info("Organising filesystem");
LogManager.info("Organising filesystem");
FileSystem.organise();
} catch (IOException e) {
LOG.error("Error organising filesystem", e);
LogManager.logStackTrace("Error organising filesystem", e, false);
}
// Load the settings from json, convert old properties config and validate it
@ -319,6 +311,7 @@ public class App {
SwingUtilities.invokeLater(() -> ss.setVisible(true));
console = new LauncherConsole();
LogManager.start();
if (!noConsole && settings.enableConsole) {
// Show the console if enabled.
@ -328,7 +321,7 @@ public class App {
try {
Language.init();
} catch (IOException e1) {
LOG.error("Error loading language", e1);
LogManager.logStackTrace("Error loading language", e1);
}
if (!noConsole && settings.enableConsole) {
@ -341,23 +334,23 @@ public class App {
// Try to enable the tray icon.
trySystemTrayIntegration();
} catch (Exception e) {
LOG.error(e);
LogManager.logStackTrace(e, false);
}
}
// log out the system information to the console
logSystemInformation(args);
LOG.info("Showing splash screen and loading everything");
LogManager.info("Showing splash screen and loading everything");
launcher.loadEverything(); // Loads everything that needs to be loaded
LOG.info("Launcher finished loading everything");
LogManager.info("Launcher finished loading everything");
if (settings.firstTimeRun) {
if (skipSetupDialog) {
App.settings.firstTimeRun = false;
App.settings.save();
} else {
LOG.warn("Launcher not setup. Loading Setup Dialog");
LogManager.warn("Launcher not setup. Loading Setup Dialog");
new SetupDialog();
}
}
@ -369,14 +362,14 @@ public class App {
i -> i.getName().equalsIgnoreCase(autoLaunch) || i.getSafeName().equalsIgnoreCase(autoLaunch))
.findFirst();
if (instance.isPresent()) {
LOG.info("Opening Instance " + instance.get().launcher.name);
LogManager.info("Opening Instance " + instance.get().launcher.name);
if (instance.get().launch()) {
open = false;
} else {
LOG.error("Error Opening Instance " + instance.get().launcher.name);
LogManager.error("Error Opening Instance " + instance.get().launcher.name);
}
} else {
LOG.error("Couldn't find instance with name of " + autoLaunch + " to auto launch.");
LogManager.error("Couldn't find instance with name of " + autoLaunch + " to auto launch.");
}
}
@ -384,12 +377,12 @@ public class App {
if (PackManager.addPack(packCodeToAdd)) {
Pack packAdded = PackManager.getSemiPublicPackByCode(packCodeToAdd);
if (packAdded != null) {
LOG.info("The pack " + packAdded.getName() + " was automatically added to the launcher!");
LogManager.info("The pack " + packAdded.getName() + " was automatically added to the launcher!");
} else {
LOG.error("Error automatically adding semi public pack with code of " + packCodeToAdd + "!");
LogManager.error("Error automatically adding semi public pack with code of " + packCodeToAdd + "!");
}
} else {
LOG.error("Error automatically adding semi public pack with code of " + packCodeToAdd + "!");
LogManager.error("Error automatically adding semi public pack with code of " + packCodeToAdd + "!");
}
}
@ -412,41 +405,41 @@ public class App {
Runtime.getRuntime().addShutdownHook(new Thread(DiscordRPC::discordShutdown));
} catch (Throwable e) {
LOG.error("Failed to initialize Discord integration", e);
LogManager.logStackTrace("Failed to initialize Discord integration", e);
discordInitialized = false;
}
}
}
private static void logSystemInformation(String[] args) {
LOG.info(Constants.LAUNCHER_NAME + " Version: " + Constants.VERSION);
LogManager.info(Constants.LAUNCHER_NAME + " Version: " + Constants.VERSION);
LOG.info(String.format("App Arguments: %s", Gsons.DEFAULT_SLIM.toJson(args)));
LogManager.info(String.format("App Arguments: %s", Gsons.DEFAULT_SLIM.toJson(args)));
LOG.info(String.format("JVM Arguments: %s",
LogManager.info(String.format("JVM Arguments: %s",
Gsons.DEFAULT_SLIM.toJson(ManagementFactory.getRuntimeMXBean().getInputArguments())));
SwingUtilities.invokeLater(
() -> Java.getInstalledJavas().forEach(version -> LOG.debug(Gsons.DEFAULT.toJson(version))));
() -> Java.getInstalledJavas().forEach(version -> LogManager.debug(Gsons.DEFAULT.toJson(version))));
LOG.info("Java Version: "
LogManager.info("Java Version: "
+ String.format("Java %d (%s)", Java.getLauncherJavaVersionNumber(), Java.getLauncherJavaVersion()));
LOG.info("Java Path: " + settings.javaPath);
LogManager.info("Java Path: " + settings.javaPath);
LOG.info("64 Bit Java: " + Java.is64Bit());
LogManager.info("64 Bit Java: " + Java.is64Bit());
int maxRam = OS.getMaximumRam();
LOG.info("RAM Available: " + (maxRam == 0 ? "Unknown" : maxRam + "MB"));
LogManager.info("RAM Available: " + (maxRam == 0 ? "Unknown" : maxRam + "MB"));
LOG.info("Launcher Directory: " + FileSystem.BASE_DIR);
LogManager.info("Launcher Directory: " + FileSystem.BASE_DIR);
if (OS.isMac()) {
LOG.info("Using Mac App? " + (OS.isUsingMacApp() ? "Yes" : "No"));
LogManager.info("Using Mac App? " + (OS.isUsingMacApp() ? "Yes" : "No"));
}
if (OS.isUsingFlatpak()) {
LOG.info("Using Flatpak!");
LogManager.info("Using Flatpak!");
}
try {
@ -456,32 +449,33 @@ public class App {
List<GraphicsCard> cards = hal.getGraphicsCards();
if (cards.size() != 0) {
for (GraphicsCard card : cards) {
LOG.info("GPU: " + card.getName() + " (" + card.getVendor() + ") " + card.getVersionInfo()
LogManager.info("GPU: " + card.getName() + " (" + card.getVendor() + ") " + card.getVersionInfo()
+ " " + (card.getVRam() / 1048576) + "MB VRAM");
}
}
CentralProcessor cpu = hal.getProcessor();
LOG.info(String.format("CPU: %s %d cores/%d threads", cpu.getProcessorIdentifier().getName().trim(),
LogManager.info(String.format("CPU: %s %d cores/%d threads", cpu.getProcessorIdentifier().getName().trim(),
cpu.getPhysicalProcessorCount(), cpu.getLogicalProcessorCount()));
OperatingSystem os = systemInfo.getOperatingSystem();
LOG.info("Operating System: " + os.getFamily() + " (" + os.getVersionInfo() + ")");
LOG.info("Bitness: " + os.getBitness());
LOG.info("Uptime: " + os.getSystemUptime());
LOG.info("Manufacturer: " + os.getManufacturer());
LogManager.info("Operating System: " + os.getFamily() + " (" + os.getVersionInfo() + ")");
LogManager.info("Bitness: " + os.getBitness());
LogManager.info("Uptime: " + os.getSystemUptime());
LogManager.info("Manufacturer: " + os.getManufacturer());
if (OS.isWindows() && OS.isUsingAntivirus()) {
LOG.error(
LogManager.warn(
"A running antivirus process was found on your system. If you notice any issues running Minecraft or downloading files, please whitelist ATLauncher and its folder in your antivirus program/s listed below.");
for (OSProcess process : OS.getAntivirusProcesses()) {
LOG.info(String.format("Process %s (running at %s)", process.getName(), process.getPath()));
LogManager.info(String.format("Process %s (running at %s)", process.getName(),
process.getPath()));
}
}
} catch (Throwable t) {
LOG.error("error: ", t);
LogManager.logStackTrace(t);
}
}
@ -553,7 +547,7 @@ public class App {
if (javaOptions != null && (javaOptions.toLowerCase().contains("-xmx")
|| javaOptions.toLowerCase().contains("-xms") || javaOptions.toLowerCase().contains("-xss"))) {
LOG.warn("_JAVA_OPTIONS environment variable detected: " + javaOptions);
LogManager.warn("_JAVA_OPTIONS environment variable detected: " + javaOptions);
if (!settings.ignoreJavaOptionsWarning) {
int ret = DialogManager.yesNoDialog().addOption(GetText.tr("Don't remind me again"))
@ -579,7 +573,7 @@ public class App {
private static void checkForBadFolderInstall() {
if (!settings.ignoreOneDriveWarning && FileSystem.BASE_DIR.toString().contains("OneDrive")) {
LOG.warn("ATLauncher installed within OneDrive!");
LogManager.warn("ATLauncher installed within OneDrive!");
int ret = DialogManager.yesNoDialog().addOption(GetText.tr("Don't remind me again"))
.setTitle(GetText.tr("ATLauncher installed within OneDrive"))
@ -599,7 +593,7 @@ public class App {
if (OS.isWindows() && !settings.ignoreProgramFilesWarning
&& FileSystem.BASE_DIR.toString().contains("Program Files")) {
LOG.warn("ATLauncher installed within Program Files!");
LogManager.warn("ATLauncher installed within Program Files!");
int ret = DialogManager.yesNoDialog().addOption(GetText.tr("Don't remind me again"))
.setTitle(GetText.tr("ATLauncher installed within Program Files"))
@ -622,7 +616,7 @@ public class App {
try {
if ((!testFile.exists() && !testFile.createNewFile())
|| !FileSystem.BASE_DIR.resolve(".test").toFile().canWrite()) {
LOG.error("ATLauncher cannot write files!");
LogManager.error("ATLauncher cannot write files!");
DialogManager.okDialog().setTitle(GetText.tr("ATLauncher cannot write files"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
@ -634,7 +628,7 @@ public class App {
System.exit(0);
}
} catch (IOException e) {
LOG.error("ATLauncher cannot write files!");
LogManager.error("ATLauncher cannot write files!");
DialogManager.okDialog().setTitle(GetText.tr("ATLauncher cannot write files"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
@ -660,7 +654,7 @@ public class App {
Method setDockIconImage = util.getMethod("setDockIconImage", Image.class);
setDockIconImage.invoke(application, Utils.getImage("/assets/image/icon-osx.png"));
} catch (Exception ex) {
LOG.error(MarkerManager.getMarker("NoReporting"), "Failed to set dock icon", ex);
LogManager.logStackTrace("Failed to set dock icon", ex);
}
}
@ -698,7 +692,7 @@ public class App {
try (FileReader fileReader = new FileReader(FileSystem.SETTINGS.toFile())) {
settings = Gsons.DEFAULT.fromJson(fileReader, Settings.class);
} catch (Throwable t) {
LOG.error("Error loading settings, using defaults", t, false);
LogManager.logStackTrace("Error loading settings, using defaults", t, false);
settings = new Settings();
}
} else {
@ -711,14 +705,14 @@ public class App {
properties.load(fileReader);
settings.convert(properties);
} catch (Throwable t) {
LOG.error("Error loading settings, using defaults", t, false);
LogManager.logStackTrace("Error loading settings, using defaults", t, false);
settings = new Settings();
}
try {
Files.delete(FileSystem.LAUNCHER_CONFIG);
} catch (IOException e) {
LOG.warn("Failed to delete old launcher config.");
LogManager.warn("Failed to delete old launcher config.");
}
}
@ -895,32 +889,39 @@ public class App {
System.exit(0);
}
if (options.has("debug")) {
Configurator.setAllLevels(LogManager.getRootLogger().getName(), Level.DEBUG);
}
if (options.has("updated")) {
wasUpdated = true;
}
if (options.has("debug")) {
LogManager.showDebug = true;
LogManager.debugLevel = 1;
LogManager.debug("Debug logging is enabled! Please note that this will remove any censoring of user data!");
}
if (options.has("debug-level")) {
LogManager.debugLevel = (Integer) options.valueOf("debug-level");
LogManager.debug("Debug level has been set to " + options.valueOf("debug-level") + "!");
}
skipSetupDialog = options.has("skip-setup-dialog");
if (skipSetupDialog) {
LOG.debug("Skipping setup dialog!");
LogManager.debug("Skipping setup dialog!");
}
skipTrayIntegration = options.has("skip-tray-integration");
if (skipTrayIntegration) {
LOG.debug("Skipping tray integration!");
LogManager.debug("Skipping tray integration!");
}
disableAnalytics = options.has("disable-analytics");
if (disableAnalytics) {
LOG.debug("Disabling analytics!");
LogManager.debug("Disabling analytics!");
}
disableErrorReporting = options.has("disable-error-reporting");
if (disableErrorReporting) {
LOG.debug("Disabling error reporting!");
LogManager.debug("Disabling error reporting!");
}
if (options.has("working-dir")) {
@ -932,41 +933,41 @@ public class App {
String baseLauncherDomain = String.valueOf(options.valueOf("base-launcher-domain"));
Constants.setBaseLauncherDomain(baseLauncherDomain);
LOG.warn("Base launcher domain set to " + baseLauncherDomain);
LogManager.warn("Base launcher domain set to " + baseLauncherDomain);
}
if (options.has("base-cdn-domain")) {
String baseCdnDomain = String.valueOf(options.valueOf("base-cdn-domain"));
Constants.setBaseCdnDomain(baseCdnDomain);
LOG.warn("Base cdn domain set to " + baseCdnDomain);
LogManager.warn("Base cdn domain set to " + baseCdnDomain);
}
if (options.has("base-cdn-path")) {
String baseCdnPath = String.valueOf(options.valueOf("base-cdn-path"));
Constants.setBaseCdnPath(baseCdnPath);
LOG.warn("Base cdn path set to " + baseCdnPath);
LogManager.warn("Base cdn path set to " + baseCdnPath);
}
allowAllSslCerts = options.has("allow-all-ssl-certs");
if (allowAllSslCerts) {
LOG.warn("Allowing all ssl certs. This is insecure and should only be used for development.");
LogManager.warn("Allowing all ssl certs. This is insecure and should only be used for development.");
}
noLauncherUpdate = options.has("no-launcher-update");
if (noLauncherUpdate) {
LOG.debug("Not updating the launcher!");
LogManager.debug("Not updating the launcher!");
}
noConsole = options.has("no-console");
if (noConsole) {
LOG.debug("Not showing console!");
LogManager.debug("Not showing console!");
}
closeLauncher = options.has("close-launcher");
if (closeLauncher) {
LOG.debug("Closing launcher once Minecraft is launched!");
LogManager.debug("Closing launcher once Minecraft is launched!");
}
if (options.has("proxy-type") && options.has("proxy-host") && options.has("proxy-port")) {
@ -977,7 +978,7 @@ public class App {
Proxy proxy = new java.net.Proxy(java.net.Proxy.Type.valueOf(proxyType),
new InetSocketAddress(proxyHost, proxyPort));
LOG.warn("Proxy set to " + proxy);
LogManager.warn("Proxy set to " + proxy);
ProxySelector.setDefault(new ProxySelector() {
@Override
@ -987,7 +988,7 @@ public class App {
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException e) {
LOG.error("Connection could not be established to proxy at socket [" + sa + "]", e);
LogManager.logStackTrace("Connection could not be established to proxy at socket [" + sa + "]", e);
}
});
}
@ -995,7 +996,7 @@ public class App {
if (options.has("config-override")) {
configOverride = (String) options.valueOf("config-override");
LOG.warn("Config overridden: " + configOverride);
LogManager.warn("Config overridden: " + configOverride);
}
}
}

View file

@ -17,14 +17,11 @@
*/
package com.atlauncher;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.managers.LogManager;
public final class ExceptionStrainer implements Thread.UncaughtExceptionHandler {
private static final Logger LOG = LogManager.getLogger(ExceptionStrainer.class);
@Override
public void uncaughtException(Thread t, Throwable e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}

View file

@ -24,18 +24,14 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.constants.Constants;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.FileUtils;
import com.atlauncher.utils.OS;
import com.atlauncher.utils.Utils;
public final class FileSystem {
private static final Logger LOG = LogManager.getLogger(FileSystem.class);
private static Path CACHED_USER_DOWNLOADS = null;
public static final Path BASE_DIR = FileSystem.getCoreGracefully();
public static final Path LOGS = BASE_DIR.resolve("logs");
public static final Path BACKUPS = BASE_DIR.resolve("backups");
@ -116,7 +112,8 @@ public final class FileSystem {
try {
return Paths.get(App.settings.customDownloadsPath);
} catch (Exception e) {
LOG.error("Problem when reading custom downloads path, defaulting to user downloads folder.", e);
LogManager.logStackTrace(
"Problem when reading custom downloads path, defaulting to user downloads folder.", e);
}
}
@ -143,7 +140,7 @@ public final class FileSystem {
}
}
} catch (Exception e) {
LOG.error("Problem when reading in registry", e);
LogManager.logStackTrace("Problem when reading in registry", e);
}
CACHED_USER_DOWNLOADS = Paths.get(System.getProperty("user.home"), "Downloads");
@ -199,7 +196,7 @@ public final class FileSystem {
Files.move(intermediaryPath, to, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
LOG.error("Error renaming directory:", e);// don't send
LogManager.logStackTrace("Error renaming directory", e, false);
}
}

View file

@ -34,8 +34,6 @@ import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.builders.HTMLBuilder;
@ -52,6 +50,7 @@ import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.CurseForgeUpdateManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.InstanceManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.atlauncher.managers.ModpacksChUpdateManager;
import com.atlauncher.managers.ModrinthModpackUpdateManager;
@ -72,8 +71,6 @@ import net.arikia.dev.drpc.DiscordRPC;
import okhttp3.OkHttpClient;
public class Launcher {
private static final Logger LOG = LogManager.getLogger(Launcher.class);
// Holding update data
private LauncherVersion latestLauncherVersion; // Latest Launcher version
private List<DownloadableFile> launcherFiles; // Files the Launcher needs to download
@ -124,7 +121,7 @@ public class Launcher {
PackManager.removeUnusedImages(); // remove unused pack images
if (OS.isWindows() && !Java.is64Bit() && OS.is64Bit()) {
LOG.warn("You're using 32 bit Java on a 64 bit Windows install!");
LogManager.warn("You're using 32 bit Java on a 64 bit Windows install!");
int ret = DialogManager.yesNoDialog().setTitle(GetText.tr("Running 32 Bit Java on 64 Bit Windows"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
@ -151,7 +148,7 @@ public class Launcher {
this.latestLauncherVersion = Gsons.DEFAULT
.fromJson(new FileReader(FileSystem.JSON.resolve("version.json").toFile()), LauncherVersion.class);
} catch (JsonSyntaxException | FileNotFoundException | JsonIOException e) {
LOG.error("Exception when loading latest launcher version!", e);
LogManager.logStackTrace("Exception when loading latest launcher version!", e);
}
return this.latestLauncherVersion != null && Constants.VERSION.needsUpdate(this.latestLauncherVersion);
@ -170,7 +167,7 @@ public class Launcher {
toget = "jar";
}
File newFile = FileSystem.TEMP.resolve(saveAs).toFile();
LOG.info("Downloading Launcher Update");
LogManager.info("Downloading Launcher Update");
Analytics.sendEvent("Update", "Launcher");
ProgressDialog<Boolean> progressDialog = new ProgressDialog<>(GetText.tr("Downloading Launcher Update"), 1,
@ -185,7 +182,7 @@ public class Launcher {
try {
download.downloadFile();
} catch (IOException e) {
LOG.error("Failed to download update", e);
LogManager.logStackTrace("Failed to download update", e);
progressDialog.setReturnValue(false);
progressDialog.close();
return;
@ -201,7 +198,7 @@ public class Launcher {
runUpdate(path, newFile.getAbsolutePath());
}
} catch (IOException e) {
LOG.error("Error downloading update", e);
LogManager.logStackTrace(e);
}
}
@ -225,12 +222,12 @@ public class Launcher {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(arguments);
LOG.info("Running launcher update with command " + arguments);
LogManager.info("Running launcher update with command " + arguments);
try {
processBuilder.start();
} catch (IOException e) {
LOG.error("failed to start the launcher:", e);
LogManager.logStackTrace(e);
}
System.exit(0);
@ -249,7 +246,7 @@ public class Launcher {
this.launcherFiles = com.atlauncher.network.Download.build().cached()
.setUrl(String.format("%s/launcher/json/files.json", Constants.DOWNLOAD_SERVER)).asType(type);
} catch (Exception e) {
LOG.error("Error loading in file hashes!", e);
LogManager.logStackTrace("Error loading in file hashes!", e);
return null;
}
}
@ -281,7 +278,7 @@ public class Launcher {
}));
progressDialog.start();
LOG.info("Finished downloading updated files!");
LogManager.info("Finished downloading updated files!");
}
public boolean checkForUpdatedFiles() {
@ -299,7 +296,7 @@ public class Launcher {
* differ from what the user has
*/
public boolean hasUpdatedFiles() {
LOG.info("Checking for updated files!");
LogManager.info("Checking for updated files!");
List<com.atlauncher.network.Download> downloads = getLauncherFiles();
if (downloads == null) {
@ -377,7 +374,7 @@ public class Launcher {
private void checkForLauncherUpdate() {
PerformanceManager.start();
LOG.debug("Checking for launcher update");
LogManager.debug("Checking for launcher update");
if (launcherHasUpdate()) {
if (App.noLauncherUpdate) {
int ret = DialogManager.okDialog().setTitle("Launcher Update Available")
@ -407,8 +404,7 @@ public class Launcher {
System.exit(0);
}
}
LOG.debug("Finished checking for launcher update");
LogManager.debug("Finished checking for launcher update");
PerformanceManager.end();
}
@ -515,7 +511,7 @@ public class Launcher {
public void killMinecraft() {
if (this.minecraftProcess != null) {
LOG.error("Killing Minecraft");
LogManager.error("Killing Minecraft");
if (App.discordInitialized) {
DiscordRPC.discordClearPresence();
@ -524,7 +520,7 @@ public class Launcher {
this.minecraftProcess.destroy();
this.minecraftProcess = null;
} else {
LOG.error("Cannot kill Minecraft as there is no instance open!");
LogManager.error("Cannot kill Minecraft as there is no instance open!");
}
}
}

View file

@ -28,8 +28,6 @@ import java.util.UUID;
import javax.swing.ImageIcon;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.FileSystem;
@ -38,6 +36,7 @@ import com.atlauncher.gui.tabs.InstancesTab;
import com.atlauncher.gui.tabs.ServersTab;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import com.atlauncher.utils.SkinUtils;
import com.atlauncher.utils.Utils;
@ -47,8 +46,6 @@ import com.mojang.util.UUIDTypeAdapter;
* This class deals with the Accounts in the launcher.
*/
public abstract class AbstractAccount implements Serializable {
private static final Logger LOG = LogManager.getLogger(AbstractAccount.class);
/**
* Auto generated serial.
*/
@ -118,11 +115,8 @@ public abstract class AbstractAccount implements Serializable {
}
if (!currentUsername.equals(this.minecraftUsername)) {
LOG.info("The username for account with UUID of {} changed from {} to {}",
this.getUUIDNoDashes(),
this.minecraftUsername,
currentUsername);
LogManager.info("The username for account with UUID of " + this.getUUIDNoDashes() + " changed from "
+ this.minecraftUsername + " to " + currentUsername);
this.minecraftUsername = currentUsername;
dialog.setReturnValue(true);
}
@ -157,8 +151,7 @@ public abstract class AbstractAccount implements Serializable {
if (!this.skinUpdating) {
this.skinUpdating = true;
final File file = FileSystem.SKINS.resolve(this.getUUIDNoDashes() + ".png").toFile();
LOG.info("Downloading skin for " + this.minecraftUsername);
LogManager.info("Downloading skin for " + this.minecraftUsername);
final ProgressDialog<Boolean> dialog = new ProgressDialog<>(GetText.tr("Downloading Skin"), 0,
GetText.tr("Downloading Skin For {0}", this.minecraftUsername),
"Aborting downloading Minecraft skin for " + this.minecraftUsername);
@ -167,7 +160,7 @@ public abstract class AbstractAccount implements Serializable {
dialog.setReturnValue(false);
String skinURL = getSkinUrl();
if (skinURL == null) {
LOG.warn("Couldn't download skin because the url found was NULL. Using default skin");
LogManager.warn("Couldn't download skin because the url found was NULL. Using default skin");
if (!file.exists()) {
String skinFilename = "default.png";
@ -181,7 +174,7 @@ public abstract class AbstractAccount implements Serializable {
java.nio.file.Files.copy(
Utils.getResourceInputStream("/assets/image/skins/" + skinFilename), file.toPath());
} catch (IOException e) {
LOG.error("error copying skin", e);
LogManager.logStackTrace(e);
}
dialog.setReturnValue(true);
@ -210,14 +203,14 @@ public abstract class AbstractAccount implements Serializable {
Utils.getResourceInputStream("/assets/image/skins/" + skinFilename),
file.toPath());
} catch (IOException e) {
LOG.error("error updating skin", e);
LogManager.logStackTrace(e);
}
dialog.setReturnValue(true);
}
}
} catch (IOException e) {
LOG.error("error updating skin", e);
LogManager.logStackTrace(e);
}
com.atlauncher.evnt.manager.AccountManager.post();
}

View file

@ -23,10 +23,8 @@ import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.gui.tabs.InstancesTab;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Utils;
/**
@ -36,8 +34,6 @@ import com.atlauncher.utils.Utils;
* and MojangAccount and MicrosoftAccount
*/
public class Account implements Serializable {
private static final Logger LOG = LogManager.getLogger(Account.class);
/**
* Auto generated serial.
*/
@ -121,7 +117,7 @@ public class Account implements Serializable {
} else {
this.password = Utils.decrypt(this.encryptedPassword);
if (this.password == null) {
LOG.error("Error reading in saved password from file!");
LogManager.error("Error reading in saved password from file!");
this.password = "";
this.remember = false;
}

View file

@ -28,8 +28,6 @@ import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.format.ISODateTimeFormat;
import org.mini2Dx.gettext.GetText;
@ -44,6 +42,7 @@ import com.atlauncher.exceptions.InvalidMinecraftVersion;
import com.atlauncher.gui.dialogs.CurseForgeProjectFileSelectorDialog;
import com.atlauncher.gui.dialogs.ModrinthVersionSelectorDialog;
import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.CurseForgeApi;
@ -54,8 +53,6 @@ import com.google.gson.annotations.SerializedName;
@SuppressWarnings("serial")
public class DisableableMod implements Serializable {
private static final Logger LOG = LogManager.getLogger(DisableableMod.class);
public String name;
public String version;
public boolean optional;
@ -321,12 +318,12 @@ public class DisableableMod implements Serializable {
}
break;
default:
LOG.warn("Unsupported mod for enabling/disabling {}", this.name);
LogManager.warn("Unsupported mod for enabling/disabling " + this.name);
break;
}
}
if (dir == null) {
LOG.warn("null path returned for mod " + this.name);
LogManager.warn("null path returned for mod " + this.name);
return null;
}
return new File(dir, file);
@ -374,7 +371,7 @@ public class DisableableMod implements Serializable {
file -> file.gameVersions.stream()
.anyMatch(gv -> minecraftVersionsToSearch.contains(gv)));
} catch (InvalidMinecraftVersion e) {
LOG.error(e);
LogManager.logStackTrace(e);
}
}

View file

@ -69,9 +69,6 @@ import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.MarkerManager;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -132,6 +129,7 @@ import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.CurseForgeUpdateManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.InstanceManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.atlauncher.managers.ModpacksChUpdateManager;
import com.atlauncher.managers.ModrinthModpackUpdateManager;
@ -148,7 +146,6 @@ import com.atlauncher.utils.CurseForgeApi;
import com.atlauncher.utils.FileUtils;
import com.atlauncher.utils.Hashing;
import com.atlauncher.utils.Java;
import com.atlauncher.utils.LoggingUtils;
import com.atlauncher.utils.ModrinthApi;
import com.atlauncher.utils.OS;
import com.atlauncher.utils.Utils;
@ -162,8 +159,6 @@ import okhttp3.OkHttpClient;
@Json
public class Instance extends MinecraftVersion {
private static final Logger LOG = LogManager.getLogger(Instance.class);
public String inheritsFrom;
public InstanceLauncher launcher;
@ -348,8 +343,9 @@ public class Instance extends MinecraftVersion {
return new ImageIcon(img.getScaledInstance(300, 150, Image.SCALE_SMOOTH));
} catch (Exception e) {
LOG.error("Error creating scaled image from the custom image of instance {}:", this.launcher.name, e);// don't
// send
LogManager.logStackTrace(
"Error creating scaled image from the custom image of instance " + this.launcher.name, e,
false);
}
}
@ -502,7 +498,7 @@ public class Instance extends MinecraftVersion {
progressDialog.doneTask();
} catch (IOException e) {
LOG.error("Error downloading minecraft", e);
LogManager.logStackTrace(e);
PerformanceManager.end("Downloading Minecraft");
PerformanceManager.end();
return false;
@ -528,7 +524,7 @@ public class Instance extends MinecraftVersion {
progressDialog.doneTask();
} catch (IOException e) {
LOG.error(e);
LogManager.logStackTrace(e);
PerformanceManager.end("Downloading Logging Config");
PerformanceManager.end();
return false;
@ -640,7 +636,7 @@ public class Instance extends MinecraftVersion {
// Files.write(runtimeSystemDirectory.resolve(javaVersion.component
// + ".sha1"), runtimeToDownload.version.name.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
LOG.error("Failed to download Java runtime", e);
LogManager.logStackTrace("Failed to download Java runtime", e);
}
}
}
@ -739,7 +735,7 @@ public class Instance extends MinecraftVersion {
if (!Utils.combineJars(getMinecraftJar(), getRoot().resolve("bin/modpack.jar").toFile(),
getCustomMinecraftJar())) {
LOG.error("Failed to combine jars into custom minecraft.jar");
LogManager.error("Failed to combine jars into custom minecraft.jar");
PerformanceManager.end("Creating custom minecraft.jar");
PerformanceManager.end();
return false;
@ -774,7 +770,7 @@ public class Instance extends MinecraftVersion {
// if Microsoft account must login again, then make sure to do that
if (!offline && account instanceof MicrosoftAccount && ((MicrosoftAccount) account).mustLogin) {
if (!((MicrosoftAccount) account).ensureAccountIsLoggedIn()) {
LOG.info("You must login to your account before continuing.");
LogManager.info("You must login to your account before continuing.");
return false;
}
}
@ -786,7 +782,7 @@ public class Instance extends MinecraftVersion {
.setContent(GetText.tr("Choose your offline player name:")).showInput(playerName);
if (playerName == null || playerName.isEmpty()) {
LOG.info("No player name provided for offline launch, so cancelling launch.");
LogManager.info("No player name provided for offline launch, so cancelling launch.");
return false;
}
}
@ -804,7 +800,7 @@ public class Instance extends MinecraftVersion {
.setType(DialogManager.ERROR).show();
if (ret != 0) {
LOG.warn("Launching of instance cancelled due to user cancelling memory warning!");
LogManager.warn("Launching of instance cancelled due to user cancelling memory warning!");
App.launcher.setMinecraftLaunched(false);
return false;
}
@ -817,7 +813,7 @@ public class Instance extends MinecraftVersion {
this.launcher.requiredPermGen)).build())
.setType(DialogManager.ERROR).show();
if (ret != 0) {
LOG.warn("Launching of instance cancelled due to user cancelling permgen warning!");
LogManager.warn("Launching of instance cancelled due to user cancelling permgen warning!");
App.launcher.setMinecraftLaunched(false);
return false;
}
@ -828,20 +824,21 @@ public class Instance extends MinecraftVersion {
try {
Files.createDirectory(nativesTempDir);
} catch (IOException e2) {
LOG.error(MarkerManager.getMarker("NoReporting"), "Couldn't create natives temp directory", e2);
LogManager.logStackTrace(e2, false);
}
ProgressDialog<Boolean> prepareDialog = new ProgressDialog<>(GetText.tr("Preparing For Launch"), 7,
GetText.tr("Preparing For Launch"));
prepareDialog.addThread(new Thread(() -> {
LOG.info("Preparing for launch!");
LogManager.info("Preparing for launch!");
prepareDialog.setReturnValue(prepareForLaunch(prepareDialog, nativesTempDir));
prepareDialog.close();
}));
prepareDialog.start();
if (prepareDialog.getReturnValue() == null || !prepareDialog.getReturnValue()) {
LOG.error("Failed to prepare instance {} for launch. Check the logs and try again.", this.launcher.name);
LogManager.error(
"Failed to prepare instance " + this.launcher.name + " for launch. Check the logs and try again.");
return false;
}
@ -855,7 +852,8 @@ public class Instance extends MinecraftVersion {
App.launcher.getParent().setVisible(false);
}
LOG.info("Launching pack {} {} for Minecraft {}", this.launcher.pack, this.launcher.version, this.id);
LogManager.info("Launching pack " + this.launcher.pack + " " + this.launcher.version + " for "
+ "Minecraft " + this.id);
Process process = null;
@ -879,7 +877,7 @@ public class Instance extends MinecraftVersion {
session = new LoginResponse(mojangAccount.username);
session.setOffline();
} else {
LOG.info("Logging into Minecraft!");
LogManager.info("Logging into Minecraft!");
ProgressDialog<LoginResponse> loginDialog = new ProgressDialog<>(
GetText.tr("Logging Into Minecraft"), 0, GetText.tr("Logging Into Minecraft"),
"Aborted login to Minecraft!");
@ -902,7 +900,7 @@ public class Instance extends MinecraftVersion {
if (enableCommands && preLaunchCommand != null) {
if (!executeCommand(preLaunchCommand)) {
LOG.error("Failed to execute pre-launch command");
LogManager.error("Failed to execute pre-launch command");
App.launcher.setMinecraftLaunched(false);
@ -919,7 +917,7 @@ public class Instance extends MinecraftVersion {
MicrosoftAccount microsoftAccount = (MicrosoftAccount) account;
if (!offline) {
LOG.info("Logging into Minecraft!");
LogManager.info("Logging into Minecraft!");
ProgressDialog<Boolean> loginDialog = new ProgressDialog<>(GetText.tr("Logging Into Minecraft"),
0, GetText.tr("Logging Into Minecraft"), "Aborted login to Minecraft!");
loginDialog.addThread(new Thread(() -> {
@ -929,7 +927,7 @@ public class Instance extends MinecraftVersion {
loginDialog.start();
if (!(Boolean) loginDialog.getReturnValue()) {
LOG.error("Failed to login");
LogManager.error("Failed to login");
App.launcher.setMinecraftLaunched(false);
if (App.launcher.getParent() != null) {
App.launcher.getParent().setVisible(true);
@ -943,7 +941,7 @@ public class Instance extends MinecraftVersion {
if (enableCommands && preLaunchCommand != null) {
if (!executeCommand(preLaunchCommand)) {
LOG.error("Failed to execute pre-launch command");
LogManager.error("Failed to execute pre-launch command");
App.launcher.setMinecraftLaunched(false);
@ -959,7 +957,7 @@ public class Instance extends MinecraftVersion {
}
if (process == null) {
LOG.error("Failed to get process for Minecraft");
LogManager.error("Failed to get process for Minecraft");
App.launcher.setMinecraftLaunched(false);
if (App.launcher.getParent() != null) {
App.launcher.getParent().setVisible(true);
@ -1031,7 +1029,7 @@ public class Instance extends MinecraftVersion {
detectedError = MinecraftError.USING_NEWER_JAVA_THAN_8;
}
if (!LOG.isDebugEnabled()) {
if (!LogManager.showDebug) {
line = line.replace(account.minecraftUsername, "**MINECRAFTUSERNAME**");
line = line.replace(account.username, "**MINECRAFTUSERNAME**");
line = line.replace(account.uuid, "**UUID**");
@ -1053,7 +1051,7 @@ public class Instance extends MinecraftVersion {
// end of the xml object so parse it
if (line.contains("</log4j:Event>")) {
LoggingUtils.minecraftLog4j(sb.toString());
LogManager.minecraftLog4j(sb.toString());
sb.setLength(0);
}
@ -1063,7 +1061,7 @@ public class Instance extends MinecraftVersion {
}
}
LoggingUtils.minecraft(line);
LogManager.minecraft(line);
}
App.launcher.hideKillMinecraft();
if (App.launcher.getParent() != null && App.settings.keepLauncherOpen) {
@ -1084,13 +1082,14 @@ public class Instance extends MinecraftVersion {
}
if (exitValue != 0) {
LOG.error(
"Oh noes. Minecraft crashed. Please check the logs for any errors and provide these logs when asking for support.");
LogManager.error(
"Oh no. Minecraft crashed. Please check the logs for any errors and provide these logs when asking for support.");
if (this.getPack() != null && !this.getPack().system) {
LOG.info("Checking for modifications to the pack since installation.");
LogManager.info("Checking for modifications to the pack since installation.");
this.launcher.mods.forEach(mod -> {
if (!mod.userAdded && mod.wasSelected && mod.disabled) {
LOG.warn("The mod {} ({}) has been disabled.", mod.name, mod.file);
LogManager.warn("The mod " + mod.name + " (" + mod.file + ") has been disabled.");
}
});
@ -1101,7 +1100,7 @@ public class Instance extends MinecraftVersion {
.noneMatch(m -> m.type == Type.mods && !m.userAdded
&& m.getFile(this).toPath().equals(file)))
.forEach(newMod -> {
LOG.warn("The mod {} has been added.", newMod.getFileName());
LogManager.warn("The mod " + newMod.getFileName().toString() + " has been added.");
});
}
@ -1118,7 +1117,7 @@ public class Instance extends MinecraftVersion {
if (enableCommands && postExitCommand != null) {
if (!executeCommand(postExitCommand)) {
LOG.error("Failed to execute post-exit command");
LogManager.error("Failed to execute post-exit command");
}
}
@ -1149,8 +1148,7 @@ public class Instance extends MinecraftVersion {
System.exit(0);
}
} catch (Exception e1) {
LOG.error("error launching minecraft", e1);
LogManager.logStackTrace(e1);
App.launcher.setMinecraftLaunched(false);
if (App.launcher.getParent() != null) {
App.launcher.getParent().setVisible(true);
@ -1191,16 +1189,16 @@ public class Instance extends MinecraftVersion {
if (reportsDir.exists()) {
for (String filename : reportsDir.list(Utils.getOpenEyePendingReportsFileFilter())) {
File report = new File(reportsDir, filename);
LOG.info("OpenEye: Sending pending crash report located at '{}'", report.getAbsolutePath());
LogManager.info("OpenEye: Sending pending crash report located at '" + report.getAbsolutePath() + "'");
OpenEyeReportResponse response = Utils.sendOpenEyePendingReport(report);
if (response == null) {
// Pending report was never sent due to an issue. Won't delete the file in case
// it's
// a temporary issue and can be sent again later.
LOG.error("OpenEye: Couldn't send pending crash report!");
LogManager.error("OpenEye: Couldn't send pending crash report!");
} else {
// OpenEye returned a response to the report, display that to user if needed.
LOG.info("OpenEye: Pending crash report sent! URL: {}", response.getURL());
LogManager.info("OpenEye: Pending crash report sent! URL: " + response.getURL());
if (response.hasNote()) {
int ret = DialogManager.optionDialog().setTitle(GetText.tr("About Your Crash"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
@ -1230,7 +1228,7 @@ public class Instance extends MinecraftVersion {
try {
return Utils.sendAPICall("pack/" + this.getPack().getSafeName() + "/play", request);
} catch (IOException e) {
LOG.error(e);
LogManager.logStackTrace(e);
}
return "Play Not Added!";
}
@ -1244,7 +1242,7 @@ public class Instance extends MinecraftVersion {
try {
return Utils.sendAPICall("pack/" + this.getPack().getSafeName() + "/timeplayed/", request);
} catch (IOException e) {
LOG.error("Error adding time played", e);
LogManager.logStackTrace(e);
}
return "Leaderboard Time Not Added!";
}
@ -1411,7 +1409,7 @@ public class Instance extends MinecraftVersion {
try {
download.downloadFile();
} catch (IOException e) {
LOG.error(e);
LogManager.logStackTrace(e);
DialogManager.okDialog().setType(DialogManager.ERROR).setTitle("Failed to download")
.setContent("Failed to download " + file.fileName + ". Please try again later.").show();
return;
@ -1477,7 +1475,7 @@ public class Instance extends MinecraftVersion {
try {
download.downloadFile();
} catch (IOException e) {
LOG.error("error downloading file", e);
LogManager.logStackTrace(e);
DialogManager.okDialog().setType(DialogManager.ERROR).setTitle("Failed to download")
.setContent("Failed to download " + fileToDownload.filename + ". Please try again later.")
.show();
@ -1563,7 +1561,7 @@ public class Instance extends MinecraftVersion {
public boolean canBeExported() {
if (launcher.loaderVersion == null) {
LOG.debug("Instance {} cannot be exported due to: No loader", launcher.name);
LogManager.debug("Instance " + launcher.name + " cannot be exported due to: No loader");
return false;
}
@ -1721,7 +1719,8 @@ public class Instance extends MinecraftVersion {
try (FileWriter fileWriter = new FileWriter(tempDir.resolve("mmc-pack.json").toFile())) {
Gsons.MINECRAFT.toJson(manifest, fileWriter);
} catch (JsonIOException | IOException e) {
LOG.error("Failed to save mmc-pack.json", e);
LogManager.logStackTrace("Failed to save mmc-pack.json", e);
FileUtils.deleteDirectory(tempDir);
return false;
@ -1791,7 +1790,7 @@ public class Instance extends MinecraftVersion {
try (OutputStream outputStream = Files.newOutputStream(instanceCfgPath)) {
instanceCfg.store(outputStream, "Exported by ATLauncher");
} catch (JsonIOException | IOException e) {
LOG.error("Failed to save mmc-pack.json", e);
LogManager.logStackTrace("Failed to save mmc-pack.json", e);
FileUtils.deleteDirectory(tempDir);
@ -1846,7 +1845,7 @@ public class Instance extends MinecraftVersion {
long hash = Hashing.murmur(dm.getFile(this.ROOT, this.id).toPath());
murmurHashes.put(hash, dm);
} catch (Throwable t) {
LOG.error(t);
LogManager.logStackTrace(t);
}
});
@ -1882,7 +1881,7 @@ public class Instance extends MinecraftVersion {
dm.curseForgeProject = curseForgeProject;
}
LOG.debug("Found matching mod from CurseForge called "
LogManager.debug("Found matching mod from CurseForge called "
+ dm.curseForgeFile.displayName);
});
}
@ -1931,7 +1930,8 @@ public class Instance extends MinecraftVersion {
try (FileWriter fileWriter = new FileWriter(tempDir.resolve("manifest.json").toFile())) {
Gsons.MINECRAFT.toJson(manifest, fileWriter);
} catch (JsonIOException | IOException e) {
LOG.error("Failed to save manifest.json", e);
LogManager.logStackTrace("Failed to save manifest.json", e);
FileUtils.deleteDirectory(tempDir);
return false;
@ -1952,7 +1952,7 @@ public class Instance extends MinecraftVersion {
try (FileWriter fileWriter = new FileWriter(tempDir.resolve("modlist.html").toFile())) {
fileWriter.write(sb.toString());
} catch (JsonIOException | IOException e) {
LOG.error("Failed to save modlist.html", e);
LogManager.logStackTrace("Failed to save modlist.html", e);
FileUtils.deleteDirectory(tempDir);
@ -2033,7 +2033,7 @@ public class Instance extends MinecraftVersion {
mod.modrinthVersion = modrinthVersion;
LOG.debug("Found matching version from Modrinth called " + mod.modrinthVersion.name);
LogManager.debug("Found matching version from Modrinth called " + mod.modrinthVersion.name);
if (modrinthProjects.containsKey(modrinthVersions.get(hash).projectId)) {
mod.modrinthProject = modrinthProjects.get(modrinthVersion.projectId);
@ -2102,7 +2102,7 @@ public class Instance extends MinecraftVersion {
StandardCharsets.UTF_8)) {
Gsons.MINECRAFT.toJson(manifest, osw);
} catch (JsonIOException | IOException e) {
LOG.error("Failed to save modrinth.index.json", e);
LogManager.logStackTrace("Failed to save modrinth.index.json", e);
FileUtils.deleteDirectory(tempDir);
@ -2173,7 +2173,7 @@ public class Instance extends MinecraftVersion {
try (FileWriter fileWriter = new FileWriter(this.getRoot().resolve("instance.json").toFile())) {
Gsons.MINECRAFT.toJson(this, fileWriter);
} catch (JsonIOException | IOException e) {
LOG.error("failed to save instance", e);
LogManager.logStackTrace(e);
}
}
@ -2501,14 +2501,14 @@ public class Instance extends MinecraftVersion {
}));
dialog.start();
} else if (clonedName == null || clonedName.equals("")) {
LOG.error("Error Occurred While Cloning Instance! Dialog Closed/Cancelled!");
LogManager.error("Error Occurred While Cloning Instance! Dialog Closed/Cancelled!");
DialogManager.okDialog().setTitle(GetText.tr("Error"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
"An error occurred while cloning the instance.<br/><br/>Please check the console and try again."))
.build())
.setType(DialogManager.ERROR).show();
} else if (clonedName.replaceAll("[^A-Za-z0-9]", "").length() == 0) {
LOG.error("Error Occurred While Cloning Instance! Invalid Name!");
LogManager.error("Error Occurred While Cloning Instance! Invalid Name!");
DialogManager.okDialog().setTitle(GetText.tr("Error"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
"An error occurred while cloning the instance.<br/><br/>Please check the console and try again."))
@ -2516,7 +2516,7 @@ public class Instance extends MinecraftVersion {
.setType(DialogManager.ERROR).show();
} else if (Files
.exists(FileSystem.INSTANCES.resolve(clonedName.replaceAll("[^A-Za-z0-9]", "")))) {
LOG.error(
LogManager.error(
"Error Occurred While Cloning Instance! Folder Already Exists Rename It And Try Again!");
DialogManager.okDialog().setTitle(GetText.tr("Error"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
@ -2524,7 +2524,7 @@ public class Instance extends MinecraftVersion {
.build())
.setType(DialogManager.ERROR).show();
} else {
LOG.error(
LogManager.error(
"Error Occurred While Cloning Instance! Instance With That Name Already Exists!");
DialogManager.okDialog().setTitle(GetText.tr("Error"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
@ -2565,7 +2565,7 @@ public class Instance extends MinecraftVersion {
Utils.safeCopy(img, getRoot().resolve("instance.png").toFile());
save();
} catch (IOException ex) {
LOG.error("Failed to set instance image", ex);
LogManager.logStackTrace("Failed to set instance image", ex);
}
}
}
@ -2595,7 +2595,7 @@ public class Instance extends MinecraftVersion {
success = installable.startInstall();
} catch (InvalidMinecraftVersion e) {
LOG.error("error changing loader version", e);
LogManager.logStackTrace(e);
}
if (success) {
@ -2640,7 +2640,7 @@ public class Instance extends MinecraftVersion {
success = installable.startInstall();
} catch (InvalidMinecraftVersion e) {
LOG.error("error adding loader {}", loaderType, e);
LogManager.logStackTrace(e);
}
if (success) {
@ -2774,7 +2774,7 @@ public class Instance extends MinecraftVersion {
success = installable.startInstall();
} catch (InvalidMinecraftVersion e) {
LOG.error("error removing loader", e);
LogManager.logStackTrace(e);
}
if (success) {
@ -2835,7 +2835,7 @@ public class Instance extends MinecraftVersion {
if (Files.isDirectory(runtimeDirectory)) {
javaPath = runtimeDirectory.toAbsolutePath().toString();
LOG.debug(String.format("Using Java runtime %s (major version %d) at path %s",
LogManager.debug(String.format("Using Java runtime %s (major version %d) at path %s",
javaVersion.component, javaVersion.majorVersion, javaPath));
}
}
@ -2887,7 +2887,7 @@ public class Instance extends MinecraftVersion {
&& mod.file.equals(file.getFileName().toString())))
.collect(Collectors.toList()));
} catch (IOException e) {
LOG.error("Error scanning missing mods", e);
LogManager.logStackTrace("Error scanning missing mods", e);
}
}
@ -2914,7 +2914,7 @@ public class Instance extends MinecraftVersion {
.getFile(ROOT, id).toPath());
murmurHashes.put(hash, dm);
} catch (Throwable t) {
LOG.error(t);
LogManager.logStackTrace(t);
}
});
@ -2952,7 +2952,7 @@ public class Instance extends MinecraftVersion {
dm.description = curseForgeProject.summary;
}
LOG.debug("Found matching mod from CurseForge called "
LogManager.debug("Found matching mod from CurseForge called "
+ dm.curseForgeFile.displayName);
});
}
@ -2974,7 +2974,7 @@ public class Instance extends MinecraftVersion {
.getFile(ROOT, id).toPath())
.toString(), dm);
} catch (Throwable t) {
LOG.error(t);
LogManager.logStackTrace(t);
}
});
@ -3009,7 +3009,7 @@ public class Instance extends MinecraftVersion {
dm.description = project.description;
}
LOG.debug(String.format(
LogManager.debug(String.format(
"Found matching mod from Modrinth called %s with file %s",
project.title, version.name));
}
@ -3020,7 +3020,7 @@ public class Instance extends MinecraftVersion {
}
}
mods.forEach(mod -> LOG.info("Found extra mod with name of " + mod.file));
mods.forEach(mod -> LogManager.info("Found extra mod with name of " + mod.file));
launcher.mods.addAll(mods);
save();
progressDialog.close();
@ -3045,7 +3045,7 @@ public class Instance extends MinecraftVersion {
}).collect(Collectors.toList());
if (removedMods.size() != 0) {
removedMods.forEach(mod -> LOG.info("Mod no longer in filesystem: {}", mod.file));
removedMods.forEach(mod -> LogManager.info("Mod no longer in filesystem: " + mod.file));
launcher.mods.removeAll(removedMods);
save();
}

View file

@ -24,17 +24,14 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import org.mini2Dx.gettext.PoFile;
import com.atlauncher.App;
import com.atlauncher.evnt.manager.RelocalizationManager;
import com.atlauncher.managers.LogManager;
public class Language {
private static final Logger LOG = LogManager.getLogger(Language.class);
public final static List<Locale> locales = new ArrayList<>();
public final static Map<String, Locale> languages = new HashMap<>();
public static String selected = Locale.ENGLISH.getDisplayName();
@ -49,7 +46,7 @@ public class Language {
if (App.class.getResourceAsStream("/assets/lang/" + locale.toString() + ".po") != null) {
System.out.println(locale.toString());
languages.put(locale.getDisplayName(), locale);
LOG.debug("Loaded language " + locale.getDisplayName() + " with key of " + locale);
LogManager.debug("Loaded language " + locale.getDisplayName() + " with key of " + locale);
}
}
}
@ -62,11 +59,11 @@ public class Language {
Locale locale;
if (isLanguageByName(language)) {
LOG.info("Language set to " + language);
LogManager.info("Language set to " + language);
locale = languages.get(language);
selected = language;
} else {
LOG.info("Unknown language " + language + ". Defaulting to " + Locale.ENGLISH.getDisplayName());
LogManager.info("Unknown language " + language + ". Defaulting to " + Locale.ENGLISH.getDisplayName());
locale = Locale.ENGLISH;
selected = Locale.ENGLISH.getDisplayName();
}
@ -76,7 +73,7 @@ public class Language {
GetText.add(
new PoFile(locale, App.class.getResourceAsStream("/assets/lang/" + locale.toString() + ".po")));
} catch (IOException e) {
LOG.error("Failed loading language po file for " + language, e);
LogManager.logStackTrace("Failed loading language po file for " + language, e);
locale = Locale.ENGLISH;
selected = Locale.ENGLISH.getDisplayName();
}

View file

@ -21,8 +21,6 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.builders.HTMLBuilder;
@ -34,12 +32,11 @@ import com.atlauncher.data.microsoft.XboxLiveAuthResponse;
import com.atlauncher.gui.dialogs.LoginWithMicrosoftDialog;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.DownloadException;
import com.atlauncher.utils.MicrosoftAuthAPI;
public class MicrosoftAccount extends AbstractAccount {
private static final Logger LOG = LogManager.getLogger(MicrosoftAccount.class);
/**
* Auto generated serial.
*/
@ -112,12 +109,12 @@ public class MicrosoftAccount extends AbstractAccount {
try {
profile = MicrosoftAuthAPI.getMcProfile(accessToken);
} catch (Exception e) {
LOG.error("Error getting Minecraft profile");
LogManager.error("Error getting Minecraft profile");
return null;
}
if (profile == null) {
LOG.error("Error getting Minecraft profile");
LogManager.error("Error getting Minecraft profile");
return null;
}
@ -136,12 +133,12 @@ public class MicrosoftAccount extends AbstractAccount {
try {
profile = MicrosoftAuthAPI.getMcProfile(accessToken);
} catch (Exception e) {
LOG.error("Error getting Minecraft profile");
LogManager.error("Error getting Minecraft profile");
return null;
}
if (profile == null) {
LOG.error("Error getting Minecraft profile");
LogManager.error("Error getting Minecraft profile");
return null;
}
@ -156,13 +153,13 @@ public class MicrosoftAccount extends AbstractAccount {
public boolean refreshAccessToken(boolean force) {
try {
if (force || new Date().after(this.oauthToken.expiresAt)) {
LOG.info("Oauth token expired. Attempting to refresh");
LogManager.info("Oauth token expired. Attempting to refresh");
OauthTokenResponse oauthTokenResponse = MicrosoftAuthAPI.refreshAccessToken(oauthToken.refreshToken);
if (oauthTokenResponse == null) {
mustLogin = true;
AccountManager.saveAccounts();
LOG.error("Failed to refresh accessToken");
LogManager.error("Failed to refresh accessToken");
return false;
}
@ -172,14 +169,14 @@ public class MicrosoftAccount extends AbstractAccount {
}
if (force || new Date().after(this.xstsAuth.notAfter)) {
LOG.info("xsts auth expired. Attempting to get new auth");
LogManager.info("xsts auth expired. Attempting to get new auth");
XboxLiveAuthResponse xboxLiveAuthResponse = MicrosoftAuthAPI.getXBLToken(this.oauthToken.accessToken);
this.xstsAuth = MicrosoftAuthAPI.getXstsToken(xboxLiveAuthResponse.token);
if (xstsAuth == null) {
mustLogin = true;
AccountManager.saveAccounts();
LOG.error("Failed to get XBLToken");
LogManager.error("Failed to get XBLToken");
return false;
}
@ -192,7 +189,7 @@ public class MicrosoftAccount extends AbstractAccount {
if (loginResponse == null) {
mustLogin = true;
AccountManager.saveAccounts();
LOG.error("Failed to login to Minecraft");
LogManager.error("Failed to login to Minecraft");
return false;
}
@ -200,7 +197,7 @@ public class MicrosoftAccount extends AbstractAccount {
if (!(entitlements.items.stream().anyMatch(i -> i.name.equalsIgnoreCase("product_minecraft"))
&& entitlements.items.stream().anyMatch(i -> i.name.equalsIgnoreCase("game_minecraft")))) {
LOG.error("This account doesn't have a valid purchase of Minecraft");
LogManager.error("This account doesn't have a valid purchase of Minecraft");
return false;
}
@ -226,7 +223,7 @@ public class MicrosoftAccount extends AbstractAccount {
mustLogin = true;
AccountManager.saveAccounts();
LOG.error("Exception refreshing accessToken", e);
LogManager.logStackTrace("Exception refreshing accessToken", e);
return false;
}
@ -249,7 +246,7 @@ public class MicrosoftAccount extends AbstractAccount {
try {
profile = MicrosoftAuthAPI.getMcProfile(accessToken);
} catch (DownloadException e) {
LOG.error("Minecraft Profile not found");
LogManager.error("Minecraft Profile not found");
DialogManager.okDialog().setTitle(GetText.tr("Minecraft Profile Not Found"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
"No Minecraft profiles were found for this account. Have you purchased Minecraft?<br/><br/>Please make sure you've bought the Java edition of Minecraft and then try again.<br/><br/>If you're an Xbox Game Pass subscriber, make sure to login and play through the Minecraft<br/>Launcher once in order to create your Minecraft profile, then try logging in again."))
@ -257,12 +254,12 @@ public class MicrosoftAccount extends AbstractAccount {
.setType(DialogManager.ERROR).show();
return false;
} catch (Exception e) {
LOG.error("Failed to get Minecraft profile", e);
LogManager.logStackTrace("Failed to get Minecraft profile", e);
return false;
}
if (profile == null) {
LOG.error("Failed to get Minecraft profile");
LogManager.error("Failed to get Minecraft profile");
return false;
}
@ -307,12 +304,12 @@ public class MicrosoftAccount extends AbstractAccount {
return true;
}
LOG.info("Access Token has expired. Attempting to refresh it.");
LogManager.info("Access Token has expired. Attempting to refresh it.");
try {
return refreshAccessToken();
} catch (Exception e) {
LOG.error("Exception while attempting to refresh access token", e);
LogManager.logStackTrace("Exception while attempting to refresh access token", e);
}
return false;

View file

@ -29,8 +29,6 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -40,13 +38,12 @@ import com.atlauncher.data.mojang.api.MinecraftProfileResponse;
import com.atlauncher.data.mojang.api.ProfileTexture;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Authentication;
import com.atlauncher.utils.MojangAPIUtils;
import com.atlauncher.utils.Utils;
public class MojangAccount extends AbstractAccount {
private static final Logger LOG = LogManager.getLogger(MojangAccount.class);
/**
* Auto generated serial.
*/
@ -134,7 +131,7 @@ public class MojangAccount extends AbstractAccount {
@Override
public String getCurrentUsername() {
if (this.uuid == null) {
LOG.error("The account {} has no UUID associated with it !", this.minecraftUsername);
LogManager.error("The account " + this.minecraftUsername + " has no UUID associated with it !");
return null;
}
@ -178,7 +175,7 @@ public class MojangAccount extends AbstractAccount {
}
reader.close();
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
response = null;
}
@ -215,12 +212,12 @@ public class MojangAccount extends AbstractAccount {
LoginResponse response = null;
if (this.getAccessToken() != null) {
LOG.info("Trying to login with access token!");
LogManager.info("Trying to login with access token!");
response = Authentication.login(this, false);
}
if (response == null || (response.hasError() && !response.isOffline())) {
LOG.error("Access token is NOT valid! Will attempt to get another one!");
LogManager.error("Access token is NOT valid! Will attempt to get another one!");
if (!this.remember) {
JPanel panel = new JPanel();
@ -235,14 +232,14 @@ public class MojangAccount extends AbstractAccount {
if (ret == DialogManager.OK_OPTION) {
if (passwordField.getPassword().length == 0) {
LOG.error("Aborting login for {}, no password entered", this.minecraftUsername);
LogManager.error("Aborting login for " + this.minecraftUsername + ", no password entered");
App.launcher.setMinecraftLaunched(false);
return null;
}
this.setPassword(new String(passwordField.getPassword()));
} else {
LOG.error("Aborting login for {}", this.minecraftUsername);
LogManager.error("Aborting login for " + this.minecraftUsername);
App.launcher.setMinecraftLaunched(false);
return null;
}
@ -252,7 +249,7 @@ public class MojangAccount extends AbstractAccount {
}
if (response.hasError() && !response.isOffline()) {
LOG.error("error: {}", response.getErrorMessage());
LogManager.error(response.getErrorMessage());
DialogManager
.okDialog().setTitle(

View file

@ -21,11 +21,9 @@ import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.annot.Json;
import com.atlauncher.managers.LogManager;
import com.google.gson.annotations.SerializedName;
/**
@ -33,8 +31,6 @@ import com.google.gson.annotations.SerializedName;
*/
@Json
public class News {
private static final Logger LOG = LogManager.getLogger(News.class);
/**
* The title of this news article.
*/
@ -58,7 +54,7 @@ public class News {
try {
return formatter.format(iso8601Format.parse(this.createdAt));
} catch (ParseException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
return null;
}
}

View file

@ -26,9 +26,6 @@ import java.util.Map;
import javax.swing.ImageIcon;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Gsons;
import com.atlauncher.constants.Constants;
@ -38,12 +35,11 @@ import com.atlauncher.data.modpacksch.ModpacksChPackManifest;
import com.atlauncher.data.modrinth.ModrinthProject;
import com.atlauncher.data.technic.TechnicModpack;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.PackManager;
import com.atlauncher.utils.Utils;
public class Pack {
private static final Logger LOG = LogManager.getLogger(Pack.class);
public int id;
public int externalId;
public boolean vanillaInstance = false;
@ -320,7 +316,7 @@ public class Pack {
try {
return Utils.sendAPICall("pack/" + getSafeName() + "/installed/", request);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return "Install Not Added!";
}
@ -333,7 +329,7 @@ public class Pack {
try {
return Utils.sendAPICall("pack/" + getSafeName() + "/serverinstalled/", request);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return "Install Not Added!";
}
@ -346,7 +342,7 @@ public class Pack {
try {
return Utils.sendAPICall("pack/" + getSafeName() + "/updated/", request);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return "Install Not Added!";
}

View file

@ -19,10 +19,8 @@ package com.atlauncher.data;
import java.lang.reflect.Type;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.exceptions.InvalidMinecraftVersion;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
@ -31,8 +29,6 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
public class PackVersionTypeAdapter implements JsonDeserializer<PackVersion> {
private static final Logger LOG = LogManager.getLogger(PackVersionTypeAdapter.class);
@Override
public PackVersion deserialize(JsonElement json, Type type, JsonDeserializationContext context)
throws JsonParseException {
@ -54,7 +50,7 @@ public class PackVersionTypeAdapter implements JsonDeserializer<PackVersion> {
packVersion.minecraftVersion = MinecraftManager
.getMinecraftVersion(rootJsonObject.get("minecraft").getAsString());
} catch (InvalidMinecraftVersion e) {
LOG.error("error:", e);
LogManager.error(e.getMessage());
}
}

View file

@ -33,8 +33,6 @@ import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -47,6 +45,7 @@ import com.atlauncher.data.minecraft.JavaVersion;
import com.atlauncher.exceptions.InvalidPack;
import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.PackManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.ArchiveUtils;
@ -56,8 +55,6 @@ import com.google.gson.JsonIOException;
@Json
public class Server {
private static final Logger LOG = LogManager.getLogger(Server.class);
public String name;
public String pack;
public Integer packId;
@ -118,7 +115,7 @@ public class Server {
serverScript += ".sh";
}
LOG.info("Starting server " + name);
LogManager.info("Starting server " + name);
List<String> arguments = new ArrayList<>();
String javaPath = null;
@ -128,7 +125,7 @@ public class Server {
if (Files.isDirectory(runtimeDirectory)) {
javaPath = runtimeDirectory.toAbsolutePath().toString();
LOG.debug(String.format("Using Java runtime %s (major version %d) at path %s",
LogManager.debug(String.format("Using Java runtime %s (major version %d) at path %s",
javaVersion.component, javaVersion.majorVersion, javaPath));
}
}
@ -206,7 +203,7 @@ public class Server {
StandardOpenOption.TRUNCATE_EXISTING);
tempLaunchFile.toFile().setExecutable(true);
LOG.info(String.format("Running \"%s\" from \".launcherrun.sh\"",
LogManager.info(String.format("Running \"%s\" from \".launcherrun.sh\"",
String.join(" ", launchScript)));
launchCommand = "./.launcherrun.sh";
@ -218,7 +215,7 @@ public class Server {
arguments.add(launchCommand);
}
LOG.info("Launching server with the following arguments: {}", arguments);
LogManager.info("Launching server with the following arguments: " + arguments.toString());
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.directory(getRoot().toFile());
processBuilder.command(arguments);
@ -234,7 +231,7 @@ public class Server {
System.exit(0);
}
} catch (IOException e) {
LOG.error("Failed to launch server", e);
LogManager.logStackTrace("Failed to launch server", e);
}
}
@ -257,7 +254,7 @@ public class Server {
if (progressDialog.getReturnValue()) {
App.TOASTER.pop(GetText.tr("Backup is complete"));
LOG.info("Backup complete and stored at {}", backupZip);
LogManager.info(String.format("Backup complete and stored at %s", backupZip.toString()));
} else {
App.TOASTER.popError(GetText.tr("Error making backup"));
}
@ -323,7 +320,7 @@ public class Server {
Image dimg = img.getScaledInstance(300, 150, Image.SCALE_SMOOTH);
return new ImageIcon(dimg);
} catch (IOException e) {
LOG.error("Error creating scaled image from the custom image of server " + this.name, e);
LogManager.logStackTrace("Error creating scaled image from the custom image of server " + this.name, e);
}
}
@ -341,7 +338,7 @@ public class Server {
try (FileWriter fileWriter = new FileWriter(this.getRoot().resolve("server.json").toFile())) {
Gsons.MINECRAFT.toJson(this, fileWriter);
} catch (JsonIOException | IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}
}

View file

@ -32,20 +32,16 @@ import java.util.List;
import java.util.Properties;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Gsons;
import com.atlauncher.constants.Constants;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.OS;
import com.atlauncher.utils.Timestamper;
import com.atlauncher.utils.Utils;
import com.atlauncher.utils.sort.InstanceSortingStrategies;
public class Settings {
private static final Logger LOG = LogManager.getLogger(Settings.class);
// Launcher things
public String lastAccount;
public boolean usingCustomJavaPath = false;
@ -388,7 +384,7 @@ public class Settings {
// now validate the java path actually exists
if (!new File(javaPath, "bin" + File.separator + "java" + (OS.isWindows() ? ".exe" : "")).exists()) {
LOG.warn("Custom Java Path Is Incorrect! Defaulting to valid value!");
LogManager.warn("Custom Java Path Is Incorrect! Defaulting to valid value!");
javaPath = OS.getDefaultJavaPath();
}
}
@ -398,19 +394,19 @@ public class Settings {
int systemMemory = OS.getMaximumRam();
if (systemMemory != 0 && initialMemory > systemMemory) {
LOG.warn("Tried to allocate " + initialMemory + "MB for initial memory but only " + systemMemory
LogManager.warn("Tried to allocate " + initialMemory + "MB for initial memory but only " + systemMemory
+ "MB is available to use!");
initialMemory = 512;
needToSave = true;
} else if (initialMemory > maximumMemory) {
LOG.warn("Tried to allocate " + initialMemory + "MB for initial memory which is more than "
LogManager.warn("Tried to allocate " + initialMemory + "MB for initial memory which is more than "
+ maximumMemory + "MB set for the maximum memory!");
initialMemory = 512;
needToSave = true;
}
if (systemMemory != 0 && maximumMemory > systemMemory) {
LOG.warn("Tried to allocate " + maximumMemory + "MB of maximum memory but only " + systemMemory
LogManager.warn("Tried to allocate " + maximumMemory + "MB of maximum memory but only " + systemMemory
+ "MB is available to use!");
if (OS.is64Bit()) {
@ -430,7 +426,7 @@ public class Settings {
private void validateWindowSize() {
int systemWindowWidth = OS.getMaximumWindowWidth();
if (windowWidth > systemWindowWidth) {
LOG.warn("Tried to set window width to " + windowWidth + "px but the maximum is " + systemWindowWidth
LogManager.warn("Tried to set window width to " + windowWidth + "px but the maximum is " + systemWindowWidth
+ "px!");
windowWidth = systemWindowWidth;
@ -438,7 +434,7 @@ public class Settings {
int systemWindowHeight = OS.getMaximumWindowHeight();
if (windowHeight > systemWindowHeight) {
LOG.warn("Tried to set window height to " + windowHeight + "px but the maximum is "
LogManager.warn("Tried to set window height to " + windowHeight + "px but the maximum is "
+ systemWindowHeight + "px!");
windowHeight = systemWindowHeight;
@ -448,14 +444,14 @@ public class Settings {
private void validateProxy() {
if (enableProxy) {
if (proxyPort <= 0 || proxyPort > 65535) {
LOG.warn("Tried to set proxy port to " + proxyPort
LogManager.warn("Tried to set proxy port to " + proxyPort
+ " which is not a valid port! Proxy support disabled!");
enableProxy = false;
proxyPort = 8080;
}
if (!proxyType.equals("SOCKS") && !proxyType.equals("HTTP") && !proxyType.equals("DIRECT")) {
LOG.warn(
LogManager.warn(
"Tried to set proxy type to " + proxyType + " which is not valid! Proxy support disabled!");
enableProxy = false;
proxyType = "HTTP";
@ -485,7 +481,7 @@ public class Settings {
private void validateConcurrentConnections() {
if (concurrentConnections < 1) {
LOG.warn("Tried to set the number of concurrent connections to " + concurrentConnections
LogManager.warn("Tried to set the number of concurrent connections to " + concurrentConnections
+ " which is not valid! Must be 1 or more. Setting back to default of 8!");
concurrentConnections = 8;
}
@ -493,7 +489,7 @@ public class Settings {
private void validateDateFormat() {
if (!Arrays.asList(Constants.DATE_FORMATS).contains(dateFormat)) {
LOG.warn("Tried to set the date format to " + dateFormat + " which is not valid! Setting "
LogManager.warn("Tried to set the date format to " + dateFormat + " which is not valid! Setting "
+ "back to default of " + Constants.DATE_FORMATS[0] + "!");
dateFormat = Constants.DATE_FORMATS[0];
}
@ -501,7 +497,7 @@ public class Settings {
private void validateInstanceTitleFormat() {
if (!Arrays.asList(Constants.INSTANCE_TITLE_FORMATS).contains(instanceTitleFormat)) {
LOG.warn(
LogManager.warn(
"Tried to set the instance title format to " + instanceTitleFormat + " which is not valid! Setting "
+ "back to default of " + Constants.INSTANCE_TITLE_FORMATS[0] + "!");
instanceTitleFormat = Constants.INSTANCE_TITLE_FORMATS[0];
@ -523,13 +519,13 @@ public class Settings {
try (FileWriter writer = new FileWriter(FileSystem.SETTINGS.toFile())) {
Gsons.DEFAULT.toJson(this, writer);
} catch (IOException e) {
LOG.error("Error saving settings", e);
LogManager.logStackTrace("Error saving settings", e);
}
try {
Timestamper.updateDateFormat(dateFormat);
} catch (Exception e) {
LOG.error("Error updating date format to " + dateFormat, e);
LogManager.logStackTrace("Error updating date format to " + dateFormat, e);
}
}
}

View file

@ -32,8 +32,6 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -51,13 +49,12 @@ import com.atlauncher.data.multimc.MultiMCManifest;
import com.atlauncher.data.technic.TechnicModpack;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.InstanceManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.ServerManager;
import com.atlauncher.utils.FileUtils;
import com.atlauncher.workers.InstanceInstaller;
public abstract class Installable {
private static final Logger LOG = LogManager.getLogger(Installable.class);
public String instanceName;
public boolean isServer = false;
public boolean isUpdate = false;
@ -210,7 +207,7 @@ public abstract class Installable {
Thread.currentThread().interrupt();
return;
} catch (ExecutionException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
if (success) {

View file

@ -23,17 +23,13 @@ import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.annot.Json;
import com.atlauncher.data.minecraft.loaders.LoaderVersion;
import com.atlauncher.managers.LogManager;
import com.atlauncher.workers.InstanceInstaller;
@Json
public class Loader {
private static final Logger LOG = LogManager.getLogger(Loader.class);
public String type;
public boolean choose = false;
public Map<String, Object> metadata;
@ -87,7 +83,7 @@ public class Loader {
return (List<LoaderVersion>) method.invoke(null, minecraft);
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return null;

View file

@ -22,8 +22,6 @@ import java.io.File;
import java.io.FilenameFilter;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.FileSystem;
@ -35,6 +33,7 @@ import com.atlauncher.data.curseforge.CurseForgeProject;
import com.atlauncher.data.modrinth.ModrinthProject;
import com.atlauncher.data.modrinth.ModrinthVersion;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Hashing;
import com.atlauncher.utils.OS;
import com.atlauncher.utils.Utils;
@ -43,8 +42,6 @@ import com.google.gson.annotations.SerializedName;
@Json
public class Mod {
private static final Logger LOG = LogManager.getLogger(Mod.class);
public String name;
public String version;
public String url;
@ -464,7 +461,7 @@ public class Mod {
} else if (retValue == 0) {
OS.openFileExplorer(FileSystem.DOWNLOADS);
} else if (retValue == 2) {
LOG.warn(String.format("Skipping browser download of mod %s", name));
LogManager.warn(String.format("Skipping browser download of mod %s", name));
return false;
}
} while (retValue != 1);
@ -530,7 +527,7 @@ public class Mod {
Utils.delete(fileLocation); // MD5 hash doesn't match, delete it
return downloadClient(installer, ++attempt); // download again
} else {
LOG.error("Cannot download {}. Aborting install!", fileLocation.getAbsolutePath());
LogManager.error("Cannot download " + fileLocation.getAbsolutePath() + ". Aborting install!");
installer.cancel(true);
return false;
}
@ -666,7 +663,7 @@ public class Mod {
Utils.delete(fileLocation); // MD5 hash doesn't match, delete it
return downloadServer(installer, ++attempt); // download again
} else {
LOG.error("Cannot download {}. Aborting install!", fileLocation.getAbsolutePath());
LogManager.error("Cannot download " + fileLocation.getAbsolutePath() + ". Aborting install!");
installer.cancel(true);
return false;
}
@ -813,7 +810,7 @@ public class Mod {
Utils.copyDirectory(folder, installer.root.toFile());
break;
default:
LOG.error("No known way to extract mod {} with type {}", this.name, this.extractTo);
LogManager.error("No known way to extract mod " + this.name + " with type " + this.extractTo);
break;
}
Utils.delete(tempDirExtract);
@ -861,17 +858,17 @@ public class Mod {
}
break;
default:
LOG.error("No known way to decomp mod {} with type {}", this.name, this.decompType);
LogManager
.error("No known way to decomp mod " + this.name + " with type " + this.decompType);
break;
}
} else {
LOG.error("Couldn't find decomp file {} for mod {}", this.decompFile, this.name);
LogManager.error("Couldn't find decomp file " + this.decompFile + " for mod " + this.name);
}
Utils.delete(tempDirDecomp);
break;
default:
LOG.error("No known way to install mod {} with type {}", this.name, thisType);
LogManager.error("No known way to install mod " + this.name + " with type " + thisType);
break;
}
}
@ -927,7 +924,7 @@ public class Mod {
base = installer.root.resolve("shaderpacks").toFile();
break;
default:
LOG.error("No known way to find installed mod {} with type {}", this.name, thisType);
LogManager.error("No known way to find installed mod " + this.name + " with type " + thisType);
break;
}
if (path != null) {

View file

@ -25,11 +25,9 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.annot.Json;
import com.atlauncher.data.DisableableMod;
import com.atlauncher.managers.LogManager;
import com.atlauncher.workers.InstanceInstaller;
import com.google.gson.annotations.SerializedName;
@ -39,8 +37,6 @@ import com.google.gson.annotations.SerializedName;
*/
@Json
public class Version {
private static final Logger LOG = LogManager.getLogger(Version.class);
/**
* The version this pack's version is.
*/
@ -360,7 +356,7 @@ public class Version {
return null;
}
if (!this.isColour(key)) {
LOG.warn("Colour with key {} not found!", key);
LogManager.warn("Colour with key " + key + " not found!");
return null;
}
String colour = this.colours.get(key);
@ -368,7 +364,7 @@ public class Version {
colour = colour.replace("#", "");
}
if (!colour.matches("[0-9A-Fa-f]{6}")) {
LOG.warn("Colour with key {} has invalid value of {}!", key, colour);
LogManager.warn("Colour with key " + key + " has invalid value of " + colour + "!");
return null;
}
int r, g, b;
@ -378,7 +374,7 @@ public class Version {
b = Integer.parseInt(colour.substring(4, 6), 16);
return new Color(r, g, b);
} catch (NumberFormatException e) {
LOG.warn("Colour with key {} failed to create object with value of {}!", key, colour);
LogManager.warn("Colour with key " + key + " failed to create object with value of " + colour + "!");
return null;
}
}

View file

@ -36,23 +36,19 @@ import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.data.minecraft.Arguments;
import com.atlauncher.data.minecraft.Library;
import com.atlauncher.data.minecraft.loaders.Loader;
import com.atlauncher.data.minecraft.loaders.LoaderVersion;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import com.atlauncher.utils.Utils;
import com.atlauncher.workers.InstanceInstaller;
import com.google.gson.reflect.TypeToken;
public class FabricLoader implements Loader {
private static final Logger LOG = LogManager.getLogger(FabricLoader.class);
protected String minecraft;
protected FabricMetaVersion version;
protected File tempDir;
@ -71,7 +67,7 @@ public class FabricLoader implements Loader {
} else if (metadata.containsKey("loader")) {
this.version = this.getVersion((String) metadata.get("loader"));
} else if ((boolean) metadata.get("latest")) {
LOG.debug("Downloading latest Fabric version");
LogManager.debug("Downloading latest Fabric version");
this.version = this.getLatestVersion();
}
}
@ -208,7 +204,7 @@ public class FabricLoader implements Loader {
.getBytes(StandardCharsets.UTF_8));
propertiesOutputStream.close();
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}

View file

@ -25,21 +25,17 @@ import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Gsons;
import com.atlauncher.data.minecraft.ArgumentRule;
import com.atlauncher.data.minecraft.Arguments;
import com.atlauncher.data.minecraft.Library;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.FileUtils;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
public class Forge113Loader extends ForgeLoader {
private static final Logger LOG = LogManager.getLogger(Forge113Loader.class);
@Override
public ForgeInstallProfile getInstallProfile() {
ForgeInstallProfile installProfile = super.getInstallProfile();
@ -85,7 +81,7 @@ public class Forge113Loader extends ForgeLoader {
try {
version = Gsons.MINECRAFT.fromJson(new FileReader(new File(this.tempDir, "version.json")), Version.class);
} catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return version;
@ -99,7 +95,8 @@ public class Forge113Loader extends ForgeLoader {
try {
processor.process(installProfile, this.tempDir, instanceInstaller);
} catch (IOException e) {
LOG.error("Failed to process processor with jar {}", processor.getJar(), e);
LogManager.logStackTrace(e);
LogManager.error("Failed to process processor with jar " + processor.getJar());
instanceInstaller.cancel(true);
}
}

View file

@ -23,14 +23,12 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Network;
import com.atlauncher.constants.Constants;
import com.atlauncher.data.minecraft.Download;
import com.atlauncher.data.minecraft.Downloads;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Hashing;
import com.atlauncher.utils.Utils;
import com.google.gson.Gson;
@ -45,8 +43,6 @@ import okhttp3.Request;
import okhttp3.Response;
public class ForgeLibraryTypeAdapter implements JsonDeserializer<ForgeLibrary> {
private static final Logger LOG = LogManager.getLogger(ForgeLibraryTypeAdapter.class);
@Override
public ForgeLibrary deserialize(JsonElement json, Type type, JsonDeserializationContext context)
throws JsonParseException {
@ -139,7 +135,7 @@ public class ForgeLibraryTypeAdapter implements JsonDeserializer<ForgeLibrary> {
artifact.sha1 = Hashing.sha1(downloadedLibrary).toString();
}
} catch (Throwable t) {
LOG.error("error", t);
LogManager.logStackTrace(t);
}
}

View file

@ -27,9 +27,6 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Gsons;
import com.atlauncher.Network;
@ -41,6 +38,7 @@ import com.atlauncher.data.minecraft.Library;
import com.atlauncher.data.minecraft.loaders.Loader;
import com.atlauncher.data.minecraft.loaders.LoaderVersion;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import com.atlauncher.utils.FileUtils;
import com.atlauncher.utils.Pair;
@ -50,8 +48,6 @@ import com.google.gson.reflect.TypeToken;
import okhttp3.OkHttpClient;
public class ForgeLoader implements Loader {
private static final Logger LOG = LogManager.getLogger(ForgeLoader.class);
protected String installerUrl;
protected String version;
protected String rawVersion;
@ -91,10 +87,10 @@ public class ForgeLoader implements Loader {
this.rawVersion = (String) metadata.get("rawVersion");
}
} else if ((boolean) metadata.get("latest")) {
LOG.debug("Downloading latest Forge version");
LogManager.debug("Downloading latest Forge version");
this.version = this.getLatestVersion();
} else if ((boolean) metadata.get("recommended")) {
LOG.debug("Downloading recommended Forge version");
LogManager.debug("Downloading recommended Forge version");
this.version = getRecommendedVersion(this.minecraft);
}
@ -212,7 +208,7 @@ public class ForgeLoader implements Loader {
installProfile = Gsons.MINECRAFT.fromJson(new FileReader(new File(this.tempDir, "install_profile.json")),
ForgeInstallProfile.class);
} catch (Throwable e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return installProfile;
@ -229,7 +225,7 @@ public class ForgeLoader implements Loader {
versionInfo = Gsons.MINECRAFT.fromJson(new FileReader(new File(this.tempDir, "version.json")),
ForgeInstallProfile.class);
} catch (Throwable e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return versionInfo;

View file

@ -23,9 +23,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Network;
import com.atlauncher.constants.Constants;
@ -33,6 +30,7 @@ import com.atlauncher.data.minecraft.Arguments;
import com.atlauncher.data.minecraft.Library;
import com.atlauncher.data.minecraft.loaders.Loader;
import com.atlauncher.data.minecraft.loaders.LoaderVersion;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import com.atlauncher.network.DownloadPool;
import com.atlauncher.utils.Pair;
@ -42,8 +40,6 @@ import com.atlauncher.workers.InstanceInstaller;
import okhttp3.OkHttpClient;
public class LegacyForgeLoader implements Loader {
private static final Logger LOG = LogManager.getLogger(LegacyForgeLoader.class);
protected String version;
protected String rawVersion;
@ -98,10 +94,10 @@ public class LegacyForgeLoader implements Loader {
this.rawVersion = (String) metadata.get("rawVersion");
}
} else if ((boolean) metadata.get("latest")) {
LOG.debug("Downloading latest Forge version");
LogManager.debug("Downloading latest Forge version");
this.version = this.getLatestVersion();
} else if ((boolean) metadata.get("recommended")) {
LOG.debug("Downloading recommended Forge version");
LogManager.debug("Downloading recommended Forge version");
this.version = getRecommendedVersion(this.minecraft);
}

View file

@ -30,19 +30,15 @@ import java.util.Map.Entry;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.annot.Json;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Hashing;
import com.atlauncher.utils.Utils;
import com.atlauncher.workers.InstanceInstaller;
@Json
public class Processor {
private static final Logger LOG = LogManager.getLogger(Processor.class);
public String jar;
public List<String> sides;
public List<String> classpath;
@ -80,9 +76,9 @@ public class Processor {
: FileSystem.LIBRARIES.toFile();
File jarPath = Utils.convertMavenIdentifierToFile(this.jar, librariesDirectory);
LOG.debug("Jar path is " + jarPath);
LogManager.debug("Jar path is " + jarPath);
if (!jarPath.exists() || !jarPath.isFile()) {
LOG.error("Failed to process processor with jar " + this.jar + " as the jar doesn't exist");
LogManager.error("Failed to process processor with jar " + this.jar + " as the jar doesn't exist");
instanceInstaller.cancel(true);
return;
}
@ -90,10 +86,10 @@ public class Processor {
JarFile jarFile = new JarFile(jarPath);
String mainClass = jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
jarFile.close();
LOG.debug("Found mainclass of " + mainClass);
LogManager.debug("Found mainclass of " + mainClass);
if (mainClass == null || mainClass.isEmpty()) {
LOG.error("Failed to process processor with jar " + this.jar + " as the mainclass wasn't found");
LogManager.error("Failed to process processor with jar " + this.jar + " as the mainclass wasn't found");
instanceInstaller.cancel(true);
return;
}
@ -102,11 +98,11 @@ public class Processor {
classpath.add(jarPath.toURI().toURL());
for (String classpathItem : this.getClasspath()) {
LOG.debug("Adding classpath " + classpathItem);
LogManager.debug("Adding classpath " + classpathItem);
File classpathFile = Utils.convertMavenIdentifierToFile(classpathItem, FileSystem.LIBRARIES.toFile());
if (!classpathFile.exists() || !classpathFile.isFile()) {
LOG.error("Failed to process processor with jar " + this.jar
LogManager.error("Failed to process processor with jar " + this.jar
+ " as the classpath item with file " + classpathFile.getAbsolutePath() + " doesn't exist");
instanceInstaller.cancel(true);
return;
@ -123,23 +119,23 @@ public class Processor {
installProfile.data.get("ROOT").getValue(!instanceInstaller.isServer, librariesDirectory));
}
LOG.debug("Processing argument " + arg);
LogManager.debug("Processing argument " + arg);
char start = arg.charAt(0);
char end = arg.charAt(arg.length() - 1);
if (start == '{' && end == '}') {
String key = arg.substring(1, arg.length() - 1);
LOG.debug("Getting data with key of " + key);
LogManager.debug("Getting data with key of " + key);
String value = installProfile.data.get(key).getValue(!instanceInstaller.isServer, librariesDirectory);
if (value == null || value.isEmpty()) {
LOG.error("Failed to process processor with jar " + this.jar + " as the argument with name "
LogManager.error("Failed to process processor with jar " + this.jar + " as the argument with name "
+ arg + " as the data item with key " + key + " was empty or null");
instanceInstaller.cancel(true);
return;
}
LOG.debug("Got value of " + value);
LogManager.debug("Got value of " + value);
// checking for local file paths returned "/data/client.lzma" and then makes
// sure we localise it to the libraries folder if it's indeed local
if (value.charAt(0) == '/') {
@ -149,10 +145,10 @@ public class Processor {
args.add(value);
} else {
File localFile = new File(extractedDir, value);
LOG.debug("Got argument with local file of " + localFile.getAbsolutePath());
LogManager.debug("Got argument with local file of " + localFile.getAbsolutePath());
if (!localFile.exists() || !localFile.isFile()) {
LOG.error("Failed to process argument with value of " + value + " as the local file "
LogManager.error("Failed to process argument with value of " + value + " as the local file "
+ localFile.getAbsolutePath() + " doesn't exist");
instanceInstaller.cancel(true);
return;
@ -166,10 +162,10 @@ public class Processor {
} else if (start == '[' && end == ']') {
String artifact = arg.substring(1, arg.length() - 1);
File artifactFile = Utils.convertMavenIdentifierToFile(artifact, FileSystem.LIBRARIES.toFile());
LOG.debug("Got argument with file of " + artifactFile.getAbsolutePath());
LogManager.debug("Got argument with file of " + artifactFile.getAbsolutePath());
if (!artifactFile.exists() || !artifactFile.isFile()) {
LOG.error("Failed to process argument with value of " + arg + " as the file "
LogManager.error("Failed to process argument with value of " + arg + " as the file "
+ artifactFile.getAbsolutePath() + " doesn't exist");
instanceInstaller.cancel(true);
return;
@ -202,18 +198,20 @@ public class Processor {
currentThread.setContextClassLoader(cl);
try {
LOG.debug("Running processor with args \"" + String.join(" ", args) + "\"");
LogManager.debug("Running processor with args \"" + String.join(" ", args) + "\"");
Class<?> cls = Class.forName(mainClass, true, cl);
Method main = cls.getDeclaredMethod("main", String[].class);
main.invoke(null, (Object) args.toArray(new String[args.size()]));
} catch (InvocationTargetException ite) {
Throwable e = ite.getCause();
LOG.error("Failed to process processor with jar " + this.jar + " as there was an error invoking the jar",
e);
LogManager.logStackTrace(e);
LogManager.error(
"Failed to process processor with jar " + this.jar + " as there was an error invoking the jar");
instanceInstaller.cancel(true);
} catch (Throwable e) {
LOG.error("Failed to process processor with jar " + this.jar + " as there was an error invoking the jar",
e);
LogManager.logStackTrace(e);
LogManager.error(
"Failed to process processor with jar " + this.jar + " as there was an error invoking the jar");
instanceInstaller.cancel(true);
} finally {
currentThread.setContextClassLoader(threadClassloader);
@ -223,7 +221,7 @@ public class Processor {
public boolean needToRun(ForgeInstallProfile installProfile, File extractedDir,
InstanceInstaller instanceInstaller) {
if (this.sides != null && !this.sides.contains(instanceInstaller.isServer ? "server" : "client")) {
LOG.debug("No need to run processor " + this.jar + " since it's not needed for this side");
LogManager.debug("No need to run processor " + this.jar + " since it's not needed for this side");
return false;
}
@ -236,17 +234,17 @@ public class Processor {
for (Entry<String, String> entry : this.outputs.entrySet()) {
String key = entry.getKey();
LOG.debug("Processing output for " + key);
LogManager.debug("Processing output for " + key);
char start = key.charAt(0);
char end = key.charAt(key.length() - 1);
if (start == '{' && end == '}') {
LOG.debug("Getting data with key of " + key.substring(1, key.length() - 1));
LogManager.debug("Getting data with key of " + key.substring(1, key.length() - 1));
String dataItem = installProfile.data.get(key.substring(1, key.length() - 1))
.getValue(!instanceInstaller.isServer, librariesDirectory);
if (dataItem == null || dataItem.isEmpty()) {
LOG.error("Failed to process processor with jar " + this.jar + " as the output with key "
LogManager.error("Failed to process processor with jar " + this.jar + " as the output with key "
+ key + " doesn't have a corresponding data entry");
instanceInstaller.cancel(true);
return true;
@ -263,11 +261,11 @@ public class Processor {
char valueEnd = value.charAt(value.length() - 1);
if (valueStart == '{' && valueEnd == '}') {
LOG.debug("Getting data with key of " + value.substring(1, value.length() - 1));
LogManager.debug("Getting data with key of " + value.substring(1, value.length() - 1));
String valueDataItem = installProfile.data.get(value.substring(1, value.length() - 1))
.getValue(!instanceInstaller.isServer, librariesDirectory);
if (dataItem == null || dataItem.isEmpty()) {
LOG.error("Failed to process processor with jar " + this.jar
LogManager.error("Failed to process processor with jar " + this.jar
+ " as the output with value " + value + " doesn't have a corresponding data entry");
instanceInstaller.cancel(true);
return true;
@ -278,7 +276,7 @@ public class Processor {
? valueDataItem.substring(1, valueDataItem.length() - 1)
: valueDataItem;
LOG.debug("Expecting " + sha1Hash + " to equal " + sha1Hash);
LogManager.debug("Expecting " + sha1Hash + " to equal " + sha1Hash);
if (!sha1Hash.equals(expectedHash)) {
Utils.delete(outputFile);
return true;
@ -287,7 +285,7 @@ public class Processor {
}
}
LOG.debug("No need to run processor " + this.jar + " since outputs all match hashes");
LogManager.debug("No need to run processor " + this.jar + " since outputs all match hashes");
return false;
}

View file

@ -35,9 +35,6 @@ import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.constants.Constants;
import com.atlauncher.data.minecraft.Arguments;
@ -45,14 +42,13 @@ import com.atlauncher.data.minecraft.Library;
import com.atlauncher.data.minecraft.loaders.Loader;
import com.atlauncher.data.minecraft.loaders.LoaderVersion;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import com.atlauncher.utils.Utils;
import com.atlauncher.workers.InstanceInstaller;
import com.google.gson.reflect.TypeToken;
public class QuiltLoader implements Loader {
private static final Logger LOG = LogManager.getLogger(QuiltLoader.class);
protected String minecraft;
protected QuiltMetaVersion version;
protected File tempDir;
@ -70,7 +66,7 @@ public class QuiltLoader implements Loader {
} else if (metadata.containsKey("loader")) {
this.version = this.getVersion((String) metadata.get("loader"));
} else if ((boolean) metadata.get("latest")) {
LOG.debug("Downloading latest Quilt version");
LogManager.debug("Downloading latest Quilt version");
this.version = this.getLatestVersion();
}
}
@ -213,7 +209,7 @@ public class QuiltLoader implements Loader {
.getBytes(StandardCharsets.UTF_8));
propertiesOutputStream.close();
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}

View file

@ -20,15 +20,11 @@ package com.atlauncher.data.mojang.api;
import java.io.IOException;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.annot.Json;
import com.atlauncher.managers.LogManager;
@Json
public class MinecraftProfileResponse {
private static final Logger LOG = LogManager.getLogger(MinecraftProfileResponse.class);
private String id;
private String name;
private List<UserPropertyRaw> properties;
@ -51,7 +47,7 @@ public class MinecraftProfileResponse {
try {
return property.parse();
} catch (IOException e) {
LOG.error("Error parsing user property " + name + " for username " + name, e);
LogManager.logStackTrace("Error parsing user property " + name + " for username " + name, e);
}
}
}

View file

@ -19,15 +19,11 @@ package com.atlauncher.data.mojang.api;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.annot.Json;
import com.atlauncher.managers.LogManager;
@Json
public class UserProperty {
private static final Logger LOG = LogManager.getLogger(UserProperty.class);
private long timestamp;
private String profileId;
private String profileName;
@ -52,7 +48,7 @@ public class UserProperty {
public ProfileTexture getTexture(String name) {
if (!textures.containsKey(name)) {
LOG.error("No texture " + name + " for account " + this.profileName);
LogManager.error("No texture " + name + " for account " + this.profileName);
return null;
}

View file

@ -27,8 +27,8 @@ import java.util.UUID;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.managers.LogManager;
import org.freedesktop.dbus.DBusMap;
import org.freedesktop.dbus.DBusMatchRule;
import org.freedesktop.dbus.connections.impl.DBusConnection;
@ -38,8 +38,6 @@ import org.freedesktop.dbus.types.UInt32;
import org.freedesktop.dbus.types.Variant;
public class DBusUtils {
private static final Logger LOG = LogManager.getLogger(DBusUtils.class);
public static File[] selectFiles() {
try {
DBusConnection bus = DBusConnection.getConnection(DBusConnection.DBusBusType.SESSION);
@ -96,7 +94,7 @@ public class DBusUtils {
}).toArray(size -> new File[selectedFiles.get().length]);
}
} catch (Throwable t) {
LOG.error("Error selecting files using DBus", t);
LogManager.logStackTrace("Error selecting files using DBus", t);
}
return new File[0];

View file

@ -0,0 +1,114 @@
/*
* ATLauncher - https://github.com/ATLauncher/ATLauncher
* Copyright (C) 2013-2022 ATLauncher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.atlauncher.evnt;
import java.awt.Color;
import javax.swing.UIManager;
import com.atlauncher.App;
import com.atlauncher.FileSystem;
import com.atlauncher.gui.components.Console;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Timestamper;
import org.apache.logging.log4j.Logger;
public final class LogEvent {
public static final int CONSOLE = 0xA;
public static final int LOG4J = 0xB;
public final LogType type;
public final String body;
public final int meta;
public LogEvent(LogType type, String body) {
this(type, body, CONSOLE | LOG4J);
}
public LogEvent(LogType type, String body, int meta) {
this.type = type;
if (App.settings != null && !LogManager.showDebug) {
body = body.replace(FileSystem.BASE_DIR.toAbsolutePath().toString(), "**USERSDIR**");
}
this.body = (!body.endsWith("\n") ? body + "\n" : body);
this.meta = meta;
}
public void post(Logger logger) {
if ((this.meta & CONSOLE) == CONSOLE) {
Console c = App.console.console;
c.setColor(this.type.color()).setBold(true).write("[" + Timestamper.now() + "] ");
c.setColor(UIManager.getColor("EditorPane.foreground")).setBold(false).write(this.body);
}
if ((this.meta & LOG4J) == LOG4J) {
switch (type) {
case WARN: {
logger.warn(body);
break;
}
case ERROR: {
logger.error(body);
break;
}
case DEBUG: {
logger.debug(body);
break;
}
case INFO:
default: {
logger.info(body);
break;
}
}
}
}
@Override
public String toString() {
return "[" + Timestamper.now() + "] [" + this.type.name() + "]" + this.body;
}
public enum LogType {
INFO, WARN, ERROR, DEBUG;
public Color color() {
switch (this) {
case INFO: {
return UIManager.getColor("Console.LogType.info");
}
case WARN: {
return UIManager.getColor("Console.LogType.warn");
}
case ERROR: {
return UIManager.getColor("Console.LogType.error");
}
case DEBUG: {
return UIManager.getColor("Console.LogType.debug");
}
default: {
return UIManager.getColor("Console.LogType.default");
}
}
}
}
}

View file

@ -33,8 +33,6 @@ import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -45,10 +43,10 @@ import com.atlauncher.evnt.manager.ConsoleOpenManager;
import com.atlauncher.evnt.manager.RelocalizationManager;
import com.atlauncher.gui.components.Console;
import com.atlauncher.gui.components.ConsoleBottomBar;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Utils;
public class LauncherConsole extends JFrame implements RelocalizationListener {
private static final Logger LOG = LogManager.getLogger(LauncherConsole.class);
private static final long serialVersionUID = -3538990021922025818L;
public Console console;
@ -72,7 +70,7 @@ public class LauncherConsole extends JFrame implements RelocalizationListener {
App.settings.consoleSize.width, App.settings.consoleSize.height);
}
} catch (Exception e) {
LOG.error("Error setting custom remembered window size settings", e);
LogManager.logStackTrace("Error setting custom remembered window size settings", e);
}
console = new Console();
@ -158,10 +156,10 @@ public class LauncherConsole extends JFrame implements RelocalizationListener {
}
public void setupLanguage() {
LOG.debug("Setting up language for console");
LogManager.debug("Setting up language for console");
copy.setText(GetText.tr("Copy"));
bottomBar.setupLanguage();
LOG.debug("Finished setting up language for console");
LogManager.debug("Finished setting up language for console");
}
public void clearConsole() {

View file

@ -33,9 +33,6 @@ import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.constants.Constants;
import com.atlauncher.data.Pack;
@ -45,16 +42,17 @@ import com.atlauncher.evnt.manager.RelocalizationManager;
import com.atlauncher.evnt.manager.TabChangeManager;
import com.atlauncher.gui.components.LauncherBottomBar;
import com.atlauncher.gui.dialogs.InstanceInstallerDialog;
import com.atlauncher.gui.tabs.accounts.AccountsTab;
import com.atlauncher.gui.tabs.InstancesTab;
import com.atlauncher.gui.tabs.news.NewsTab;
import com.atlauncher.gui.tabs.PacksBrowserTab;
import com.atlauncher.gui.tabs.ServersTab;
import com.atlauncher.gui.tabs.SettingsTab;
import com.atlauncher.gui.tabs.Tab;
import com.atlauncher.gui.tabs.tools.ToolsTab;
import com.atlauncher.gui.tabs.VanillaPacksTab;
import com.atlauncher.gui.tabs.accounts.AccountsTab;
import com.atlauncher.gui.tabs.news.NewsTab;
import com.atlauncher.gui.tabs.tools.ToolsTab;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.PackManager;
import com.atlauncher.managers.PerformanceManager;
import com.atlauncher.network.Analytics;
@ -62,16 +60,14 @@ import com.atlauncher.utils.Utils;
@SuppressWarnings("serial")
public final class LauncherFrame extends JFrame implements RelocalizationListener {
private static final Logger LOG = LogManager.getLogger(LauncherFrame.class);
private JTabbedPane tabbedPane;
private List<Tab> tabs;
public LauncherFrame(boolean show) {
LOG.info("Launcher opening");
LOG.info("Made By Bob*");
LOG.info("*(Not Actually)");
LogManager.info("Launcher opening");
LogManager.info("Made By Bob*");
LogManager.info("*(Not Actually)");
App.launcher.setParentFrame(this);
setTitle(Constants.LAUNCHER_NAME);
@ -92,22 +88,22 @@ public final class LauncherFrame extends JFrame implements RelocalizationListene
setLocation(App.settings.launcherPosition);
}
} catch (Exception e) {
LOG.error("Error setting custom remembered window size settings", e);
LogManager.logStackTrace("Error setting custom remembered window size settings", e);
}
LOG.info("Setting up Bottom Bar");
LogManager.info("Setting up Bottom Bar");
LauncherBottomBar bottomBar = new LauncherBottomBar();
LOG.info("Finished Setting up Bottom Bar");
LogManager.info("Finished Setting up Bottom Bar");
LOG.info("Setting up Tabs");
LogManager.info("Setting up Tabs");
setupTabs(); // Setup the JTabbedPane
LOG.info("Finished Setting up Tabs");
LogManager.info("Finished Setting up Tabs");
this.add(tabbedPane, BorderLayout.CENTER);
this.add(bottomBar, BorderLayout.SOUTH);
if (show) {
LOG.info("Showing Launcher");
LogManager.info("Showing Launcher");
setVisible(true);
addWindowListener(new WindowAdapter() {
@ -129,11 +125,11 @@ public final class LauncherFrame extends JFrame implements RelocalizationListene
Pack pack = PackManager.getPackBySafeName(App.packToInstall);
if (pack != null && pack.isSemiPublic() && !PackManager.canViewSemiPublicPackByCode(pack.getCode())) {
LOG.error("Error automatically installing " + pack.getName() + " as you don't have the "
LogManager.error("Error automatically installing " + pack.getName() + " as you don't have the "
+ "pack added to the launcher!");
} else {
if (AccountManager.getSelectedAccount() == null || pack == null) {
LOG
LogManager
.error("Error automatically installing " + (pack == null ? "pack" : pack.getName()) + "!");
} else {
new InstanceInstallerDialog(pack);
@ -143,21 +139,21 @@ public final class LauncherFrame extends JFrame implements RelocalizationListene
String[] parts = App.packShareCodeToInstall.split("\\|\\|\\|");
if (parts.length != 4) {
LOG.error("Error automatically installing pack from share code!");
LogManager.error("Error automatically installing pack from share code!");
} else {
Pack pack = PackManager.getPackBySafeName(parts[0]);
if (pack != null && pack.isSemiPublic() && !PackManager.canViewSemiPublicPackByCode(pack.getCode())) {
LOG.error("Error automatically installing " + pack.getName() + " as you don't have the "
LogManager.error("Error automatically installing " + pack.getName() + " as you don't have the "
+ "pack added to the launcher!");
} else {
if (pack == null) {
LOG.error("Error automatically installing pack from share code!");
LogManager.error("Error automatically installing pack from share code!");
} else {
PackVersion version = pack.getVersionByName(parts[1]);
if (version == null) {
LOG.error("Error automatically installing " + pack.getName() + " from share code!");
LogManager.error("Error automatically installing " + pack.getName() + " from share code!");
} else {
new InstanceInstallerDialog(pack, version, parts[2], Boolean.parseBoolean(parts[3]));
}

View file

@ -38,8 +38,6 @@ import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -64,6 +62,7 @@ import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.InstanceManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.OS;
import com.atlauncher.utils.Utils;
@ -75,8 +74,6 @@ import com.google.gson.reflect.TypeToken;
*/
@SuppressWarnings("serial")
public class InstanceCard extends CollapsiblePanel implements RelocalizationListener {
private static final Logger LOG = LogManager.getLogger(InstanceCard.class);
private final Instance instance;
private final JTextArea descArea = new JTextArea();
private final ImagePanel image;
@ -593,10 +590,10 @@ public class InstanceCard extends CollapsiblePanel implements RelocalizationList
clipboard.setContents(text, null);
App.TOASTER.pop(GetText.tr("Share code copied to clipboard"));
LOG.info("Share code copied to clipboard");
LogManager.info("Share code copied to clipboard");
}
} catch (IOException ex) {
LOG.error("API call failed", ex);
LogManager.logStackTrace("API call failed", ex);
}
});
shareCodeItem.setVisible((instance.getPack() != null && !instance.getPack().system)

View file

@ -37,8 +37,6 @@ import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -49,6 +47,7 @@ import com.atlauncher.gui.components.CollapsiblePanel;
import com.atlauncher.gui.components.ImagePanel;
import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.ServerManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.OS;
@ -56,8 +55,6 @@ import com.atlauncher.utils.Utils;
@SuppressWarnings("serial")
public class ServerCard extends CollapsiblePanel implements RelocalizationListener {
private static final Logger LOG = LogManager.getLogger(ServerCard.class);
private final Server server;
private final ImagePanel image;
private final JButton launchButton = new JButton(GetText.tr("Launch"));
@ -185,7 +182,7 @@ public class ServerCard extends CollapsiblePanel implements RelocalizationListen
image.setImage(server.getImage().getImage());
server.save();
} catch (IOException ex) {
LOG.error("Failed to set server image", ex);
LogManager.logStackTrace("Failed to set server image", ex);
}
}
}

View file

@ -26,16 +26,12 @@ import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.UIManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.evnt.listener.ThemeListener;
import com.atlauncher.evnt.manager.ThemeManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.OS;
public abstract class BottomBar extends JPanel implements ThemeListener {
private static final Logger LOG = LogManager.getLogger(BottomBar.class);
private static final long serialVersionUID = -7488195680365431776L;
protected final JButton nodeCraftIcon = new SMButton("/assets/image/social/nodecraft.png",
@ -67,27 +63,27 @@ public abstract class BottomBar extends JPanel implements ThemeListener {
private void setupSocialButtonListeners() {
nodeCraftIcon.addActionListener(e -> {
LOG.info("Opening Up Nodecraft");
LogManager.info("Opening Up Nodecraft");
OS.openWebBrowser("https://atl.pw/nodecraft-from-launcher");
});
discordIcon.addActionListener(e -> {
LOG.info("Opening Up ATLauncher Discord");
LogManager.info("Opening Up ATLauncher Discord");
OS.openWebBrowser("https://atl.pw/discord");
});
facebookIcon.addActionListener(e -> {
LOG.info("Opening up ATLauncher Facebook Page");
LogManager.info("Opening Up ATLauncher Facebook Page");
OS.openWebBrowser("https://atl.pw/facebook");
});
githubIcon.addActionListener(e -> {
LOG.info("Opening Up ATLauncher GitHub Page");
LogManager.info("Opening Up ATLauncher GitHub Page");
OS.openWebBrowser("https://atl.pw/github-launcher-3");
});
redditIcon.addActionListener(e -> {
LOG.info("Opening Up ATLauncher Reddit Page");
LogManager.info("Opening Up ATLauncher Reddit Page");
OS.openWebBrowser("https://atl.pw/reddit");
});
twitterIcon.addActionListener(e -> {
LOG.info("Opening Up ATLauncher Twitter Page");
LogManager.info("Opening Up ATLauncher Twitter Page");
OS.openWebBrowser("https://atl.pw/twitter");
});
}

View file

@ -27,8 +27,6 @@ import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JPanel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -38,12 +36,12 @@ import com.atlauncher.evnt.listener.RelocalizationListener;
import com.atlauncher.evnt.manager.RelocalizationManager;
import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.thread.PasteUpload;
@SuppressWarnings("serial")
public class ConsoleBottomBar extends BottomBar implements RelocalizationListener {
private static final Logger LOG = LogManager.getLogger(ConsoleBottomBar.class);
private final JButton clearButton = new JButton(GetText.tr("Clear"));
private final JButton copyLogButton = new JButton(GetText.tr("Copy Log"));
@ -72,12 +70,12 @@ public class ConsoleBottomBar extends BottomBar implements RelocalizationListene
private void addActionListeners() {
clearButton.addActionListener(e -> {
App.console.clearConsole();
LOG.info("Console Cleared");
LogManager.info("Console Cleared");
});
copyLogButton.addActionListener(e -> {
Analytics.sendEvent("CopyLog", "Launcher");
App.TOASTER.pop("Copied Log to clipboard");
LOG.info("Copied Log to clipboard");
LogManager.info("Copied Log to clipboard");
StringSelection text = new StringSelection(App.console.getLog());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(text, null);
@ -94,7 +92,7 @@ public class ConsoleBottomBar extends BottomBar implements RelocalizationListene
Thread.currentThread().interrupt();
dialog.setReturnValue(null);
} catch (ExecutionException ex) {
LOG.error("Exception while uploading paste", ex);
LogManager.logStackTrace("Exception while uploading paste", ex);
dialog.setReturnValue(null);
}
@ -107,13 +105,13 @@ public class ConsoleBottomBar extends BottomBar implements RelocalizationListene
if (result != null && result.contains(Constants.PASTE_CHECK_URL)) {
Analytics.sendEvent("UploadLog", "Launcher");
App.TOASTER.pop("Log uploaded and link copied to clipboard");
LOG.info("Log uploaded and link copied to clipboard: {}", result);
LogManager.info("Log uploaded and link copied to clipboard: " + result);
StringSelection text = new StringSelection(result);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(text, null);
} else {
App.TOASTER.popError("Log failed to upload!");
LOG.error("Log failed to upload: {}", result);
LogManager.error("Log failed to upload: " + result);
}
});
killMinecraftButton.addActionListener(arg0 -> {

View file

@ -37,8 +37,6 @@ import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -60,6 +58,7 @@ import com.atlauncher.gui.panels.LoadingPanel;
import com.atlauncher.gui.panels.NoCurseModsPanel;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.ComboItem;
@ -69,8 +68,6 @@ import com.formdev.flatlaf.icons.FlatSearchIcon;
@SuppressWarnings("serial")
public final class AddModsDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(AddModsDialog.class);
private final Instance instance;
private boolean updating = false;
@ -485,7 +482,7 @@ public final class AddModsDialog extends JDialog {
versionsToSearchFor.addAll(MinecraftManager.getMajorMinecraftVersions(this.instance.id).stream()
.map(mv -> mv.id).collect(Collectors.toList()));
} catch (InvalidMinecraftVersion e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
versionsToSearchFor = null;
}
} else if (App.settings.addModRestriction == AddModRestriction.NONE) {

View file

@ -40,8 +40,6 @@ import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -50,6 +48,7 @@ import com.atlauncher.builders.HTMLBuilder;
import com.atlauncher.constants.UIConstants;
import com.atlauncher.data.AbstractAccount;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.ComboItem;
import com.atlauncher.utils.MojangAPIUtils;
@ -57,8 +56,6 @@ import com.atlauncher.utils.Utils;
@SuppressWarnings("serial")
public class ChangeSkinDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(ChangeSkinDialog.class);
private JTextField skinPath;
private JComboBox<ComboItem<String>> skinType;
private File selectedSkinFile;
@ -160,7 +157,7 @@ public class ChangeSkinDialog extends JDialog {
skinPath.setText(selectedPath.getAbsolutePath());
uploadButton.setEnabled(true);
} catch (IOException err) {
LOG.error("Error reading in skin", err);
LogManager.logStackTrace("Error reading in skin", err);
}
}
});

View file

@ -36,8 +36,6 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -51,6 +49,7 @@ import com.atlauncher.data.minecraft.loaders.LoaderVersion;
import com.atlauncher.exceptions.InvalidMinecraftVersion;
import com.atlauncher.gui.card.CurseForgeFileDependencyCard;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.CurseForgeApi;
@ -58,8 +57,6 @@ import com.atlauncher.utils.OS;
@SuppressWarnings("serial")
public class CurseForgeProjectFileSelectorDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(CurseForgeProjectFileSelectorDialog.class);
private int filesLength = 0;
private final CurseForgeProject mod;
private final Instance instance;
@ -290,7 +287,7 @@ public class CurseForgeProjectFileSelectorDialog extends JDialog {
.filter(v -> v.gameVersions.stream()
.anyMatch(gv -> minecraftVersionsToSearch.contains(gv)));
} catch (InvalidMinecraftVersion e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}

View file

@ -27,6 +27,7 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.swing.AbstractButton;
@ -41,14 +42,14 @@ import javax.swing.JSplitPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
import com.atlauncher.builders.HTMLBuilder;
import com.atlauncher.data.DisableableMod;
import com.atlauncher.data.Instance;
import com.atlauncher.data.minecraft.FabricMod;
import com.atlauncher.data.minecraft.MCMod;
import com.atlauncher.gui.components.ModsJCheckBox;
import com.atlauncher.gui.handlers.ModsJCheckBoxTransferHandler;
import com.atlauncher.gui.layouts.WrapLayout;
@ -59,7 +60,6 @@ import com.atlauncher.utils.FileUtils;
import com.atlauncher.utils.Utils;
public class EditModsDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(EditModsDialog.class);
private static final long serialVersionUID = 7004414192679481818L;
public Instance instance;

View file

@ -48,8 +48,6 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -96,6 +94,7 @@ import com.atlauncher.data.technic.TechnicSolderModpack;
import com.atlauncher.exceptions.InvalidMinecraftVersion;
import com.atlauncher.gui.components.JLabelWithHover;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.ComboItem;
@ -107,8 +106,6 @@ import com.atlauncher.utils.Utils;
import okhttp3.CacheControl;
public class InstanceInstallerDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(InstanceInstallerDialog.class);
private static final long serialVersionUID = -6984886874482721558L;
private int versionLength = 0;
private int loaderVersionLength = 0;
@ -602,7 +599,7 @@ public class InstanceInstallerDialog extends JDialog {
packVersion.minecraftVersion = MinecraftManager
.getMinecraftVersion(version.gameVersions.get(0));
} catch (InvalidMinecraftVersion e) {
LOG.error(e.getMessage());
LogManager.error(e.getMessage());
packVersion.minecraftVersion = null;
}
@ -702,7 +699,7 @@ public class InstanceInstallerDialog extends JDialog {
try {
packVersion.minecraftVersion = MinecraftManager.getMinecraftVersion(curseForgeManifest.minecraft.version);
} catch (InvalidMinecraftVersion e) {
LOG.error(e.getMessage());
LogManager.error(e.getMessage());
return;
}
@ -729,7 +726,7 @@ public class InstanceInstallerDialog extends JDialog {
packVersion.minecraftVersion = MinecraftManager
.getMinecraftVersion(modrinthManifest.dependencies.get("minecraft"));
} catch (InvalidMinecraftVersion e) {
LOG.error(e.getMessage());
LogManager.error(e.getMessage());
return;
}
@ -759,14 +756,14 @@ public class InstanceInstallerDialog extends JDialog {
.filter(c -> c.uid.equalsIgnoreCase("net.minecraft")).findFirst();
if (!minecraftVersionComponent.isPresent()) {
LOG.error("No net.minecraft component present in manifest");
LogManager.error("No net.minecraft component present in manifest");
return;
}
packVersion.minecraftVersion = MinecraftManager
.getMinecraftVersion(minecraftVersionComponent.get().version);
} catch (InvalidMinecraftVersion e) {
LOG.error(e.getMessage());
LogManager.error(e.getMessage());
return;
}

View file

@ -33,8 +33,6 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -51,6 +49,7 @@ import com.atlauncher.data.microsoft.XboxLiveAuthResponse;
import com.atlauncher.gui.panels.LoadingPanel;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.DownloadException;
import com.atlauncher.utils.MicrosoftAuthAPI;
import com.atlauncher.utils.OS;
@ -60,8 +59,6 @@ import net.freeutils.httpserver.HTTPServer.VirtualHost;
@SuppressWarnings("serial")
public final class LoginWithMicrosoftDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(LoginWithMicrosoftDialog.class);
private static final HTTPServer server = new HTTPServer(Constants.MICROSOFT_LOGIN_REDIRECT_PORT);
private static final VirtualHost host = server.getVirtualHost(null);
@ -116,7 +113,7 @@ public final class LoginWithMicrosoftDialog extends JDialog {
try {
startServer();
} catch (IOException e) {
LOG.error("Error starting web server for Microsoft login", e);
LogManager.logStackTrace("Error starting web server for Microsoft login", e);
close();
}
@ -136,7 +133,7 @@ public final class LoginWithMicrosoftDialog extends JDialog {
if (req.getParams().containsKey("error")) {
res.getHeaders().add("Content-Type", "text/plain");
res.send(500, GetText.tr("Error logging in. Check console for more information"));
LOG.error("Error logging into Microsoft account: {}", URLDecoder
LogManager.error("Error logging into Microsoft account: " + URLDecoder
.decode(req.getParams().get("error_description"), StandardCharsets.UTF_8.toString()));
close();
return 0;
@ -152,7 +149,7 @@ public final class LoginWithMicrosoftDialog extends JDialog {
try {
acquireAccessToken(req.getParams().get("code"));
} catch (Exception e) {
LOG.error("Error acquiring accessToken", e);
LogManager.logStackTrace("Error acquiring accessToken", e);
res.getHeaders().add("Content-Type", "text/html");
res.send(500, GetText.tr("Error logging in. Check console for more information"));
close();
@ -217,14 +214,14 @@ public final class LoginWithMicrosoftDialog extends JDialog {
xstsAuthResponse = MicrosoftAuthAPI.getXstsToken(xblToken);
} catch (DownloadException e) {
if (e.response != null) {
LOG.debug(Gsons.DEFAULT.toJson(e.response));
LogManager.debug(Gsons.DEFAULT.toJson(e.response));
XboxLiveAuthErrorResponse xboxLiveAuthErrorResponse = Gsons.DEFAULT.fromJson(e.response,
XboxLiveAuthErrorResponse.class);
String error = xboxLiveAuthErrorResponse.getErrorMessageForCode();
if (error != null) {
LOG.warn(error);
LogManager.warn(error);
DialogManager.okDialog().setTitle(GetText.tr("Error logging into Xbox Live"))
.setContent(new HTMLBuilder().center().text(error).build()).setType(DialogManager.ERROR)
.show();

View file

@ -37,8 +37,6 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -53,6 +51,7 @@ import com.atlauncher.data.modrinth.ModrinthVersion;
import com.atlauncher.exceptions.InvalidMinecraftVersion;
import com.atlauncher.gui.card.ModrinthProjectDependencyCard;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.ComboItem;
@ -61,10 +60,7 @@ import com.atlauncher.utils.OS;
@SuppressWarnings("serial")
public class ModrinthVersionSelectorDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(ModrinthVersionSelectorDialog.class);
private int versionsLength = 0;
private int filesLength = 0;
private final ModrinthProject mod;
private final Instance instance;
@ -371,7 +367,7 @@ public class ModrinthVersionSelectorDialog extends JDialog {
modrinthVersionsStream = modrinthVersionsStream.filter(
v -> v.gameVersions.stream().anyMatch(gv -> minecraftVersionsToSearch.contains(gv)));
} catch (InvalidMinecraftVersion e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}

View file

@ -35,8 +35,6 @@ import javax.swing.JSplitPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -44,6 +42,7 @@ import com.atlauncher.Gsons;
import com.atlauncher.data.json.Mod;
import com.atlauncher.gui.components.ModsJCheckBox;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.Utils;
import com.atlauncher.workers.InstanceInstaller;
@ -52,8 +51,6 @@ import com.google.gson.reflect.TypeToken;
import io.github.asyncronous.toast.Toaster;
public class ModsChooser extends JDialog {
private static final Logger LOG = LogManager.getLogger(ModsChooser.class);
private static final long serialVersionUID = -5309108183485463434L;
private final InstanceInstaller installer;
private final JButton useShareCode;
@ -225,7 +222,7 @@ public class ModsChooser extends JDialog {
} else {
Mod linkedMod = installer.getModByName(mod.getLinked());
if (linkedMod == null) {
LOG.error("The mod " + mod.getName() + " tried to reference a linked mod "
LogManager.error("The mod " + mod.getName() + " tried to reference a linked mod "
+ mod.getLinked() + " which doesn't exist!");
installer.cancel(true);
return;
@ -415,7 +412,7 @@ public class ModsChooser extends JDialog {
}
}
} catch (Exception e) {
LOG.error("Invalid share code!");
LogManager.error("Invalid share code!");
Toaster.instance().popError(GetText.tr("Invalid Share Code"));
}
}
@ -454,7 +451,7 @@ public class ModsChooser extends JDialog {
for (Mod mod : linkedMods) {
for (ModsJCheckBox check : modCheckboxes) {
if (check.getMod() == mod) {
LOG.debug("Selected " + a.getMod().getName() + " which is auto selecting "
LogManager.debug("Selected " + a.getMod().getName() + " which is auto selecting "
+ check.getMod().getName() + " because it's a linked mod.");
check.setEnabled(true);
}
@ -465,7 +462,7 @@ public class ModsChooser extends JDialog {
for (Mod mod : groupMods) {
for (ModsJCheckBox check : modCheckboxes) {
if (check.getMod() == mod) {
LOG.debug("Selected " + a.getMod().getName() + " which is auto deselecting "
LogManager.debug("Selected " + a.getMod().getName() + " which is auto deselecting "
+ check.getMod().getName() + " because it's in the same group.");
check.setSelected(false);
}
@ -477,7 +474,7 @@ public class ModsChooser extends JDialog {
for (Mod mod : dependsMods) {
for (ModsJCheckBox check : modCheckboxes) {
if (check.getMod() == mod && !sortedOut.contains(check)) {
LOG.debug("Selected " + a.getMod().getName() + " which is auto selecting "
LogManager.debug("Selected " + a.getMod().getName() + " which is auto selecting "
+ check.getMod().getName() + " because it's a dependency.");
sortedOut.add(check);
check.setSelected(true);
@ -491,7 +488,7 @@ public class ModsChooser extends JDialog {
for (Mod mod : linkedMods) {
for (ModsJCheckBox check : modCheckboxes) {
if (check.getMod() == mod) {
LOG.debug("Deselected " + a.getMod().getName() + " which is auto deselecting "
LogManager.debug("Deselected " + a.getMod().getName() + " which is auto deselecting "
+ check.getMod().getName() + " because it's a linked mod.");
check.setEnabled(false);
check.setSelected(false);
@ -503,7 +500,7 @@ public class ModsChooser extends JDialog {
for (Mod mod : dependedMods) {
for (ModsJCheckBox check : modCheckboxes) {
if (check.getMod() == mod) {
LOG.debug("Deselected " + a.getMod().getName() + " which is auto deselecting "
LogManager.debug("Deselected " + a.getMod().getName() + " which is auto deselecting "
+ check.getMod().getName() + " because it's a dependant mod.");
check.setSelected(false);
}
@ -515,7 +512,7 @@ public class ModsChooser extends JDialog {
for (ModsJCheckBox check : modCheckboxes) {
if (check.getMod() == mod) {
if (check.getMod().isLibrary()) {
LOG.debug("Deselected " + a.getMod().getName() + " which is auto deselecting "
LogManager.debug("Deselected " + a.getMod().getName() + " which is auto deselecting "
+ check.getMod().getName() + " because it's a dependant library mod.");
check.setSelected(false);
}

View file

@ -28,18 +28,15 @@ import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
import com.atlauncher.interfaces.NetworkProgressable;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Utils;
import org.mini2Dx.gettext.GetText;
@SuppressWarnings("serial")
public class ProgressDialog<T> extends JDialog implements NetworkProgressable {
private static final Logger LOG = LogManager.getLogger(ProgressDialog.class);
private final String labelText; // The text to add to the JLabel
private final JProgressBar progressBar; // The Progress Bar
private final JProgressBar subProgressBar; // The Progress Bar
@ -89,7 +86,7 @@ public class ProgressDialog<T> extends JDialog implements NetworkProgressable {
public void windowClosing(WindowEvent e) {
wasClosed = true;
if (closedLogMessage != null) {
LOG.error(closedLogMessage);
LogManager.error(closedLogMessage);
}
if (thread != null) {
if (thread.isAlive()) {

View file

@ -31,8 +31,6 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -41,12 +39,12 @@ import com.atlauncher.constants.UIConstants;
import com.atlauncher.data.Instance;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.InstanceManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.Utils;
@SuppressWarnings("serial")
public class RenameInstanceDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(RenameInstanceDialog.class);
private JTextField instanceName;
@ -129,7 +127,7 @@ public class RenameInstanceDialog extends JDialog {
if (instance.rename(instanceName.getText())) {
App.launcher.reloadInstancesPanel();
} else {
LOG.error("Unknown Error Occurred While Renaming Instance!");
LogManager.error("Unknown Error Occurred While Renaming Instance!");
DialogManager.okDialog().setParent(RenameInstanceDialog.this).setTitle(GetText.tr("Error"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
"An error occurred renaming the instance.<br/><br/>Please check the console and try again."))

View file

@ -31,8 +31,6 @@ import java.util.Set;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -50,6 +48,7 @@ import com.atlauncher.gui.dialogs.EditModsDialog;
import com.atlauncher.gui.dialogs.FileTypeDialog;
import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.CurseForgeApi;
import com.atlauncher.utils.Hashing;
import com.atlauncher.utils.ModrinthApi;
@ -57,8 +56,6 @@ import com.atlauncher.utils.Utils;
@SuppressWarnings("serial")
public class ModsJCheckBoxTransferHandler extends TransferHandler {
private static final Logger LOG = LogManager.getLogger(ModsJCheckBoxTransferHandler.class);
private final EditModsDialog dialog;
private final boolean disabled;
@ -194,7 +191,7 @@ public class ModsJCheckBoxTransferHandler extends TransferHandler {
.murmur(dm.getFile(dialog.instance.ROOT, dialog.instance.id).toPath());
murmurHashes.put(hash, dm);
} catch (Throwable t) {
LOG.error(t);
LogManager.logStackTrace(t);
}
});
@ -232,7 +229,7 @@ public class ModsJCheckBoxTransferHandler extends TransferHandler {
dm.description = curseForgeProject.summary;
}
LOG.debug("Found matching mod from CurseForge called "
LogManager.debug("Found matching mod from CurseForge called "
+ dm.curseForgeFile.displayName);
});
}
@ -254,7 +251,7 @@ public class ModsJCheckBoxTransferHandler extends TransferHandler {
.getFile(dialog.instance.ROOT, dialog.instance.id).toPath())
.toString(), dm);
} catch (Throwable t) {
LOG.error(t);
LogManager.logStackTrace(t);
}
});
@ -289,9 +286,10 @@ public class ModsJCheckBoxTransferHandler extends TransferHandler {
dm.description = project.description;
}
LOG.debug(String.format(
"Found matching mod from Modrinth called %s with file %s",
project.title, version.name));
LogManager
.debug(String.format(
"Found matching mod from Modrinth called %s with file %s",
project.title, version.name));
}
}
}

View file

@ -28,8 +28,6 @@ import java.util.stream.Collectors;
import javax.swing.JPanel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.constants.Constants;
@ -44,12 +42,11 @@ import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.CurseForgeApi;
public class CurseForgePacksPanel extends PackBrowserPlatformPanel {
private static final Logger LOG = LogManager.getLogger(CurseForgePacksPanel.class);
GridBagConstraints gbc = new GridBagConstraints();
boolean hasMorePages = true;
@ -223,7 +220,7 @@ public class CurseForgePacksPanel extends PackBrowserPlatformPanel {
Matcher matcher = pattern.matcher(id);
if (!matcher.find() || matcher.groupCount() < 2) {
LOG.error("Cannot install as the url was not a valid CurseForge modpack url");
LogManager.error("Cannot install as the url was not a valid CurseForge modpack url");
progressDialog.doneTask();
progressDialog.close();
return;

View file

@ -29,8 +29,6 @@ import java.util.stream.Collectors;
import javax.swing.JPanel;
import org.apache.commons.text.WordUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.constants.UIConstants;
@ -46,12 +44,11 @@ import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.ModrinthApi;
public class ModrinthPacksPanel extends PackBrowserPlatformPanel {
private static final Logger LOG = LogManager.getLogger(ModrinthPacksPanel.class);
GridBagConstraints gbc = new GridBagConstraints();
boolean hasMorePages = true;
@ -208,7 +205,7 @@ public class ModrinthPacksPanel extends PackBrowserPlatformPanel {
Matcher matcher = pattern.matcher(id);
if (!matcher.find() || matcher.groupCount() < 1) {
LOG.error("Cannot install as the url was not a valid Modrinth modpack url");
LogManager.error("Cannot install as the url was not a valid Modrinth modpack url");
return;
}

View file

@ -50,8 +50,6 @@ import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
@ -73,14 +71,13 @@ import com.atlauncher.exceptions.InvalidMinecraftVersion;
import com.atlauncher.managers.ConfigManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.InstanceManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.MinecraftManager;
import com.atlauncher.utils.ComboItem;
import com.atlauncher.utils.Utils;
@SuppressWarnings("serial")
public final class VanillaPacksTab extends JPanel implements Tab {
private static final Logger LOG = LogManager.getLogger(VanillaPacksTab.class);
private final List<VersionManifestVersionType> minecraftVersionTypeFilters = new ArrayList<>(
Arrays.asList(VersionManifestVersionType.RELEASE));
private String selectedMinecraftVersion = null;
@ -726,7 +723,7 @@ public final class VanillaPacksTab extends JPanel implements Tab {
minecraftVersionTable.setRowSelectionInterval(0, 0);
}
} catch (InvalidMinecraftVersion e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}

View file

@ -41,11 +41,8 @@ import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.gui.tabs.Tab;
import com.atlauncher.builders.HTMLBuilder;
import com.atlauncher.constants.UIConstants;
import com.atlauncher.data.AbstractAccount;
@ -56,16 +53,17 @@ import com.atlauncher.evnt.listener.RelocalizationListener;
import com.atlauncher.evnt.manager.RelocalizationManager;
import com.atlauncher.gui.dialogs.LoginWithMicrosoftDialog;
import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.gui.tabs.Tab;
import com.atlauncher.gui.tabs.accounts.IAccountsViewModel.LoginPostResult;
import com.atlauncher.gui.tabs.accounts.IAccountsViewModel.LoginPreCheckResult;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.ComboItem;
import com.atlauncher.utils.OS;
import com.atlauncher.utils.SkinUtils;
public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
private static final Logger LOG = LogManager.getLogger(AccountsTab.class);
private static final long serialVersionUID = 2493791137600123223L;
private final IAccountsViewModel viewModel;
@ -99,16 +97,16 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
JEditorPane infoTextPane = new JEditorPane("text/html", new HTMLBuilder().center().text(GetText.tr(
"In order to login and use ATLauncher modpacks, " +
"you must authenticate with your existing " +
"Minecraft/Mojang account. You must own and have paid " +
"for the Minecraft Java edition " +
"(not the Windows 10 edition) and use the same " +
"login here.<br><br>If you don't have an existing " +
"account, you can get one " +
"<a href=\"https://atl.pw/create-account\">by buying " +
"Minecraft here</a>. ATLauncher doesn't work with cracked" +
" accounts."))
.build());
"you must authenticate with your existing " +
"Minecraft/Mojang account. You must own and have paid " +
"for the Minecraft Java edition " +
"(not the Windows 10 edition) and use the same " +
"login here.<br><br>If you don't have an existing " +
"account, you can get one " +
"<a href=\"https://atl.pw/create-account\">by buying " +
"Minecraft here</a>. ATLauncher doesn't work with cracked" +
" accounts."))
.build());
infoTextPane.setEditable(false);
infoTextPane.addHyperlinkListener(e -> {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
@ -149,8 +147,7 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
gbc.gridwidth = 1;
gbc.insets = UIConstants.LABEL_INSETS;
gbc.anchor = GridBagConstraints.BASELINE_TRAILING;
usernameLabel =
new JLabel(GetText.tr("Username/Email") + ":");
usernameLabel = new JLabel(GetText.tr("Username/Email") + ":");
bottomPanel.add(usernameLabel, gbc);
gbc.gridx++;
@ -165,7 +162,8 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (!viewModel.isLoginPasswordSet())
passwordField.grabFocus();
else login();
else
login();
}
}
});
@ -175,8 +173,7 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
gbc.gridy++;
gbc.insets = UIConstants.LABEL_INSETS;
gbc.anchor = GridBagConstraints.BASELINE_TRAILING;
passwordLabel =
new JLabel(GetText.tr("Password") + ":");
passwordLabel = new JLabel(GetText.tr("Password") + ":");
bottomPanel.add(passwordLabel, gbc);
gbc.gridx++;
@ -188,12 +185,12 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
@Override
public void keyReleased(KeyEvent e) {
viewModel.setLoginPassword(
new String(passwordField.getPassword())
);
new String(passwordField.getPassword()));
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (!viewModel.isLoginUsernameSet())
usernameField.grabFocus();
else login();
else
login();
}
}
});
@ -215,19 +212,19 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
viewModel.setRememberLogin(rememberField.isSelected());
if (rememberField.isSelected()) {
int ret = DialogManager
.optionDialog()
.setTitle(GetText.tr("Security Warning"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
"Make sure you only do this on a " +
"computer you trust.<br/>If you do this " +
"on a shared computer, your password may be " +
"stolen.<br/>Do you still want to save " +
"your password?"))
.build())
.setType(DialogManager.ERROR)
.addOption(GetText.tr("Yes"), true)
.addOption(GetText.tr("No"))
.show();
.optionDialog()
.setTitle(GetText.tr("Security Warning"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
"Make sure you only do this on a " +
"computer you trust.<br/>If you do this " +
"on a shared computer, your password may be " +
"stolen.<br/>Do you still want to save " +
"your password?"))
.build())
.setType(DialogManager.ERROR)
.addOption(GetText.tr("Yes"), true)
.addOption(GetText.tr("No"))
.show();
if (ret != 0) {
rememberField.setSelected(false);
@ -252,24 +249,23 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
clearLogin();
} else {
int ret = DialogManager
.yesNoDialog()
.setTitle(GetText.tr("Delete"))
.setContent(GetText.tr("Are you sure you want " +
"to delete this account?"))
.setType(DialogManager.WARNING).show();
.yesNoDialog()
.setTitle(GetText.tr("Delete"))
.setContent(GetText.tr("Are you sure you want " +
"to delete this account?"))
.setType(DialogManager.WARNING).show();
if (ret == DialogManager.YES_OPTION) {
viewModel.deleteAccount();
}
}
});
loginWithMicrosoftButton =
new JButton(GetText.tr("Login with Microsoft"));
loginWithMicrosoftButton = new JButton(GetText.tr("Login with Microsoft"));
loginWithMicrosoftButton.addActionListener(e -> {
// TODO This should be handled by some reaction via listener
int numberOfAccountsBefore = viewModel.accountCount();
new LoginWithMicrosoftDialog();
if (numberOfAccountsBefore != viewModel.accountCount()) {
if (numberOfAccountsBefore != viewModel.accountCount()) {
viewModel.pushNewAccounts();
accountsComboBox.setSelectedItem(AccountManager.getSelectedAccount());
}
@ -289,7 +285,7 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
viewModel.changeSkin();
// TODO Have this done via listener
// To describe, userSkin icon should be reactive, not active.
// To describe, userSkin icon should be reactive, not active.
AbstractAccount account = viewModel.getSelectedAccount();
userSkin.setIcon(account.getMinecraftSkin());
});
@ -300,19 +296,17 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
viewModel.updateSkin();
// TODO Have this done via listener
// To describe, userSkin icon should be reactive, not active.
// To describe, userSkin icon should be reactive, not active.
AbstractAccount account = viewModel.getSelectedAccount();
userSkin.setIcon(account.getMinecraftSkin());
});
contextMenu.add(updateSkin);
JMenuItem updateUsername =
new JMenuItem(GetText.tr("Update Username"));
JMenuItem updateUsername = new JMenuItem(GetText.tr("Update Username"));
updateUsername.addActionListener(e -> viewModel.updateUsername());
contextMenu.add(updateUsername);
refreshAccessTokenMenuItem =
new JMenuItem(GetText.tr("Refresh Access Token"));
refreshAccessTokenMenuItem = new JMenuItem(GetText.tr("Refresh Access Token"));
refreshAccessTokenMenuItem.setVisible(false);
refreshAccessTokenMenuItem.addActionListener(e -> {
refreshAccessToken();
@ -330,8 +324,7 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
}
});
userSkin.setBorder(
BorderFactory.createEmptyBorder(0, 60, 0, 0)
);
BorderFactory.createEmptyBorder(0, 60, 0, 0));
add(infoPanel, BorderLayout.NORTH);
add(userSkin, BorderLayout.WEST);
add(rightPanel, BorderLayout.CENTER);
@ -346,14 +339,14 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
*/
private void refreshAccessToken() {
MicrosoftAccount account = viewModel.getSelectedAccountAs();
if (account == null) return;
if (account == null)
return;
final ProgressDialog<Boolean> dialog = new ProgressDialog<>(
GetText.tr("Refreshing Access Token"),
0,
GetText.tr("Refreshing Access Token For {0}", account.minecraftUsername),
"Aborting refreshing access token for " + account.minecraftUsername
);
GetText.tr("Refreshing Access Token"),
0,
GetText.tr("Refreshing Access Token For {0}", account.minecraftUsername),
"Aborting refreshing access token for " + account.minecraftUsername);
dialog.addThread(new Thread(() -> {
boolean success = viewModel.refreshAccessToken();
@ -366,20 +359,19 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
if (success) {
DialogManager
.okDialog()
.setTitle(GetText.tr("Access Token Refreshed"))
.setContent(
GetText.tr("Access token refreshed successfully")
)
.setType(DialogManager.INFO)
.show();
.okDialog()
.setTitle(GetText.tr("Access Token Refreshed"))
.setContent(
GetText.tr("Access token refreshed successfully"))
.setType(DialogManager.INFO)
.show();
} else {
DialogManager
.okDialog()
.setTitle(GetText.tr("Failed To Refresh Access Token"))
.setContent(GetText.tr("Failed to refresh accessToken. Please login again."))
.setType(DialogManager.ERROR)
.show();
.okDialog()
.setTitle(GetText.tr("Failed To Refresh Access Token"))
.setContent(GetText.tr("Failed to refresh accessToken. Please login again."))
.setType(DialogManager.ERROR)
.show();
new LoginWithMicrosoftDialog(account);
}
@ -419,11 +411,9 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
leftButton.setVisible(account instanceof MojangAccount);
rightButton.setVisible(true);
loginWithMicrosoftButton.setVisible(
account instanceof MicrosoftAccount
);
account instanceof MicrosoftAccount);
refreshAccessTokenMenuItem.setVisible(
account instanceof MicrosoftAccount
);
account instanceof MicrosoftAccount);
if (account instanceof MojangAccount) {
MojangAccount mojangAccount = (MojangAccount) account;
@ -444,11 +434,9 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
viewModel.onAccountsNamesChanged(accounts -> {
accountsComboBox.removeAllItems();
accountsComboBox.addItem(
new ComboItem<>(
null,
GetText.tr("Add An Account")
)
);
new ComboItem<>(
null,
GetText.tr("Add An Account")));
for (String account : accounts) {
accountsComboBox.addItem(new ComboItem<>(null, account));
}
@ -479,20 +467,20 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
LoginPreCheckResult preCheckResult = viewModel.loginPreCheck();
if (preCheckResult instanceof LoginPreCheckResult.Exists) {
DialogManager
.okDialog()
.setTitle(GetText.tr("Account Not Added"))
.setContent(GetText.tr("This account already exists."))
.setType(DialogManager.ERROR)
.show();
.okDialog()
.setTitle(GetText.tr("Account Not Added"))
.setContent(GetText.tr("This account already exists."))
.setType(DialogManager.ERROR)
.show();
return;
}
LOG.info("Logging into Minecraft!");
LogManager.info("Logging into Minecraft!");
final ProgressDialog<LoginResponse> dialog = new ProgressDialog<>(
GetText.tr("Logging Into Minecraft"),
0,
GetText.tr("Logging Into Minecraft"),
"Aborting login for " + viewModel.getLoginUsername());
GetText.tr("Logging Into Minecraft"),
0,
GetText.tr("Logging Into Minecraft"),
"Aborting login for " + viewModel.getLoginUsername());
dialog.setName("loginDialog");
dialog.addThread(new Thread(() -> {
viewModel.login();
@ -504,33 +492,30 @@ public class AccountsTab extends JPanel implements Tab, RelocalizationListener {
if (postResult instanceof LoginPostResult.Error) {
String error = ((LoginPostResult.Error) postResult).errorContent;
LOG.error("error response: {}", error);
LogManager.error("error response: " + error);
DialogManager
.okDialog()
.setTitle(GetText.tr("Account Not Added"))
.setContent(
new HTMLBuilder()
.center()
// #. {0} is the error message from Mojang as to why we couldn't login
.text(GetText.tr(
"Account not added as login " +
"details were incorrect.<br/><br/>{0}",
error
)
)
.build())
.setType(DialogManager.INFO)
.show();
.okDialog()
.setTitle(GetText.tr("Account Not Added"))
.setContent(
new HTMLBuilder()
.center()
// #. {0} is the error message from Mojang as to why we couldn't login
.text(GetText.tr(
"Account not added as login " +
"details were incorrect.<br/><br/>{0}",
error))
.build())
.setType(DialogManager.INFO)
.show();
} else {
if (postResult instanceof LoginPostResult.Edited) {
DialogManager
.okDialog()
.setTitle(GetText.tr("Account Edited"))
.setContent(
GetText.tr("Account edited successfully")
)
.setType(DialogManager.INFO)
.show();
.okDialog()
.setTitle(GetText.tr("Account Edited"))
.setContent(
GetText.tr("Account edited successfully"))
.setType(DialogManager.INFO)
.show();
}
viewModel.pushNewAccounts();

View file

@ -22,8 +22,6 @@ import java.util.UUID;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -33,6 +31,7 @@ import com.atlauncher.data.MicrosoftAccount;
import com.atlauncher.data.MojangAccount;
import com.atlauncher.gui.dialogs.ChangeSkinDialog;
import com.atlauncher.managers.AccountManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.Authentication;
@ -40,8 +39,6 @@ import com.atlauncher.utils.Authentication;
* 12 / 06 / 2022
*/
public class AccountsViewModel implements IAccountsViewModel {
private static final Logger LOG = LogManager.getLogger(AccountsViewModel.class);
@Override
public int accountCount() {
return AccountManager.getAccounts().size();
@ -194,7 +191,7 @@ public class AccountsViewModel implements IAccountsViewModel {
}
Analytics.sendEvent("Edit", "Account");
LOG.info("Edited Account {}", account);
LogManager.info("Edited Account " + account);
pushNewAccounts();
}

View file

@ -25,6 +25,8 @@ import javax.swing.JLabel;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.builders.HTMLBuilder;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.OS;
@SuppressWarnings("serial")
public class DebugModePanel extends AbstractToolPanel {
@ -37,9 +39,9 @@ public class DebugModePanel extends AbstractToolPanel {
.build());
MIDDLE_PANEL.add(INFO_LABEL);
BOTTOM_PANEL.add(LAUNCH_BUTTON);
LAUNCH_BUTTON.setEnabled(viewModel.isLaunchInDebugEnabled());
LAUNCH_BUTTON.setEnabled(!OS.isUsingFlatpak() && !LogManager.showDebug);
if (!viewModel.isDebugEnabled()) {
if (!LogManager.showDebug) {
LAUNCH_BUTTON.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {

View file

@ -22,17 +22,15 @@ import java.awt.event.ActionListener;
import javax.swing.JLabel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.builders.HTMLBuilder;
import com.atlauncher.constants.Constants;
import com.atlauncher.gui.dialogs.ProgressDialog;
import com.atlauncher.managers.DialogManager;
import com.atlauncher.managers.LogManager;
public class NetworkCheckerToolPanel extends AbstractToolPanel implements ActionListener {
private static final Logger LOG = LogManager.getLogger(NetworkCheckerToolPanel.class);
private final IToolsViewModel viewModel;
public NetworkCheckerToolPanel(IToolsViewModel viewModel) {
@ -40,50 +38,48 @@ public class NetworkCheckerToolPanel extends AbstractToolPanel implements Action
this.viewModel = viewModel;
JLabel INFO_LABEL = new JLabel(new HTMLBuilder().center().split(70)
.text(GetText.tr(
"This tool does various tests on your network and determines any issues that may pop up with "
+ "connecting to our file servers and to other servers."))
.build());
.text(GetText.tr(
"This tool does various tests on your network and determines any issues that may pop up with "
+ "connecting to our file servers and to other servers."))
.build());
MIDDLE_PANEL.add(INFO_LABEL);
BOTTOM_PANEL.add(LAUNCH_BUTTON);
LAUNCH_BUTTON.addActionListener(this);
viewModel.onCanRunNetworkCheckerChanged(LAUNCH_BUTTON::setEnabled);
}
@Override
public void actionPerformed(ActionEvent e) {
int ret = DialogManager.yesNoDialog().setTitle(GetText.tr("Network Checker"))
.setContent(new HTMLBuilder().center().split(75).text(GetText.tr(
"Please note that the data from this tool is sent to ATLauncher so we can diagnose possible issues in your setup. This test may take up to 10 minutes or longer to complete and you will be unable to do anything while it's running. Please also keep in mind that this test will use some of your bandwidth, it will use approximately 100MB.<br/><br/>Do you wish to continue?"))
.build())
.setType(DialogManager.INFO).show();
.setContent(new HTMLBuilder().center().split(75).text(GetText.tr(
"Please note that the data from this tool is sent to ATLauncher so we can diagnose possible issues in your setup. This test may take up to 10 minutes or longer to complete and you will be unable to do anything while it's running. Please also keep in mind that this test will use some of your bandwidth, it will use approximately 100MB.<br/><br/>Do you wish to continue?"))
.build())
.setType(DialogManager.INFO).show();
if (ret == 0) {
final ProgressDialog<Boolean> dialog = new ProgressDialog<>(GetText.tr("Network Checker"),
17 + viewModel.hostsLength(), GetText.tr("Network Checker Running. Please Wait!"),
"Network Checker Tool Cancelled!");
17 + viewModel.hostsLength(), GetText.tr("Network Checker Running. Please Wait!"),
"Network Checker Tool Cancelled!");
dialog.addThread(new Thread(() -> {
viewModel.runNetworkChecker(
taskComplete -> dialog.doneTask(),
fail -> dialog.setReturnValue(false),
success -> dialog.setReturnValue(true)
);
taskComplete -> dialog.doneTask(),
fail -> dialog.setReturnValue(false),
success -> dialog.setReturnValue(true));
dialog.close();
}));
dialog.start();
if (dialog.getReturnValue() == null || !dialog.getReturnValue()) {
LOG.error("Network Test failed to run!");
LogManager.error("Network Test failed to run!");
} else {
LOG.info("Network Test ran and submitted to {}!", Constants.LAUNCHER_NAME);
LogManager.info("Network Test ran and submitted to " + Constants.LAUNCHER_NAME + "!");
DialogManager.okDialog().setTitle(GetText.tr("Network Checker"))
.setContent(new HTMLBuilder().center().text(GetText.tr(
"The network checker tool has completed and the data sent off to ATLauncher.<br/><br/>Thanks for your input to help understand and fix network related issues."))
.build())
.setType(DialogManager.INFO).show();
.setContent(new HTMLBuilder().center().text(GetText.tr(
"The network checker tool has completed and the data sent off to ATLauncher.<br/><br/>Thanks for your input to help understand and fix network related issues."))
.build())
.setType(DialogManager.INFO).show();
}
}
}

View file

@ -39,7 +39,7 @@ public class RuntimeDownloaderToolPanel extends AbstractToolPanel {
JLabel INFO_LABEL = new JLabel(new HTMLBuilder().center().split(70).text(GetText
.tr("Use this to automatically install and use a recommended version of Java to use with ATLauncher."))
.build());
.build());
MIDDLE_PANEL.add(INFO_LABEL);
BOTTOM_PANEL.add(LAUNCH_BUTTON);
LAUNCH_BUTTON.addActionListener(e -> downloadRuntime());
@ -54,34 +54,32 @@ public class RuntimeDownloaderToolPanel extends AbstractToolPanel {
private void removeRuntime() {
viewModel.removeRuntime(
onFail -> {
DialogManager.okDialog().setTitle(GetText.tr("Runtime Downloader"))
.setContent(new HTMLBuilder().center()
.text(GetText.tr("An error occurred removing the runtime. Please check the logs.")).build())
.setType(DialogManager.ERROR).show();
},
onSuccess -> {
DialogManager
.okDialog().setTitle(GetText.tr("Runtime Downloader")).setContent(new HTMLBuilder().center()
.text(GetText.tr("Downloaded runtimes have been removed.")).build())
.setType(DialogManager.INFO).show();
}
);
onFail -> {
DialogManager.okDialog().setTitle(GetText.tr("Runtime Downloader"))
.setContent(new HTMLBuilder().center()
.text(GetText.tr("An error occurred removing the runtime. Please check the logs."))
.build())
.setType(DialogManager.ERROR).show();
},
onSuccess -> {
DialogManager
.okDialog().setTitle(GetText.tr("Runtime Downloader")).setContent(new HTMLBuilder().center()
.text(GetText.tr("Downloaded runtimes have been removed.")).build())
.setType(DialogManager.INFO).show();
});
}
private void downloadRuntime() {
final ProgressDialog<Boolean> dialog = new ProgressDialog<>(GetText.tr("Runtime Downloader"), 3,
GetText.tr("Downloading. Please Wait!"), "Runtime Downloader Tool Cancelled!");
GetText.tr("Downloading. Please Wait!"), "Runtime Downloader Tool Cancelled!");
dialog.addThread(new Thread(() -> {
dialog.setReturnValue(
viewModel.downloadRuntime(
dialog,
taskComplete -> dialog.doneTask(),
dialog::setLabel,
clear -> dialog.clearDownloadedBytes()
)
);
viewModel.downloadRuntime(
dialog,
taskComplete -> dialog.doneTask(),
dialog::setLabel,
clear -> dialog.clearDownloadedBytes()));
dialog.close();
}));
@ -90,16 +88,16 @@ public class RuntimeDownloaderToolPanel extends AbstractToolPanel {
if (!dialog.getReturnValue()) {
DialogManager.okDialog().setTitle(GetText.tr("Runtime Downloader"))
.setContent(new HTMLBuilder().center()
.text(GetText.tr("An error occurred downloading the runtime. Please check the logs."))
.build())
.setType(DialogManager.ERROR).show();
.setContent(new HTMLBuilder().center()
.text(GetText.tr("An error occurred downloading the runtime. Please check the logs."))
.build())
.setType(DialogManager.ERROR).show();
} else {
DialogManager.okDialog().setTitle(GetText.tr("Runtime Downloader"))
.setContent(new HTMLBuilder().center()
.text(GetText.tr("The recommended version of Java has been installed and set to be used."))
.build())
.setType(DialogManager.INFO).show();
.setContent(new HTMLBuilder().center()
.text(GetText.tr("The recommended version of Java has been installed and set to be used."))
.build())
.setType(DialogManager.INFO).show();
}
}
}

View file

@ -23,15 +23,9 @@ import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import com.atlauncher.gui.tabs.Tab;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.gui.tabs.tools.DebugModePanel;
import com.atlauncher.gui.tabs.tools.DownloadClearerToolPanel;
import com.atlauncher.gui.tabs.tools.LogClearerToolPanel;
import com.atlauncher.gui.tabs.tools.NetworkCheckerToolPanel;
import com.atlauncher.gui.tabs.tools.RuntimeDownloaderToolPanel;
import com.atlauncher.gui.tabs.tools.SkinUpdaterToolPanel;
import com.atlauncher.gui.tabs.Tab;
@SuppressWarnings("serial")
public class ToolsTab extends JPanel implements Tab {

View file

@ -17,6 +17,16 @@
*/
package com.atlauncher.gui.tabs.tools;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.FileSystem;
@ -30,28 +40,21 @@ import com.atlauncher.evnt.manager.AccountManager;
import com.atlauncher.evnt.manager.SettingsManager;
import com.atlauncher.interfaces.NetworkProgressable;
import com.atlauncher.managers.InstanceManager;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.network.Download;
import com.atlauncher.utils.*;
import okhttp3.OkHttpClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.utils.ArchiveUtils;
import com.atlauncher.utils.FileUtils;
import com.atlauncher.utils.Java;
import com.atlauncher.utils.OS;
import com.atlauncher.utils.Utils;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import okhttp3.OkHttpClient;
/**
* 15 / 06 / 2022
*/
public class ToolsViewModel implements IToolsViewModel, SettingsListener, AccountListener {
private static final Logger LOG = LogManager.getLogger(ToolsViewModel.class);
private Consumer<Boolean> onCanRunNetworkCheckerChanged;
private Consumer<Boolean> onSkinUpdaterEnabledChanged;
@ -76,7 +79,7 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
@Override
public boolean isDebugEnabled() {
return LOG.isDebugEnabled();
return LogManager.showDebug;
}
@Override
@ -131,10 +134,10 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
onCanRunNetworkCheckerChanged = onChanged;
}
private final String[] HOSTS = {"authserver.mojang.com", "session.minecraft.net", "libraries.minecraft.net",
"launchermeta.mojang.com", "launcher.mojang.com", Constants.API_HOST, Constants.PASTE_HOST,
Constants.DOWNLOAD_HOST, Constants.FABRIC_HOST, Constants.FORGE_HOST, Constants.QUILT_HOST,
Constants.CURSEFORGE_CORE_API_HOST, Constants.MODRINTH_HOST, Constants.MODPACKS_CH_HOST};
private final String[] HOSTS = { "authserver.mojang.com", "session.minecraft.net", "libraries.minecraft.net",
"launchermeta.mojang.com", "launcher.mojang.com", Constants.API_HOST, Constants.PASTE_HOST,
Constants.DOWNLOAD_HOST, Constants.FABRIC_HOST, Constants.FORGE_HOST, Constants.QUILT_HOST,
Constants.CURSEFORGE_CORE_API_HOST, Constants.MODRINTH_HOST, Constants.MODPACKS_CH_HOST };
@Override
public int hostsLength() {
@ -148,88 +151,87 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
// Connection to CDN
results.append("Ping results to " + Constants.DOWNLOAD_HOST + " was ")
.append(Utils.pingAddress(Constants.DOWNLOAD_HOST));
.append(Utils.pingAddress(Constants.DOWNLOAD_HOST));
onTaskComplete.accept(null);
results.append("Tracert to " + Constants.DOWNLOAD_HOST + " was ")
.append(Utils.traceRoute(Constants.DOWNLOAD_HOST)).append("\n\n----------------\n\n");
.append(Utils.traceRoute(Constants.DOWNLOAD_HOST)).append("\n\n----------------\n\n");
onTaskComplete.accept(null);
// Connection to ATLauncher API
results.append("Ping results to " + Constants.API_HOST + " was ")
.append(Utils.pingAddress(Constants.API_HOST));
.append(Utils.pingAddress(Constants.API_HOST));
onTaskComplete.accept(null);
results.append("Tracert to " + Constants.API_HOST + " was ")
.append(Utils.traceRoute(Constants.API_HOST)).append("\n\n----------------\n\n");
.append(Utils.traceRoute(Constants.API_HOST)).append("\n\n----------------\n\n");
onTaskComplete.accept(null);
// Connection to CurseForge Core API
results.append("Ping results to " + Constants.CURSEFORGE_CORE_API_HOST + " was ")
.append(Utils.pingAddress(Constants.CURSEFORGE_CORE_API_HOST));
.append(Utils.pingAddress(Constants.CURSEFORGE_CORE_API_HOST));
onTaskComplete.accept(null);
results.append("Tracert to " + Constants.CURSEFORGE_CORE_API_HOST + " was ")
.append(Utils.traceRoute(Constants.CURSEFORGE_CORE_API_HOST))
.append("\n\n----------------\n\n");
.append(Utils.traceRoute(Constants.CURSEFORGE_CORE_API_HOST))
.append("\n\n----------------\n\n");
onTaskComplete.accept(null);
// Connection to Modrinth API
results.append("Ping results to " + Constants.MODRINTH_HOST + " was ")
.append(Utils.pingAddress(Constants.MODRINTH_HOST));
.append(Utils.pingAddress(Constants.MODRINTH_HOST));
onTaskComplete.accept(null);
results.append("Tracert to " + Constants.MODRINTH_HOST + " was ")
.append(Utils.traceRoute(Constants.MODRINTH_HOST)).append("\n\n----------------\n\n");
.append(Utils.traceRoute(Constants.MODRINTH_HOST)).append("\n\n----------------\n\n");
onTaskComplete.accept(null);
// Connection to Modpacks.ch API
results.append("Ping results to " + Constants.MODPACKS_CH_HOST + " was ")
.append(Utils.pingAddress(Constants.MODPACKS_CH_HOST));
.append(Utils.pingAddress(Constants.MODPACKS_CH_HOST));
onTaskComplete.accept(null);
results.append("Tracert to " + Constants.MODPACKS_CH_HOST + " was ")
.append(Utils.traceRoute(Constants.MODPACKS_CH_HOST)).append("\n\n----------------\n\n");
.append(Utils.traceRoute(Constants.MODPACKS_CH_HOST)).append("\n\n----------------\n\n");
onTaskComplete.accept(null);
// Connection to Fabric CDN
results.append("Ping results to " + Constants.FABRIC_HOST + " was ")
.append(Utils.pingAddress(Constants.FABRIC_HOST));
.append(Utils.pingAddress(Constants.FABRIC_HOST));
onTaskComplete.accept(null);
results.append("Tracert to " + Constants.FABRIC_HOST + " was ")
.append(Utils.traceRoute(Constants.FABRIC_HOST)).append("\n\n----------------\n\n");
.append(Utils.traceRoute(Constants.FABRIC_HOST)).append("\n\n----------------\n\n");
onTaskComplete.accept(null);
// Connection to Forge CDN
results.append("Ping results to " + Constants.FORGE_HOST + " was ")
.append(Utils.pingAddress(Constants.FORGE_HOST));
.append(Utils.pingAddress(Constants.FORGE_HOST));
onTaskComplete.accept(null);
results.append("Tracert to " + Constants.FORGE_HOST + " was ")
.append(Utils.traceRoute(Constants.FORGE_HOST)).append("\n\n----------------\n\n");
.append(Utils.traceRoute(Constants.FORGE_HOST)).append("\n\n----------------\n\n");
onTaskComplete.accept(null);
// Connection to Quilt CDN
results.append("Ping results to " + Constants.QUILT_HOST + " was ")
.append(Utils.pingAddress(Constants.QUILT_HOST));
.append(Utils.pingAddress(Constants.QUILT_HOST));
onTaskComplete.accept(null);
results.append("Tracert to " + Constants.QUILT_HOST + " was ")
.append(Utils.traceRoute(Constants.QUILT_HOST)).append("\n\n----------------\n\n");
.append(Utils.traceRoute(Constants.QUILT_HOST)).append("\n\n----------------\n\n");
onTaskComplete.accept(null);
// Resolution of key services
for (String host : HOSTS) {
try {
String resolvedHosts = Arrays.stream(InetAddress.getAllByName(host))
.map(InetAddress::getHostAddress).collect(Collectors.joining(", "));
.map(InetAddress::getHostAddress).collect(Collectors.joining(", "));
results.append("Resolution of ").append(host).append(" was ").append(resolvedHosts)
.append("\n\n");
.append("\n\n");
} catch (Exception e1) {
results.append("Resolution of ").append(host).append(" failed: ").append(e1.toString())
.append("\n\n");
.append("\n\n");
}
onTaskComplete.accept(null);
@ -240,21 +242,21 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
// Response Code Test
try {
results.append(String.format("Response code to %s was %d\n\n----------------\n\n",
Constants.DOWNLOAD_SERVER,
Download.build()
.setUrl(String.format("%s/launcher/json/files.json", Constants.DOWNLOAD_SERVER))
.getResponseCode()));
Constants.DOWNLOAD_SERVER,
Download.build()
.setUrl(String.format("%s/launcher/json/files.json", Constants.DOWNLOAD_SERVER))
.getResponseCode()));
} catch (Exception e1) {
results.append(String.format("Exception thrown when connecting to %s\n\n----------------\n\n",
Constants.DOWNLOAD_SERVER));
Constants.DOWNLOAD_SERVER));
results.append(e1);
}
onTaskComplete.accept(null);
// Ping Pong Test
results.append(String.format("Response to ping on %s was %s\n\n----------------\n\n",
Constants.DOWNLOAD_SERVER,
Download.build().setUrl(String.format("%s/ping", Constants.DOWNLOAD_SERVER)).asString()));
Constants.DOWNLOAD_SERVER,
Download.build().setUrl(String.format("%s/ping", Constants.DOWNLOAD_SERVER)).asString()));
onTaskComplete.accept(null);
// Speed Test
@ -265,11 +267,11 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
long started = System.currentTimeMillis();
try {
Download.build().setUrl(String.format("%s/100MB.bin", Constants.DOWNLOAD_SERVER))
.downloadTo(file.toPath()).downloadFile();
.downloadTo(file.toPath()).downloadFile();
} catch (Exception e2) {
results.append(
String.format("Exception thrown when downloading 100MB.bin from %s\n\n----------------\n\n",
Constants.DOWNLOAD_SERVER));
String.format("Exception thrown when downloading 100MB.bin from %s\n\n----------------\n\n",
Constants.DOWNLOAD_SERVER));
results.append(e2);
}
@ -278,20 +280,20 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
float kbps = bps / 1024;
float mbps = kbps / 1024;
String speed = (mbps < 1
? (kbps < 1 ? String.format("%.2f B/s", bps) : String.format("%.2f " + "KB/s", kbps))
: String.format("%.2f MB/s", mbps));
? (kbps < 1 ? String.format("%.2f B/s", bps) : String.format("%.2f " + "KB/s", kbps))
: String.format("%.2f MB/s", mbps));
results.append(
String.format("Download speed to %s was %s, " + "" + "taking %.2f seconds to download 100MB",
Constants.DOWNLOAD_SERVER, speed, (timeTaken / 1000.0)));
String.format("Download speed to %s was %s, " + "" + "taking %.2f seconds to download 100MB",
Constants.DOWNLOAD_SERVER, speed, (timeTaken / 1000.0)));
onTaskComplete.accept(null);
String result = Utils.uploadPaste(Constants.LAUNCHER_NAME + " Network Test Log", results.toString());
if (result.contains(Constants.PASTE_CHECK_URL)) {
LOG.info("Network Test has finished running, you can view the results at {}", result);
LogManager.info("Network Test has finished running, you can view the results at " + result);
onTaskComplete.accept(null);
onSuccess.accept(null);
} else {
LOG.error("Network Test failed to submit to {}!", Constants.LAUNCHER_NAME);
LogManager.error("Network Test failed to submit");
onTaskComplete.accept(null);
onFail.accept(null);
}
@ -299,11 +301,12 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
private Consumer<Boolean> _onCanDownloadRuntimeChanged;
private Consumer<Boolean> _onCanRemoveDownloadChanged;
private boolean canDownloadRuntime(){
private boolean canDownloadRuntime() {
return !OS.isLinux();
}
private boolean canRemoveDownload(){
private boolean canRemoveDownload() {
return !OS.isLinux() && Java.hasInstalledRuntime();
}
@ -319,7 +322,7 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
onChanged.accept(canRemoveDownload());
}
private void updateDownloadButtons(){
private void updateDownloadButtons() {
_onCanDownloadRuntimeChanged.accept(canDownloadRuntime());
_onCanRemoveDownloadChanged.accept(canRemoveDownload());
}
@ -338,14 +341,14 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
// remove the path from any custom paths set for instances
InstanceManager.getInstances().stream()
.filter(i -> i.launcher.javaPath != null && i.launcher.javaPath.contains(oldPath)).forEach(i -> {
i.launcher.javaPath = null;
i.save();
});
.filter(i -> i.launcher.javaPath != null && i.launcher.javaPath.contains(oldPath)).forEach(i -> {
i.launcher.javaPath = null;
i.save();
});
onSuccess.accept(null);
} else {
LOG.error("Runtime removal failed!");
LogManager.error("Runtime removal failed!");
onFail.accept(null);
}
updateDownloadButtons();
@ -358,16 +361,15 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
@Override
public boolean downloadRuntime(
NetworkProgressable progressbar,
Consumer<Void> onTaskComplete,
Consumer<String> newLabel,
Consumer<Void> clearDownloadedBytes
) {
NetworkProgressable progressbar,
Consumer<Void> onTaskComplete,
Consumer<String> newLabel,
Consumer<Void> clearDownloadedBytes) {
Analytics.sendEvent("RuntimeDownloader", "Run", "Tool");
Runtimes runtimes = Download.build().cached()
.setUrl(String.format("%s/launcher/json/runtimes.json", Constants.DOWNLOAD_SERVER))
.asClass(Runtimes.class);
.setUrl(String.format("%s/launcher/json/runtimes.json", Constants.DOWNLOAD_SERVER))
.asClass(Runtimes.class);
onTaskComplete.accept(null);
Runtime runtime = runtimes.getRuntimeForOS();
@ -379,7 +381,7 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
// no need to download/extract
if (releaseFile.exists()) {
downloadRuntimePost(runtimeFolder.getAbsolutePath());
LOG.info("Runtime downloaded!");
LogManager.info("Runtime downloaded!");
updateDownloadButtons();
return true;
}
@ -396,8 +398,8 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
OkHttpClient httpClient = Network.createProgressClient(progressbar);
com.atlauncher.network.Download download = com.atlauncher.network.Download.build().setUrl(url)
.hash(runtime.sha1).size(runtime.size).withHttpClient(httpClient)
.downloadTo(downloadFile.toPath());
.hash(runtime.sha1).size(runtime.size).withHttpClient(httpClient)
.downloadTo(downloadFile.toPath());
if (download.needToDownload()) {
newLabel.accept(GetText.tr("Downloading"));
@ -406,8 +408,7 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
try {
download.downloadFile();
} catch (IOException e1) {
LOG.error("error", e1);
LOG.error("Runtime downloaded failed to run!");
LogManager.logStackTrace("Runtime downloaded failed to run!", e1);
updateDownloadButtons();
return false;
}
@ -422,8 +423,7 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
try {
Utils.unXZFile(downloadFile, unpackedFile);
} catch (IOException e2) {
LOG.error("error", e2);
LOG.error("Runtime downloaded failed to run!");
LogManager.logStackTrace("Runtime downloaded failed to run!", e2);
updateDownloadButtons();
return false;
}
@ -432,12 +432,12 @@ public class ToolsViewModel implements IToolsViewModel, SettingsListener, Accoun
Utils.delete(unpackedFile);
downloadRuntimePost(runtimeFolder.getAbsolutePath());
LOG.info("Runtime downloaded!");
LogManager.info("Runtime downloaded!");
updateDownloadButtons();
return true;
}
LOG.error("Runtime downloaded failed to run!");
LogManager.error("Runtime downloaded failed to run!");
updateDownloadButtons();
return false;
}

View file

@ -1,113 +0,0 @@
/*
* ATLauncher - https://github.com/ATLauncher/ATLauncher
* Copyright (C) 2013-2022 ATLauncher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.atlauncher.logging;
import java.awt.Color;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Optional;
import javax.swing.UIManager;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Core;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import com.atlauncher.App;
import com.atlauncher.FileSystem;
import com.atlauncher.gui.components.Console;
import com.atlauncher.utils.Timestamper;
@Plugin(name = LauncherConsoleAppender.PLUGIN_NAME, category = LauncherConsoleAppender.PLUGIN_CATEGORY, elementType = Appender.ELEMENT_TYPE, printObject = true)
public final class LauncherConsoleAppender extends AbstractAppender {
public static final String PLUGIN_NAME = "LauncherConsole";
public static final String PLUGIN_CATEGORY = Core.CATEGORY_NAME;
public LauncherConsoleAppender(String name,
Filter filter,
Layout<? extends Serializable> layout,
boolean ignoreExceptions,
Property[] properties) {
super(name, filter, layout, ignoreExceptions, properties);
}
private Optional<Console> getConsole() {
if (App.console == null) {
return Optional.empty();
}
return Optional.ofNullable(App.console.console);
}
@Override
public synchronized void append(LogEvent e) {
this.getConsole().ifPresent((console) -> {
final Throwable t = e.getThrown();
String body = e.getMessage().getFormattedMessage();
if (!LogManager.getLogger().isDebugEnabled()) {
body = body.replace(FileSystem.BASE_DIR.toAbsolutePath().toString(),
"**USERSDIR**");
}
// write timestamp
console.setColor(getColor(e)).setBold(true).write("[" + Timestamper.now() + "] ");
console.setColor(UIManager.getColor("EditorPane.foreground"))
.setBold(false)
.write(String.format("%s\n", body));
if (t != null) {
try (CharArrayWriter writer = new CharArrayWriter()) {
t.printStackTrace(new PrintWriter(writer));
console.setColor(UIManager.getColor("EditorPane.foreground"))
.setBold(false)
.write(String.format("%s\n", writer.toString()));
}
}
});
}
private static Color getColor(final LogEvent e) {
if (e.getLevel().equals(Level.INFO)) {
return UIManager.getColor("Console.LogType.info");
} else if (e.getLevel().equals(Level.WARN)) {
return UIManager.getColor("Console.LogType.warn");
} else if (e.getLevel().equals(Level.ERROR)) {
return UIManager.getColor("Console.LogType.error");
} else if (e.getLevel().equals(Level.DEBUG)) {
return UIManager.getColor("Console.LogType.debug");
}
return UIManager.getColor("Console.LogType.default");
}
@PluginFactory
public static LauncherConsoleAppender createAppender(@PluginAttribute("name") String name) {
return new LauncherConsoleAppender(name, null, null, false, null);
}
}

View file

@ -1,56 +0,0 @@
/*
* ATLauncher - https://github.com/ATLauncher/ATLauncher
* Copyright (C) 2013-2022 ATLauncher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.atlauncher.logging;
import org.apache.logging.log4j.core.Core;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import com.atlauncher.exceptions.LocalException;
import com.atlauncher.network.Analytics;
import com.atlauncher.network.ErrorReporting;
@Plugin(name = LauncherReportingAppender.PLUGIN_NAME, category = LauncherReportingAppender.PLUGIN_CATEGORY, elementType = LauncherReportingAppender.ELEMENT_TYPE, printObject = true)
public final class LauncherReportingAppender extends AbstractAppender {
public static final String PLUGIN_NAME = "LauncherReporter";
public static final String PLUGIN_CATEGORY = Core.CATEGORY_NAME;
public LauncherReportingAppender(final String name, final Filter filter) {
super(name, filter, null, false, null);
}
@Override
public void append(LogEvent event) {
final Throwable th = event.getThrown();
if (th != null && !(th instanceof LocalException)) { // don't report LocalExceptions
Analytics.sendException(th.getMessage());
ErrorReporting.captureException(th);
}
}
@PluginFactory
public static LauncherReportingAppender createAppender(@PluginAttribute("name") final String name,
@PluginElement("Filter") final Filter filter) {
return new LauncherReportingAppender(name, filter);
}
}

View file

@ -28,8 +28,6 @@ import java.nio.file.Files;
import java.util.LinkedList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
@ -47,8 +45,6 @@ import com.google.gson.reflect.TypeToken;
@SuppressWarnings("deprecation")
public class AccountManager {
private static final Logger LOG = LogManager.getLogger(AccountManager.class);
private static final Type abstractAccountListType = new TypeToken<List<AbstractAccount>>() {
}.getType();
@ -65,10 +61,10 @@ public class AccountManager {
*/
public static void loadAccounts() {
PerformanceManager.start();
LOG.debug("Loading accounts");
LogManager.debug("Loading accounts");
if (Files.exists(FileSystem.USER_DATA)) {
LOG.info("Converting old account format to new format.");
LogManager.info("Converting old account format to new format.");
convertAccounts();
}
@ -76,7 +72,7 @@ public class AccountManager {
try (FileReader fileReader = new FileReader(FileSystem.ACCOUNTS.toFile())) {
Data.ACCOUNTS.addAll(Gsons.DEFAULT.fromJson(fileReader, abstractAccountListType));
} catch (Exception e) {
LOG.error("Exception loading accounts", e);
LogManager.logStackTrace("Exception loading accounts", e);
}
}
@ -94,7 +90,7 @@ public class AccountManager {
} else {
mojangAccount.password = Utils.decrypt(mojangAccount.encryptedPassword);
if (mojangAccount.password == null) {
LOG.error("Error reading in saved password from file!");
LogManager.error("Error reading in saved password from file!");
mojangAccount.password = "";
mojangAccount.remember = false;
}
@ -106,7 +102,7 @@ public class AccountManager {
Data.SELECTED_ACCOUNT = Data.ACCOUNTS.get(0);
}
LOG.debug("Finished loading accounts");
LogManager.debug("Finished loading accounts");
PerformanceManager.end();
}
@ -130,7 +126,7 @@ public class AccountManager {
} catch (EOFException e) {
// Don't log this, it always happens when it gets to the end of the file
} catch (IOException | ClassNotFoundException e) {
LOG.error("Exception while trying to convert accounts from file.", e);
LogManager.logStackTrace("Exception while trying to convert accounts from file.", e);
} finally {
try {
if (objIn != null) {
@ -140,7 +136,7 @@ public class AccountManager {
in.close();
}
} catch (IOException e) {
LOG.error(
LogManager.logStackTrace(
"Exception while trying to close FileInputStream/ObjectInputStream when reading in " + ""
+ "accounts.",
e);
@ -152,7 +148,7 @@ public class AccountManager {
try {
Files.delete(FileSystem.USER_DATA);
} catch (IOException e) {
LOG.error("Exception trying to remove old userdata file after conversion.", e);
LogManager.logStackTrace("Exception trying to remove old userdata file after conversion.", e);
}
}
@ -164,7 +160,7 @@ public class AccountManager {
try (FileWriter fileWriter = new FileWriter(FileSystem.ACCOUNTS.toFile())) {
Gsons.DEFAULT.toJson(accounts, abstractAccountListType, fileWriter);
} catch (JsonIOException | IOException e) {
LOG.error("error:", e);
LogManager.logStackTrace(e);
}
}
@ -172,7 +168,7 @@ public class AccountManager {
String accountType = account instanceof MicrosoftAccount ? "Microsoft" : "Mojang";
Analytics.sendEvent(accountType, "Add", "Account");
LOG.info("Added " + accountType + " Account " + account);
LogManager.info("Added " + accountType + " Account " + account);
Data.ACCOUNTS.add(account);
@ -216,11 +212,11 @@ public class AccountManager {
*/
public static void switchAccount(AbstractAccount account) {
if (account == null) {
LOG.info("Logging out of account");
LogManager.info("Logging out of account");
Data.SELECTED_ACCOUNT = null;
App.settings.lastAccount = null;
} else {
LOG.info("Changed account to " + account);
LogManager.info("Changed account to " + account);
Data.SELECTED_ACCOUNT = account;
App.settings.lastAccount = account.username;
}

View file

@ -26,9 +26,6 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.FileSystem;
@ -39,7 +36,6 @@ import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
public class ConfigManager {
private static final Logger LOG = LogManager.getLogger(ConfigManager.class);
/**
* Gets a config item. Use dot notation to get an item from the config
@ -88,7 +84,7 @@ public class ConfigManager {
}
return thirdLevel.containsKey(keyParts[2]);
} catch (Throwable t) {
LOG.error(String.format("Error checking if config value for key '%s' exists", key), t);
LogManager.logStackTrace(String.format("Error checking if config value for key '%s' exists", key), t);
return false;
}
}
@ -125,7 +121,7 @@ public class ConfigManager {
return (T) thirdLevel.get(keyParts[2]);
} catch (Throwable t) {
LOG.error(String.format("Error loading config value for key '%s'", key), t);
LogManager.logStackTrace(String.format("Error loading config value for key '%s'", key), t);
return defaultValue;
}
}
@ -135,7 +131,7 @@ public class ConfigManager {
*/
public static void loadConfig() {
PerformanceManager.start();
LOG.debug("Loading config");
LogManager.debug("Loading config");
java.lang.reflect.Type type = new TypeToken<Map<String, Object>>() {
}.getType();
@ -148,20 +144,20 @@ public class ConfigManager {
Data.CONFIG = Gsons.DEFAULT.fromJson(in, type);
in.close();
} catch (JsonIOException | JsonSyntaxException | IOException e) {
LOG.error("error: ", e);
LogManager.logStackTrace(e);
}
if (App.configOverride != null) {
try {
Data.CONFIG_OVERRIDES = Gsons.DEFAULT.fromJson(App.configOverride, type);
} catch (JsonIOException | JsonSyntaxException e) {
LOG.error("Failed to read in config overrides", e);
LogManager.logStackTrace("Failed to read in config overrides", e);
}
}
afterConfigLoaded();
LOG.debug("Finished loading config");
LogManager.debug("Finished loading config");
PerformanceManager.end();
}

View file

@ -20,9 +20,6 @@ package com.atlauncher.managers;
import java.util.Comparator;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.data.Instance;
@ -31,8 +28,6 @@ import com.atlauncher.data.curseforge.CurseForgeProject;
import com.atlauncher.utils.CurseForgeApi;
public class CurseForgeUpdateManager {
private static final Logger LOG = LogManager.getLogger(CurseForgeUpdateManager.class);
public static CurseForgeFile getLatestVersion(Instance instance) {
return Data.CURSEFORGE_INSTANCE_LATEST_VERSION.get(instance);
}
@ -43,7 +38,7 @@ public class CurseForgeUpdateManager {
}
PerformanceManager.start();
LOG.info("Checking for updates to CurseForge instances");
LogManager.info("Checking for updates to CurseForge instances");
int[] projectIdsFound = Data.INSTANCES.parallelStream()
.filter(i -> i.isCurseForgePack() && i.hasCurseForgeProjectId())

View file

@ -28,16 +28,11 @@ import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.MarkerManager;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
public final class DialogManager {
private static final Logger LOG = LogManager.getLogger(DialogManager.class);
import org.mini2Dx.gettext.GetText;
public final class DialogManager {
public static final int OPTION_TYPE = 0;
public static final int CONFIRM_TYPE = 1;
public static final int OK_TYPE = 1;
@ -194,7 +189,7 @@ public final class DialogManager {
return JOptionPane.showOptionDialog(this.getParent(), this.content, this.title, this.lookAndFeel, this.type,
this.icon, this.getOptions(), this.defaultOption);
} catch (Exception e) {
LOG.error(MarkerManager.getMarker("NoReporting"), "Couldn't show dialog", e);
LogManager.logStackTrace(e, false);
}
return -1;
@ -251,7 +246,7 @@ public final class DialogManager {
return CLOSED_OPTION;
} catch (Exception e) {
LOG.error(e);
LogManager.logStackTrace(e, false);
}
return -1;
@ -266,7 +261,7 @@ public final class DialogManager {
return (String) JOptionPane.showInputDialog(this.getParent(), this.content, this.title, this.type,
this.icon, null, defaultValue);
} catch (Exception e) {
LOG.error(MarkerManager.getMarker("NoReporting"), "Couldn't show input dialog", e);
LogManager.logStackTrace(e, false);
}
return null;

View file

@ -24,9 +24,6 @@ import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.FileSystem;
@ -39,8 +36,6 @@ import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
public class InstanceManager {
private static final Logger LOG = LogManager.getLogger(InstanceManager.class);
public static List<Instance> getInstances() {
return Data.INSTANCES;
}
@ -56,7 +51,7 @@ public class InstanceManager {
*/
public static void loadInstances() {
PerformanceManager.start();
LOG.debug("Loading instances");
LogManager.debug("Loading instances");
Data.INSTANCES.clear();
for (String folder : Optional.of(FileSystem.INSTANCES.toFile().list(Utils.getInstanceFileFilter()))
@ -69,21 +64,21 @@ public class InstanceManager {
try (FileReader fileReader = new FileReader(new File(instanceDir, "instance.json"))) {
instance = Gsons.MINECRAFT.fromJson(fileReader, Instance.class);
instance.ROOT = instanceDir.toPath();
LOG.debug("Loaded instance from " + instanceDir);
LogManager.debug("Loaded instance from " + instanceDir);
if (instance.launcher == null) {
instance = null;
throw new JsonSyntaxException("Error parsing instance.json as Instance");
}
} catch (JsonIOException | JsonSyntaxException e) {
LOG.error("Failed to load instance in the folder " + instanceDir, e);
LogManager.logStackTrace("Failed to load instance in the folder " + instanceDir, e);
continue;
}
if (instance.launcher.curseForgeManifest != null
&& instance.launcher.curseForgeManifest.projectID != null
&& instance.launcher.curseForgeManifest.fileID != null) {
LOG.error(String.format("Converting instance \"%s\" CurseForge information",
LogManager.info(String.format("Converting instance \"%s\" CurseForge information",
instance.launcher.name));
instance.launcher.curseForgeProject = CurseForgeApi
.getProjectById(instance.launcher.curseForgeManifest.projectID);
@ -96,7 +91,7 @@ public class InstanceManager {
}
if (instance.launcher.numPlays == null) {
LOG.info(String.format("Converting instance \"%s\" numPlays/lastPlayed",
LogManager.info(String.format("Converting instance \"%s\" numPlays/lastPlayed",
instance.launcher.name));
instance.launcher.numPlays = instance.numPlays;
instance.launcher.lastPlayed = instance.lastPlayed;
@ -106,15 +101,16 @@ public class InstanceManager {
if (instance.launcher.account != null
&& !AccountManager.isAccountByName(instance.launcher.account)) {
LOG.warn(String.format("No account with name of %s, so setting instance account back to default",
instance.launcher.account));
LogManager.warn(
String.format("No account with name of %s, so setting instance account back to default",
instance.launcher.account));
instance.launcher.account = null;
instance.save();
}
Data.INSTANCES.add(instance);
} catch (Exception e2) {
LOG.error("Failed to load instance in the folder " + instanceDir, e2);
LogManager.logStackTrace("Failed to load instance in the folder " + instanceDir, e2);
continue;
}
}
@ -130,7 +126,7 @@ public class InstanceManager {
}
});
LOG.debug("Finished loading instances");
LogManager.debug("Finished loading instances");
PerformanceManager.end();
}
@ -209,7 +205,7 @@ public class InstanceManager {
Instance clonedInstance = Gsons.MINECRAFT.fromJson(Gsons.MINECRAFT.toJson(instance), Instance.class);
if (clonedInstance == null) {
LOG.error("Error Occurred While Cloning Instance! Instance Object Couldn't Be Cloned!");
LogManager.error("Error Occurred While Cloning Instance! Instance Object Couldn't Be Cloned!");
} else {
clonedInstance.launcher.name = clonedName;
clonedInstance.ROOT = FileSystem.INSTANCES.resolve(clonedInstance.getSafeName());

View file

@ -0,0 +1,259 @@
/*
* ATLauncher - https://github.com/ATLauncher/ATLauncher
* Copyright (C) 2013-2022 ATLauncher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.atlauncher.managers;
import java.io.CharArrayWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.atlauncher.Gsons;
import com.atlauncher.evnt.LogEvent;
import com.atlauncher.evnt.LogEvent.LogType;
import com.atlauncher.exceptions.LocalException;
import com.atlauncher.network.Analytics;
import com.atlauncher.network.DownloadException;
import com.atlauncher.network.ErrorReporting;
import com.atlauncher.thread.LoggingThread;
import com.atlauncher.utils.SystemOutInterceptor;
public final class LogManager {
private static final BlockingQueue<LogEvent> queue = new ArrayBlockingQueue<>(128);
public static boolean showDebug = false;
private static final Pattern LOG4J_THREAD_REGEX = Pattern.compile("<log4j:Event.*?thread=\"(.*?)\".*?>");
private static final Pattern LOG4J_LEVEL_REGEX = Pattern.compile("<log4j:Event.*?level=\"(.*?)\".*?>");
private static final Pattern LOG4J_MESSAGE_REGEX = Pattern
.compile("<log4j:Message><!\\[CDATA\\[(.*?)\\]\\]></log4j:Message>");
public static void start() {
new LoggingThread(queue).start();
redirectSystemOutLogs();
}
private static void redirectSystemOutLogs() {
PrintStream origOut = System.out;
PrintStream origErr = System.err;
System.setOut(new SystemOutInterceptor(origOut, LogType.DEBUG));
System.setErr(new SystemOutInterceptor(origErr, LogType.ERROR));
}
/**
* The level of debug logs to show. 1 being lowest, 2 being meh, 3 being
* EXTREEEEEEEME and 5 being OMG WTF SO MUCH LOGS
*/
public static int debugLevel = 0;
public static void info(String message) {
queue.offer(new LogEvent(LogType.INFO, message));
}
public static void debug(String message) {
if (showDebug) {
queue.offer(new LogEvent(LogType.DEBUG, message));
}
}
public static void warn(String message) {
queue.offer(new LogEvent(LogType.WARN, message));
}
public static void error(String message) {
queue.offer(new LogEvent(LogType.ERROR, message));
}
public static void debugObject(Object object) {
debug(Gsons.DEFAULT.toJson(object));
}
public static void debug(String message, int level) {
if (debugLevel >= level) {
debug(message);
}
}
public static void minecraft(String message) {
Object[] value = prepareMessageForMinecraftLog(message);
queue.offer(new LogEvent((LogType) value[0], (String) value[1], LogEvent.CONSOLE));
}
public static void logStackTrace(Throwable t) {
logStackTrace(t, true);
}
public static void logStackTrace(Throwable t, boolean sendRemote) {
t.printStackTrace();
try (CharArrayWriter writer = new CharArrayWriter()) {
Analytics.sendException(t.getMessage());
if (!(t instanceof LocalException) && sendRemote) {
ErrorReporting.captureException(t);
}
t.printStackTrace(new PrintWriter(writer));
error(writer.toString());
}
if (t instanceof DownloadException) {
DownloadException exception = ((DownloadException) t);
try {
if (exception.download.response != null && exception.response != null
&& (exception.download.response.header("Content-Type").equalsIgnoreCase("application/json")
|| exception.download.response.header("Content-Type")
.equalsIgnoreCase("application/xml")
|| exception.download.response.header("Content-Type").startsWith("text/"))) {
debug(exception.response, 5);
}
} catch (Exception e) {
}
}
}
public static void logStackTrace(String message, Throwable t) {
logStackTrace(message, t, true);
}
public static void logStackTrace(String message, Throwable t, boolean sendRemote) {
error(message);
logStackTrace(t, sendRemote);
}
public static Object[] prepareMessageForMinecraftLog(String text) {
LogType type; // The log message type
String message; // The log message
if (text.contains("[INFO] [STDERR]")) {
message = text.substring(text.indexOf("[INFO] [STDERR]"));
type = LogType.WARN;
} else if (text.contains("[INFO]")) {
message = text.substring(text.indexOf("[INFO]"));
if (message.contains("CONFLICT")) {
type = LogType.ERROR;
} else if (message.contains("overwriting existing item")) {
type = LogType.WARN;
} else {
type = LogType.INFO;
}
} else if (text.contains("[WARNING]")) {
message = text.substring(text.indexOf("[WARNING]"));
type = LogType.WARN;
} else if (text.contains("WARNING:")) {
message = text.substring(text.indexOf("WARNING:"));
type = LogType.WARN;
} else if (text.contains("INFO:")) {
message = text.substring(text.indexOf("INFO:"));
type = LogType.INFO;
} else if (text.contains("Exception")) {
message = text;
type = LogType.ERROR;
} else if (text.contains("[SEVERE]")) {
message = text.substring(text.indexOf("[SEVERE]"));
type = LogType.ERROR;
} else if (text.contains("[Sound Library Loader/ERROR]")) {
message = text.substring(text.indexOf("[Sound Library Loader/ERROR]"));
type = LogType.ERROR;
} else if (text.contains("[Sound Library Loader/WARN]")) {
message = text.substring(text.indexOf("[Sound Library Loader/WARN]"));
type = LogType.WARN;
} else if (text.contains("[Sound Library Loader/INFO]")) {
message = text.substring(text.indexOf("[Sound Library Loader/INFO]"));
type = LogType.INFO;
} else if (text.contains("[MCO Availability Checker #1/ERROR]")) {
message = text.substring(text.indexOf("[MCO Availability Checker #1/ERROR]"));
type = LogType.ERROR;
} else if (text.contains("[MCO Availability Checker #1/WARN]")) {
message = text.substring(text.indexOf("[MCO Availability Checker #1/WARN]"));
type = LogType.WARN;
} else if (text.contains("[MCO Availability Checker #1/INFO]")) {
message = text.substring(text.indexOf("[MCO Availability Checker #1/INFO]"));
type = LogType.INFO;
} else if (text.contains("[Client thread/ERROR]")) {
message = text.substring(text.indexOf("[Client thread/ERROR]"));
type = LogType.ERROR;
} else if (text.contains("[Client thread/WARN]")) {
message = text.substring(text.indexOf("[Client thread/WARN]"));
type = LogType.WARN;
} else if (text.contains("[Client thread/INFO]")) {
message = text.substring(text.indexOf("[Client thread/INFO]"));
type = LogType.INFO;
} else if (text.contains("[Server thread/ERROR]")) {
message = text.substring(text.indexOf("[Server thread/ERROR]"));
type = LogType.ERROR;
} else if (text.contains("[Server thread/WARN]")) {
message = text.substring(text.indexOf("[Server thread/WARN]"));
type = LogType.WARN;
} else if (text.contains("[Server thread/INFO]")) {
message = text.substring(text.indexOf("[Server thread/INFO]"));
type = LogType.INFO;
} else if (text.contains("[main/ERROR]")) {
message = text.substring(text.indexOf("[main/ERROR]"));
type = LogType.ERROR;
} else if (text.contains("[main/WARN]")) {
message = text.substring(text.indexOf("[main/WARN]"));
type = LogType.WARN;
} else if (text.contains("[main/INFO]")) {
message = text.substring(text.indexOf("[main/INFO]"));
type = LogType.INFO;
} else {
message = text;
type = LogType.INFO;
}
return new Object[] { type, message };
}
public static void minecraftLog4j(String string) {
String thread = "";
String message = "";
String levelString = "";
LogType level = LogType.INFO;
Matcher threadMatcher = LOG4J_THREAD_REGEX.matcher(string);
if (threadMatcher.find()) {
thread = threadMatcher.group(1);
}
Matcher levelMatcher = LOG4J_LEVEL_REGEX.matcher(string);
if (levelMatcher.find()) {
levelString = levelMatcher.group(1);
if (levelString.equalsIgnoreCase("INFO")) {
level = LogType.INFO;
} else if (levelString.equalsIgnoreCase("ERROR") || levelString.equalsIgnoreCase("SEVERE")) {
level = LogType.ERROR;
} else if (levelString.equalsIgnoreCase("WARN")) {
level = LogType.WARN;
}
}
Matcher messageMatcher = LOG4J_MESSAGE_REGEX.matcher(string);
if (messageMatcher.find()) {
message = messageMatcher.group(1);
}
queue.offer(new LogEvent(level, String.format("[%s/%s] %s", thread, levelString, message),
LogEvent.CONSOLE));
}
}

View file

@ -27,8 +27,6 @@ import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.format.ISODateTimeFormat;
import com.atlauncher.Data;
@ -46,7 +44,6 @@ import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
public class MinecraftManager {
private static final Logger LOG = LogManager.getLogger(MinecraftManager.class);
private static boolean forceReloaded = false;
public static void loadMinecraftVersions() {
@ -58,7 +55,7 @@ public class MinecraftManager {
*/
public static void loadMinecraftVersions(boolean force) {
PerformanceManager.start();
LOG.debug("Loading Minecraft versions");
LogManager.debug("Loading Minecraft versions");
Data.MINECRAFT.clear();
@ -75,14 +72,14 @@ public class MinecraftManager {
versionManifest = download.asClassWithThrow(VersionManifest.class);
} catch (IOException e) {
LOG.error("error: ", e);
LogManager.logStackTrace(e);
if (Files.exists(manifestPath)) {
try {
versionManifest = Gsons.DEFAULT.fromJson(new FileReader(manifestPath.toFile()),
VersionManifest.class);
} catch (JsonSyntaxException | FileNotFoundException | JsonIOException e1) {
LOG.error("error: ", e1);
LogManager.logStackTrace(e1);
}
}
}
@ -95,7 +92,7 @@ public class MinecraftManager {
loadAdditiveVersions();
LOG.debug("Finished loading Minecraft versions");
LogManager.debug("Finished loading Minecraft versions");
PerformanceManager.end();
}
@ -110,7 +107,7 @@ public class MinecraftManager {
try {
additiveVersionsManifest = Gsons.DEFAULT.fromJson(new FileReader(additiveManifestPath.toFile()), type);
} catch (JsonSyntaxException | FileNotFoundException | JsonIOException e1) {
LOG.error("error: ", e1);
LogManager.logStackTrace(e1);
}
}
@ -130,7 +127,7 @@ public class MinecraftManager {
*/
public static void loadJavaRuntimes(boolean force) {
PerformanceManager.start();
LOG.debug("Loading Java runtimes");
LogManager.debug("Loading Java runtimes");
try {
Download download = Download.build().setUrl(Constants.MINECRAFT_JAVA_RUNTIME_URL);
@ -142,10 +139,10 @@ public class MinecraftManager {
Data.JAVA_RUNTIMES = download.asClassWithThrow(JavaRuntimes.class);
} catch (IOException e) {
// safe to ignore, we'll just not use it
LOG.error("error: ", e);
LogManager.logStackTrace(e);
}
LOG.debug("Finished loading Java runtimes");
LogManager.debug("Finished loading Java runtimes");
PerformanceManager.end();
}

View file

@ -20,9 +20,6 @@ package com.atlauncher.managers;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.constants.Constants;
@ -33,8 +30,6 @@ import com.atlauncher.data.modpacksch.ModpacksChPackVersion;
import okhttp3.CacheControl;
public class ModpacksChUpdateManager {
private static final Logger LOG = LogManager.getLogger(ModpacksChUpdateManager.class);
public static ModpacksChPackVersion getLatestVersion(Instance instance) {
return Data.MODPACKS_CH_INSTANCE_LATEST_VERSION.get(instance);
}
@ -45,7 +40,7 @@ public class ModpacksChUpdateManager {
}
PerformanceManager.start();
LOG.info("Checking for updates to modpacks.ch instances");
LogManager.info("Checking for updates to modpacks.ch instances");
boolean refreshInstancesPanel = Data.INSTANCES.parallelStream().filter(
i -> i.launcher.modpacksChPackManifest != null && i.launcher.modpacksChPackVersionManifest != null)

View file

@ -20,9 +20,6 @@ package com.atlauncher.managers;
import java.util.Comparator;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.data.Instance;
@ -30,8 +27,6 @@ import com.atlauncher.data.modrinth.ModrinthVersion;
import com.atlauncher.utils.ModrinthApi;
public class ModrinthModpackUpdateManager {
private static final Logger LOG = LogManager.getLogger(ModrinthModpackUpdateManager.class);
public static ModrinthVersion getLatestVersion(Instance instance) {
return Data.MODRINTH_INSTANCE_LATEST_VERSION.get(instance);
}
@ -42,7 +37,7 @@ public class ModrinthModpackUpdateManager {
}
PerformanceManager.start();
LOG.info("Checking for updates to Modrinth instances");
LogManager.info("Checking for updates to Modrinth instances");
boolean refreshInstancesPanel = Data.INSTANCES.parallelStream()
.filter(i -> i.isModrinthPack()).map(i -> {

View file

@ -25,9 +25,6 @@ import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.Data;
import com.atlauncher.FileSystem;
import com.atlauncher.Gsons;
@ -37,7 +34,6 @@ import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
public class NewsManager {
private static final Logger LOG = LogManager.getLogger(NewsManager.class);
/**
* Get the News for the Launcher
@ -53,7 +49,7 @@ public class NewsManager {
*/
public static void loadNews() {
PerformanceManager.start();
LOG.debug("Loading news");
LogManager.debug("Loading news");
Data.NEWS.clear();
try {
java.lang.reflect.Type type = new TypeToken<List<News>>() {
@ -65,9 +61,9 @@ public class NewsManager {
Data.NEWS.addAll(Gsons.DEFAULT.fromJson(in, type));
in.close();
} catch (JsonIOException | JsonSyntaxException | IOException e) {
LOG.error("error: ", e);
LogManager.logStackTrace(e);
}
LOG.debug("Finished loading news");
LogManager.debug("Finished loading news");
PerformanceManager.end();
}

View file

@ -28,9 +28,6 @@ import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.FileSystem;
@ -44,8 +41,6 @@ import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
public class PackManager {
private static final Logger LOG = LogManager.getLogger(PackManager.class);
public static List<Pack> getPacks() {
return Data.PACKS;
}
@ -55,7 +50,7 @@ public class PackManager {
*/
public static void loadPacks() {
PerformanceManager.start();
LOG.debug("Loading packs");
LogManager.debug("Loading packs");
Data.PACKS.clear();
try {
java.lang.reflect.Type type = new TypeToken<List<Pack>>() {
@ -63,9 +58,9 @@ public class PackManager {
Data.PACKS.addAll(Gsons.DEFAULT_ALT
.fromJson(new FileReader(FileSystem.JSON.resolve("packsnew.json").toFile()), type));
} catch (JsonSyntaxException | FileNotFoundException | JsonIOException e) {
LOG.error("error: ", e);
LogManager.logStackTrace(e);
}
LOG.debug("Finished loading packs");
LogManager.debug("Finished loading packs");
PerformanceManager.end();
}
@ -268,7 +263,7 @@ public class PackManager {
*/
public static void loadUsers() {
PerformanceManager.start();
LOG.debug("Loading users");
LogManager.debug("Loading users");
List<PackUsers> packUsers = new ArrayList<>();
try {
@ -277,14 +272,14 @@ public class PackManager {
packUsers.addAll(
Gsons.DEFAULT_ALT.fromJson(new FileReader(FileSystem.JSON.resolve("users.json").toFile()), type));
} catch (JsonSyntaxException | FileNotFoundException | JsonIOException e) {
LOG.error("error: ", e);
LogManager.logStackTrace(e);
}
for (PackUsers pu : packUsers) {
pu.addUsers();
}
LOG.debug("Finished loading users");
LogManager.debug("Finished loading users");
PerformanceManager.end();
}
@ -299,7 +294,7 @@ public class PackManager {
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".png") && !packImageFilenames.contains(file.getName())) {
LOG.info("Pack image no longer used, deleting file " + file.getName());
LogManager.info("Pack image no longer used, deleting file " + file.getName());
file.delete();
}
}

View file

@ -22,11 +22,7 @@ import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public final class PerformanceManager {
private static final Logger LOG = LogManager.getLogger(PerformanceManager.class);
private static final Map<String, Instant> times = new HashMap<>();
@ -35,7 +31,7 @@ public final class PerformanceManager {
}
public static void start(String name) {
if (LOG.isDebugEnabled()) {
if (LogManager.showDebug) {
times.put(name, Instant.now());
}
}
@ -45,12 +41,12 @@ public final class PerformanceManager {
}
public static void end(String name) {
if (LOG.isDebugEnabled() && times.containsKey(name)) {
if (LogManager.showDebug && times.containsKey(name)) {
long timeElapsed = Duration.between(times.get(name), Instant.now()).toMillis();
times.remove(name);
LOG.debug(name + " took " + timeElapsed + " ms", 5);
LogManager.debug(name + " took " + timeElapsed + " ms", 5);
}
}
}

View file

@ -24,9 +24,6 @@ import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.FileSystem;
@ -36,8 +33,6 @@ import com.atlauncher.utils.FileUtils;
import com.atlauncher.utils.Utils;
public class ServerManager {
private static final Logger LOG = LogManager.getLogger(ServerManager.class);
public static List<Server> getServers() {
return Data.SERVERS;
}
@ -47,7 +42,7 @@ public class ServerManager {
*/
public static void loadServers() {
PerformanceManager.start();
LOG.debug("Loading servers");
LogManager.debug("Loading servers");
Data.SERVERS.clear();
for (String folder : Optional.of(FileSystem.SERVERS.toFile().list(Utils.getServerFileFilter()))
@ -58,21 +53,21 @@ public class ServerManager {
try (FileReader fileReader = new FileReader(new File(serverDir, "server.json"))) {
server = Gsons.MINECRAFT.fromJson(fileReader, Server.class);
LOG.debug("Loaded server from " + serverDir);
LogManager.debug("Loaded server from " + serverDir);
} catch (Exception e) {
LOG.error("Failed to load server in the folder " + serverDir, e);
LogManager.logStackTrace("Failed to load server in the folder " + serverDir, e);
continue;
}
if (server == null) {
LOG.error("Failed to load server in the folder " + serverDir);
LogManager.error("Failed to load server in the folder " + serverDir);
continue;
}
Data.SERVERS.add(server);
}
LOG.debug("Finished loading servers");
LogManager.debug("Finished loading servers");
PerformanceManager.end();
}

View file

@ -19,9 +19,6 @@ package com.atlauncher.managers;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Data;
import com.atlauncher.Gsons;
@ -32,8 +29,6 @@ import com.atlauncher.network.DownloadException;
import com.atlauncher.utils.TechnicApi;
public class TechnicModpackUpdateManager {
private static final Logger LOG = LogManager.getLogger(TechnicModpackUpdateManager.class);
public static TechnicModpack getUpToDateModpack(Instance instance) {
return Data.TECHNIC_INSTANCE_LATEST_VERSION.get(instance);
}
@ -48,7 +43,7 @@ public class TechnicModpackUpdateManager {
}
PerformanceManager.start();
LOG.info("Checking for updates to Technic Modpack instances");
LogManager.info("Checking for updates to Technic Modpack instances");
boolean refreshInstancesPanel = Data.INSTANCES.parallelStream()
.filter(i -> i.isTechnicPack() && i.launcher.checkForUpdates).map(i -> {
@ -60,10 +55,10 @@ public class TechnicModpackUpdateManager {
technicModpack = TechnicApi.getModpackBySlugWithThrow(i.launcher.technicModpack.name);
} catch (DownloadException e) {
if (e.response != null) {
LOG.debug(Gsons.DEFAULT.toJson(e.response));
LogManager.debug(Gsons.DEFAULT.toJson(e.response));
if (e.statusCode == 404) {
LOG.error(String.format(
LogManager.error(String.format(
"Technic pack with name of %s no longer exists, disabling update checks.",
i.launcher.technicModpack.displayName));
i.launcher.checkForUpdates = false;
@ -71,7 +66,7 @@ public class TechnicModpackUpdateManager {
}
}
} catch (IOException e) {
LOG.error(e);
LogManager.logStackTrace(e);
}
if (technicModpack == null) {

View file

@ -19,6 +19,7 @@ package com.atlauncher.mclauncher;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
@ -29,14 +30,10 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.FileSystem;
import com.atlauncher.constants.Constants;
import com.atlauncher.data.AbstractAccount;
import com.atlauncher.data.DisableableMod;
import com.atlauncher.data.Instance;
import com.atlauncher.data.LoginResponse;
import com.atlauncher.data.MicrosoftAccount;
@ -44,6 +41,7 @@ import com.atlauncher.data.MojangAccount;
import com.atlauncher.data.minecraft.Library;
import com.atlauncher.data.minecraft.LoggingClient;
import com.atlauncher.data.minecraft.PropertyMapSerializer;
import com.atlauncher.managers.LogManager;
import com.atlauncher.mclauncher.legacy.LegacyMCLauncher;
import com.atlauncher.network.ErrorReporting;
import com.atlauncher.utils.Java;
@ -55,8 +53,6 @@ import com.mojang.authlib.properties.PropertyMap;
import com.mojang.util.UUIDTypeAdapter;
public class MCLauncher {
private static final Logger LOG = LogManager.getLogger(MCLauncher.class);
public static final List<String> IGNORED_ARGUMENTS = new ArrayList<String>() {
{
// these seem to be tracking/telemetry things
@ -93,7 +89,7 @@ public class MCLauncher {
logInstanceInformation(instance);
LOG.info("Launching Minecraft with the following arguments (user related stuff has been removed): "
LogManager.info("Launching Minecraft with the following arguments (user related stuff has been removed): "
+ censorArguments(arguments, account, props, username));
ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.directory(instance.getRootDirectory());
@ -105,37 +101,31 @@ public class MCLauncher {
private static void logInstanceInformation(Instance instance) {
try {
if (instance.launcher.loaderVersion != null) {
LOG.info(String.format("Loader: %s %s", instance.launcher.loaderVersion.type,
LogManager.info(String.format("Loader: %s %s", instance.launcher.loaderVersion.type,
instance.launcher.loaderVersion.version));
}
if (instance.ROOT.resolve("mods").toFile().listFiles().length != 0) {
LOG.info("Mods:");
LogManager.info("Mods:");
Files.walk(instance.ROOT.resolve("mods"))
.filter(file -> Files.isRegularFile(file)
&& (file.toString().endsWith(".jar") || file.toString().endsWith(".zip")))
.forEach(file -> {
String filename = file.toString().replace(instance.ROOT.resolve("mods").toString(), "");
DisableableMod mod = instance.launcher.mods.parallelStream()
.filter(m -> filename.contains(m.file)).findFirst().orElse(null);
boolean isCustomAdded = filename.lastIndexOf(File.separator) == 0
&& (mod == null || mod.userAdded);
LOG.info(" - {}{}", filename, isCustomAdded ? " (Added)" : "");
LogManager.info(
" - " + file.toString().replace(instance.ROOT.resolve("mods").toString(), ""));
});
}
if (instance.launcher.mods.stream().anyMatch(m -> m.skipped)) {
instance.launcher.mods.stream().filter(m -> m.skipped).forEach(m -> {
LOG.warn(String.format(
LogManager.warn(String.format(
"Mod %s (%s) was skipped from downloading during instance installation", m.name, m.file));
});
}
if (instance.shouldUseLegacyLaunch() && Optional.ofNullable(instance.launcher.disableLegacyLaunching)
.orElse(App.settings.disableLegacyLaunching)) {
LOG.warn(
LogManager.warn(
"Legacy launching disabled. If you have issues with Minecraft, please enable this setting again");
}
} catch (IOException ignored) {
@ -186,7 +176,7 @@ public class MCLauncher {
String javaPath = instance.getJavaPath();
if (instance.isUsingJavaRuntime()) {
LOG.debug(String.format("Using Java runtime %s (major version %d) at path %s",
LogManager.debug(String.format("Using Java runtime %s (major version %d) at path %s",
instance.javaVersion.component, instance.javaVersion.majorVersion, javaPath));
}
@ -226,7 +216,7 @@ public class MCLauncher {
for (File file : libraryFiles) {
if (!file.getName().equalsIgnoreCase("minecraft.jar")
&& !file.getName().equalsIgnoreCase("modpack.jar")) {
LOG.info("Added in custom library " + file.getName());
LogManager.info("Added in custom library " + file.getName());
cpb.append(file);
cpb.append(File.pathSeparator);
@ -249,9 +239,12 @@ public class MCLauncher {
try {
pathh = thisFile.getCanonicalPath();
pathh = URLDecoder.decode(pathh, "UTF-8");
} catch (UnsupportedEncodingException e) {
pathh = System.getProperty("java.class.path");
LogManager.logStackTrace(e);
} catch (IOException e) {
pathh = System.getProperty("java.class.path");
LOG.error("error: ", e);
LogManager.logStackTrace(e);
}
cpb.append(pathh);
}
@ -333,7 +326,7 @@ public class MCLauncher {
for (String arg : javaArguments.split(" ")) {
if (!arg.isEmpty()) {
if (arguments.toString().contains(arg)) {
LOG.error("Duplicate argument " + arg + " found and not added!");
LogManager.error("Duplicate argument " + arg + " found and not added!");
continue;
}
@ -438,7 +431,7 @@ public class MCLauncher {
String username) {
String argsString = arguments.toString();
if (!LOG.isDebugEnabled()) {
if (!LogManager.showDebug) {
if (App.settings != null) {
argsString = argsString.replace(FileSystem.BASE_DIR.toAbsolutePath().toString(), "USERSDIR");
}

View file

@ -19,13 +19,11 @@ package com.atlauncher.network;
import java.awt.Rectangle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Network;
import com.atlauncher.constants.Constants;
import com.atlauncher.evnt.listener.SettingsListener;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Java;
import com.atlauncher.utils.OS;
import com.brsanthu.googleanalytics.GoogleAnalytics;
@ -33,8 +31,6 @@ import com.brsanthu.googleanalytics.GoogleAnalyticsConfig;
import com.brsanthu.googleanalytics.request.DefaultRequest;
public final class Analytics implements SettingsListener {
private static final Logger LOG = LogManager.getLogger(Analytics.class);
private static GoogleAnalytics ga;
public static void startSession() {
@ -110,7 +106,7 @@ public final class Analytics implements SettingsListener {
ga.screenView().sessionControl("end").send();
ga.close();
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}

View file

@ -20,21 +20,18 @@ package com.atlauncher.network;
import java.io.IOException;
import java.net.HttpURLConnection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.managers.LogManager;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public final class DebugLoggingInterceptor implements Interceptor {
private static final Logger LOG = LogManager.getLogger(DebugLoggingInterceptor.class);
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
LOG.debug("Sending request {}", request.url());
LogManager.debug(String.format("Sending request %s", request.url()), 3);
String debugLogMessage = request.toString();
if (request.header("Authorization") != null) {
@ -42,8 +39,7 @@ public final class DebugLoggingInterceptor implements Interceptor {
} else if (request.header("x-api-key") != null) {
debugLogMessage = debugLogMessage.replace(request.header("x-api-key"), "REDACTED");
}
LOG.debug(debugLogMessage);
LogManager.debug(debugLogMessage, 5);
long t1 = System.nanoTime();
Response response = chain.proceed(request);
@ -51,14 +47,15 @@ public final class DebugLoggingInterceptor implements Interceptor {
if (response.cacheResponse() != null && (response.networkResponse() == null
|| response.networkResponse().code() == HttpURLConnection.HTTP_NOT_MODIFIED)) {
LOG.debug(String.format("Received cached response code %d for %s in %.1fms", response.code(),
LogManager.debug(String.format("Received cached response code %d for %s in %.1fms", response.code(),
response.request().url(), (t2 - t1) / 1e6d), 3);
} else {
LOG.debug(String.format("Received response code %d for %s in %.1fms", response.code(),
LogManager.debug(String.format("Received response code %d for %s in %.1fms", response.code(),
response.request().url(), (t2 - t1) / 1e6d), 3);
}
LOG.debug("{}", response);
LogManager.debug(response.toString(), 5);
return response;
}
}

View file

@ -28,12 +28,10 @@ import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Gsons;
import com.atlauncher.Network;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.ArchiveUtils;
import com.atlauncher.utils.FileUtils;
import com.atlauncher.utils.Hashing;
@ -51,8 +49,6 @@ import okhttp3.Response;
// TODO: fuck this file, it's shit, I hate it
public final class Download {
private static Logger LOG = LogManager.getLogger(Download.class);
public static final int MAX_ATTEMPTS = 3;
// pre request
@ -92,14 +88,9 @@ public final class Download {
}
return this.response.isSuccessful();
} catch (DownloadException exc) {
LOG.error("error fetching download from {}", this.url, exc);
if (exc.hasResponse()) {
LOG.error("response: {}", exc.getResponse());
}
} catch (IOException e) {
LOG.error("error fetching download from {}", this.url, e);
} finally {
LogManager.logStackTrace(e);
if (this.response != null) {
this.response.close();
this.response = null;
@ -115,7 +106,8 @@ public final class Download {
return this.response.body().string();
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
if (this.response != null) {
this.response.close();
this.response = null;
@ -145,7 +137,8 @@ public final class Download {
try {
return asClassWithThrow(tClass, gson);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
if (this.response != null) {
this.response.close();
this.response = null;
@ -183,7 +176,8 @@ public final class Download {
try {
return asTypeWithThrow(tClass, gson);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
if (this.response != null) {
this.response.close();
this.response = null;
@ -330,7 +324,8 @@ public final class Download {
}
return this.response.code();
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
if (this.response != null) {
this.response.close();
this.response = null;
@ -378,7 +373,7 @@ public final class Download {
try {
this.hash = this.getHashFromURL();
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
this.hash = "-";
}
}
@ -401,7 +396,7 @@ public final class Download {
}
}
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
return -1;
}
@ -425,7 +420,7 @@ public final class Download {
return false;
}
} catch (IOException e) {
LOG.error("Error getting murmur hash", e);
LogManager.error("Error getting murmur hash");
return false;
}
} else if (this.md5() && Hashing.md5(this.to).equals(Hashing.toHashCode(this.getHash()))) {
@ -457,7 +452,7 @@ public final class Download {
ReadableByteChannel rbc = Channels.newChannel(this.response.body().byteStream())) {
fc.transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (Exception e) {
LOG.error("Failed to download file {}", this.to, e);// don't send
LogManager.logStackTrace("Failed to download file " + this.to, e, false);
}
}
@ -467,7 +462,7 @@ public final class Download {
try {
return Hashing.murmur(this.to) == this.fingerprint;
} catch (IOException e) {
LOG.error("Error getting murmur hash", e);
LogManager.error("Error getting murmur hash");
return false;
}
} else if (this.md5()) {
@ -497,7 +492,8 @@ public final class Download {
try {
this.execute();
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
if (this.response != null) {
this.response.close();
this.response = null;
@ -520,13 +516,14 @@ public final class Download {
// if hash doesn't match but we're ignoring failures, then pass it if not 0 in
// size and log a warning
if (this.ignoreFailures && this.to.toFile().length() != 0) {
LOG.warn(String.format("%s (of size %d) hash didn't match, but we're ignoring failures, so continuing",
this.to.getFileName(), this.to.toFile().length()));
LogManager
.warn(String.format("%s (of size %d) hash didn't match, but we're ignoring failures, so continuing",
this.to.getFileName(), this.to.toFile().length()));
return true;
}
// if the hash doesn't match, attempt again
LOG.debug("Failed downloading " + this.url + " on attempt " + attempt);
LogManager.debug("Failed downloading " + this.url + " on attempt " + attempt);
return this.downloadRec(attempt + 1);
}
@ -627,31 +624,26 @@ public final class Download {
if (!downloaded) {
if (this.response != null && this.response.header("content-type").contains("text/html")) {
LOG.error(
LogManager.error(
"The response from this request was a HTML response. This is usually caused by an antivirus or firewall software intercepting and rewriting the response. The response is below.");
LOG.error(new String(Files.readAllBytes(this.to)));
LogManager.error(new String(Files.readAllBytes(this.to)));
}
FileUtils.copyFile(this.to, FileSystem.FAILED_DOWNLOADS);
if (fingerprint != null) {
LOG.error(
"Error downloading {} from {}. Expected fingerprint of {} (with size of {}) but got {} (with size of {}) instead. Copied to FailedDownloads folder & cancelling install!",
this.to.getFileName(),
this.url,
this.fingerprint,
this.size,
Hashing.murmur(this.to),
(Files.exists(this.to) ? Files.size(this.to) : 0));
LogManager.error("Error downloading " + this.to.getFileName() + " from " + this.url + ". Expected"
+ " fingerprint of " + fingerprint.toString() + " (with size of " + this.size + ") but got "
+ Hashing.murmur(this.to) + " (with size of "
+ (Files.exists(this.to) ? Files.size(this.to) : 0)
+ ") instead. Copied to FailedDownloads folder & cancelling install!");
} else {
LOG.error(
"Error downloading {} from {}. Expected hash of {} (with size of {}) but got {} (with size of {}) instead. Copied to FailedDownloads folder & cancelling install!",
this.to.getFileName(),
this.url,
expected,
this.size,
(this.md5() ? Hashing.md5(this.to)
: (this.sha512() ? Hashing.sha512(this.to) : Hashing.sha1(this.to))),
(Files.exists(this.to) ? Files.size(this.to) : 0));
LogManager.error("Error downloading " + this.to.getFileName() + " from " + this.url + ". Expected"
+ " hash of " + expected.toString() + " (with size of " + this.size + ") but got "
+ (this.md5() ? Hashing.md5(this.to)
: (this.sha512() ? Hashing.sha512(this.to) : Hashing.sha1(this.to)))
+ " (with size of " + (Files.exists(this.to) ? Files.size(this.to) : 0)
+ ") instead. Copied to FailedDownloads folder & cancelling install!");
}
if (this.instanceInstaller != null) {
this.instanceInstaller.cancel(true);

View file

@ -39,17 +39,4 @@ public class DownloadException extends IOException {
}
}
}
public String getResponse() {
return this.response;
}
public boolean hasResponse() {
if (this.download.response == null || this.response == null)
return false;
final String contentType = this.download.response.header("Content-Type");
return contentType.equalsIgnoreCase("application/json")
|| contentType.equalsIgnoreCase("application/xml")
|| contentType.startsWith("text/");
}
}

View file

@ -24,16 +24,12 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.FileUtils;
@SuppressWarnings("serial")
public final class DownloadPool extends LinkedList<Download> {
private static final Logger LOG = LogManager.getLogger(DownloadPool.class);
private final boolean wait;
public DownloadPool(boolean wait) {
@ -129,7 +125,7 @@ public final class DownloadPool extends LinkedList<Download> {
this.dl.copy();
}
} catch (Exception e) {
LOG.error("Error trying to download " + this.dl.to.getFileName(), e);
LogManager.logStackTrace("Error trying to download " + this.dl.to.getFileName(), e);
}
}
}

View file

@ -20,12 +20,9 @@ package com.atlauncher.network;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.MarkerManager;
import com.atlauncher.constants.Constants;
import com.atlauncher.data.minecraft.loaders.LoaderVersion;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Java;
import com.atlauncher.utils.Utils;
@ -34,8 +31,6 @@ import io.sentry.Sentry;
import io.sentry.SentryLevel;
public final class ErrorReporting {
private static final Logger LOG = LogManager.getLogger(ErrorReporting.class);
public static List<String> sentEvents = new ArrayList<>();
public static List<String> ignoredMessages = new ArrayList<>();
public static boolean sentryInitialised = false;
@ -93,7 +88,7 @@ public final class ErrorReporting {
try {
Sentry.close();
} catch (Exception e) {
LOG.error(MarkerManager.getMarker("NoReporting"), "Error disabling error reporting", e);
LogManager.logStackTrace("Error disabling error reporting", e);
}
sentryInitialised = false;

View file

@ -22,10 +22,8 @@ import java.awt.GraphicsEnvironment;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.Resources;
import com.formdev.flatlaf.FlatDarculaLaf;
import com.formdev.flatlaf.FlatDarkLaf;
@ -35,8 +33,6 @@ import com.formdev.flatlaf.FlatLightLaf;
@SuppressWarnings("serial")
public class ATLauncherLaf extends FlatLaf {
private static final Logger LOG = LogManager.getLogger(ATLauncherLaf.class);
public static ATLauncherLaf instance;
private final String defaultFontName = "OpenSans-Regular";
@ -101,7 +97,7 @@ public class ATLauncherLaf extends FlatLaf {
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(Resources.makeFont(consoleFontName));
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(Resources.makeFont(tabFontName));
} catch (Throwable t) {
LOG.error("Error registering fonts", t);
LogManager.logStackTrace("Error registering fonts", t);
}
}

View file

@ -0,0 +1,51 @@
/*
* ATLauncher - https://github.com/ATLauncher/ATLauncher
* Copyright (C) 2013-2022 ATLauncher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.atlauncher.thread;
import java.util.concurrent.BlockingQueue;
import com.atlauncher.evnt.LogEvent;
import org.apache.logging.log4j.Logger;
public final class LoggingThread extends Thread {
private final BlockingQueue<LogEvent> queue;
private static final Logger logger = org.apache.logging.log4j.LogManager.getLogger(LoggingThread.class);
public LoggingThread(BlockingQueue<LogEvent> queue) {
this.queue = queue;
this.setName("ATL-Logging-Thread");
}
@Override
public void run() {
while (true) {
LogEvent next;
try {
next = this.queue.take();
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
return;
}
if (next != null) {
next.post(logger);
}
}
}
}

View file

@ -28,16 +28,12 @@ import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.Callable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.Network;
import com.atlauncher.constants.Constants;
import com.atlauncher.managers.LogManager;
public final class PasteUpload implements Callable<String> {
private static final Logger LOG = LogManager.getLogger(PasteUpload.class);
@Override
public String call() {
String log = App.console.getLog().replace(System.getProperty("line.separator"), "\n");
@ -48,17 +44,17 @@ public final class PasteUpload implements Callable<String> {
urlParameters += "private=" + URLEncoder.encode("1", "UTF-8") + "&";
urlParameters += "text=" + URLEncoder.encode(log, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOG.error("Unsupported encoding", e);
LogManager.logStackTrace("Unsupported encoding", e);
return "Unsupported encoding";
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) new URL(Constants.PASTE_API_URL).openConnection();
} catch (MalformedURLException e) {
LOG.error("Malformed paste API URL", e);
LogManager.logStackTrace("Malformed paste API URL", e);
return "Malformed paste API URL";
} catch (IOException e) {
LOG.error("Failed to connect to paste API", e);
LogManager.logStackTrace("Failed to connect to paste API", e);
return "Failed to connect to paste API";
}
conn.setDoOutput(true);
@ -69,7 +65,7 @@ public final class PasteUpload implements Callable<String> {
conn.getOutputStream().flush();
conn.getOutputStream().close();
} catch (IOException e) {
LOG.error("Failed to send data to paste API", e);
LogManager.logStackTrace("Failed to send data to paste API", e);
return "Failed to send data to paste API";
}
@ -78,10 +74,10 @@ public final class PasteUpload implements Callable<String> {
try {
stream = conn.getInputStream();
} catch (IOException e) {
LOG.error("Failed to receive response from paste API", e);
LogManager.logStackTrace("Failed to receive response from paste API", e);
stream = conn.getErrorStream();
if (stream == null) {
LOG.error("No error message returned from paste API");
LogManager.error("No error message returned from paste API");
return "No error message returned from paste API";
}
}
@ -92,12 +88,12 @@ public final class PasteUpload implements Callable<String> {
builder.append(line);
}
} catch (IOException e) {
LOG.error("Failed to read error data", e);
LogManager.logStackTrace("Failed to read error data", e);
} finally {
try {
reader.close();
} catch (IOException e) {
LOG.error("Failed to close error reader", e);
LogManager.logStackTrace("Failed to close error reader", e);
}
}
return builder.toString();

View file

@ -31,26 +31,24 @@ import java.nio.file.attribute.BasicFileAttributes;
import javax.annotation.Nullable;
import com.atlauncher.managers.LogManager;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.zeroturnaround.zip.NameMapper;
import org.zeroturnaround.zip.ZipUtil;
public class ArchiveUtils {
private static final Logger LOG = LogManager.getLogger(ArchiveUtils.class);
public static boolean archiveContainsFile(Path archivePath, String file) {
try {
return ZipUtil.containsEntry(archivePath.toFile(), file);
} catch (Throwable t) {
// allow this to fail as we can fallback to Apache Commons library
LOG.error("Failed to check if archive contains file in {}", archivePath.toAbsolutePath());
LogManager.error("Failed to check if archive contains file in " + archivePath.toAbsolutePath());
}
boolean found = false;
@ -69,7 +67,7 @@ public class ArchiveUtils {
}
}
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return found;
@ -92,7 +90,7 @@ public class ArchiveUtils {
is = Files.newInputStream(archivePath);
}
} catch (Exception e) {
LOG.error(e);
LogManager.logStackTrace(e);
}
return is;
@ -103,7 +101,8 @@ public class ArchiveUtils {
return new String(ZipUtil.unpackEntry(createInputStream(archivePath), file));
} catch (Throwable t) {
// allow this to fail as we can fallback to Apache Commons library
LOG.debug("Failed to get contents of file in " + archivePath.toAbsolutePath() + ". Trying fallback method");
LogManager.debug(
"Failed to get contents of file in " + archivePath.toAbsolutePath() + ". Trying fallback method");
}
String contents = null;
@ -124,10 +123,10 @@ public class ArchiveUtils {
}
}
} catch (Exception e) {
LOG.error(e);
LogManager.logStackTrace(e);
}
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return contents;
@ -143,7 +142,7 @@ public class ArchiveUtils {
return true;
} catch (Throwable t) {
// allow this to fail as we can fallback to Apache Commons library
LOG.error("Failed to extract {}", archivePath.toAbsolutePath());
LogManager.error("Failed to extract " + archivePath.toAbsolutePath());
}
try (InputStream is = createInputStream(archivePath);
@ -165,8 +164,9 @@ public class ArchiveUtils {
outputPath = extractToPath.resolve(fileName);
} catch (InvalidPathException e) {
String newFilename = fileName.replaceAll("[:*\\?\"<>|]", "");
LOG.warn("Invalid path when extracting file with name of '{}'. Renaming to '{}'", fileName,
newFilename);
LogManager
.warn(String.format("InvalidPath when extracting file with name of '%s'. Renaming to '%s'",
fileName, newFilename));
outputPath = extractToPath.resolve(newFilename);
}
@ -186,7 +186,7 @@ public class ArchiveUtils {
}
}
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
return false;
}
@ -203,9 +203,8 @@ public class ArchiveUtils {
return true;
} catch (Throwable t) {
// allow this to fail as we can fallback to Apache Commons library
LOG.error("Failed to create zip {} from {}",
archivePath.toAbsolutePath(),
pathToCompress.toAbsolutePath());
LogManager.error("Failed to create zip " + archivePath.toAbsolutePath() + " from "
+ pathToCompress.toAbsolutePath());
}
// TODO, It seems that exports currently do not use dbus for dir sel,
@ -236,7 +235,7 @@ public class ArchiveUtils {
aos.closeArchiveEntry();
} catch (IOException e) {
LOG.error(String.format("Unable to add %s to zip", file), e);
LogManager.logStackTrace(String.format("Unable to add %s to zip", file), e);
}
return FileVisitResult.CONTINUE;
@ -244,13 +243,13 @@ public class ArchiveUtils {
@Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
LOG.error(String.format("Unable to add %s to zip", file), e);
LogManager.logStackTrace(String.format("Unable to add %s to zip", file), e);
return FileVisitResult.CONTINUE;
}
});
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
return false;
}

View file

@ -17,13 +17,12 @@
*/
package com.atlauncher.utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mini2Dx.gettext.GetText;
import com.atlauncher.App;
import com.atlauncher.data.LoginResponse;
import com.atlauncher.data.MojangAccount;
import com.atlauncher.managers.LogManager;
import com.mojang.authlib.Agent;
import com.mojang.authlib.UserAuthentication;
import com.mojang.authlib.exceptions.AuthenticationException;
@ -32,8 +31,6 @@ import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import com.mojang.authlib.yggdrasil.YggdrasilUserAuthentication;
public class Authentication {
private static final Logger LOG = LogManager.getLogger(Authentication.class);
public static LoginResponse checkAccount(String username, String password, String clientToken) {
YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) new YggdrasilAuthenticationService(
App.settings.proxy, clientToken).createUserAuthentication(Agent.MINECRAFT);
@ -55,7 +52,7 @@ public class Authentication {
response.setErrorMessage(e.getMessage());
}
LOG.error("Authentication failed");
LogManager.error("Authentication failed");
}
}
@ -85,7 +82,7 @@ public class Authentication {
} catch (AuthenticationUnavailableException e) {
response.setErrorMessage(e.getMessage());
response.setOffline();
LOG.error("Authentication servers unavailable");
LogManager.error("Authentication servers unavailable");
} catch (AuthenticationException e) {
if (e.getMessage() == null) {
response.setErrorMessage("No error was returned from Mojang");
@ -96,7 +93,7 @@ public class Authentication {
response.setErrorMessage(e.getMessage());
}
LOG.error("Authentication failed");
LogManager.error("Authentication failed");
}
}

View file

@ -31,18 +31,14 @@ import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.FileSystem;
import com.atlauncher.data.Instance;
import com.atlauncher.data.minecraft.JavaRuntimes;
import com.atlauncher.exceptions.CommandException;
import com.atlauncher.managers.LogManager;
public class CommandExecutor {
private static final Logger LOG = LogManager.getLogger(CommandExecutor.class);
/**
* Runs the specified {@code command} in the system command line. Substitutes
* <br/>
@ -66,7 +62,7 @@ public class CommandExecutor {
try {
command = replaceArgumentTokensForCommand(getCommandArgumentTokensForInstance(instance), command);
LOG.info("Running command: \"{}\"", command);
LogManager.info("Running command: \"" + command + "\"");
Process process;
@ -88,7 +84,7 @@ public class CommandExecutor {
throw new CommandException();
}
} catch (IOException | InterruptedException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
throw new CommandException(e);
}
}
@ -100,10 +96,10 @@ public class CommandExecutor {
String line;
while ((line = reader.readLine()) != null) {
LOG.info(line);
LogManager.info(line);
}
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
// throw new RuntimeException(e);
}
}
@ -125,9 +121,10 @@ public class CommandExecutor {
}
}
LOG.error("error: {}", message);
LogManager.error(message.toString());
} catch (Exception e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
// throw new RuntimeException(e);
}
}
@ -183,10 +180,8 @@ public class CommandExecutor {
if (Files.isDirectory(runtimeDirectory)) {
javaPath = runtimeDirectory.toAbsolutePath().toString();
LOG.debug("Using Java runtime {} (major version {}) at path {}",
instance.javaVersion.component,
instance.javaVersion.majorVersion,
javaPath);
LogManager.debug(String.format("Using Java runtime %s (major version %d) at path %s",
instance.javaVersion.component, instance.javaVersion.majorVersion, javaPath));
}
}

View file

@ -28,9 +28,6 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.Gsons;
import com.atlauncher.constants.Constants;
import com.atlauncher.data.curseforge.CurseForgeCategoryForGame;
@ -38,6 +35,7 @@ import com.atlauncher.data.curseforge.CurseForgeCoreApiResponse;
import com.atlauncher.data.curseforge.CurseForgeFile;
import com.atlauncher.data.curseforge.CurseForgeFingerprint;
import com.atlauncher.data.curseforge.CurseForgeProject;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import com.google.gson.reflect.TypeToken;
@ -49,8 +47,6 @@ import okhttp3.RequestBody;
* Various utility methods for interacting with the CurseForge API.
*/
public class CurseForgeApi {
private static final Logger LOG = LogManager.getLogger(CurseForgeApi.class);
public static List<CurseForgeProject> searchCurseForge(int sectionId, String query, int page, int modLoaderType,
String sort) {
return searchCurseForge(null, sectionId, query, page, modLoaderType, sort);
@ -97,7 +93,7 @@ public class CurseForgeApi {
return response.data;
}
} catch (UnsupportedEncodingException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return null;
@ -229,7 +225,7 @@ public class CurseForgeApi {
.collect(Collectors.toMap(p -> p.id, p -> p, (existing, replacement) -> existing));
}
} catch (Throwable t) {
LOG.error("Error trying to get CurseForge projects as map", t);
LogManager.logStackTrace("Error trying to get CurseForge projects as map", t);
}
return null;

View file

@ -24,27 +24,23 @@ import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.managers.LogManager;
import com.atlauncher.utils.walker.DeleteDirVisitor;
public class FileUtils {
private static final Logger LOG = LogManager.getLogger(FileUtils.class);
public static boolean delete(Path path) {
return delete(path, false);
}
public static boolean delete(Path path, boolean recycle) {
if (!Files.exists(path)) {
LOG.error("Couldn't delete {} as it doesn't exist!", path);
LogManager.error("Couldn't delete " + path + " as it doesn't exist!");
return false;
}
if (Files.isSymbolicLink(path)) {
LOG.error("Not deleting {} as it's a symlink!", path);
LogManager.error("Not deleting " + path + " as it's a symlink!");
return false;
}
@ -59,7 +55,7 @@ public class FileUtils {
try {
Files.delete(path);
} catch (IOException e) {
LOG.error("Path {} couldn't be deleted:", path, e);// don't send
LogManager.logStackTrace("Path " + path + " couldn't be deleted!", e, false);
return false;
}
@ -68,7 +64,7 @@ public class FileUtils {
private static boolean recycle(Path path) {
if (!Files.exists(path)) {
LOG.error("Cannot recycle " + path + " as it doesn't exist.");
LogManager.error("Cannot recycle " + path + " as it doesn't exist.");
return false;
}
@ -87,14 +83,14 @@ public class FileUtils {
public static boolean deleteDirectory(Path dir) {
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
LOG.error("Cannot delete directory {} as it doesn't exist or isn't a directory!", dir);
LogManager.error("Cannot delete directory " + dir + " as it doesn't exist or isn't a directory!");
return false;
}
try {
Files.walkFileTree(dir, new DeleteDirVisitor());
} catch (IOException e) {
LOG.error("Error trying to delete the directory {}", dir, e);// don't send
LogManager.logStackTrace("Error trying to delete the directory " + dir, e, false);
return false;
}
@ -122,7 +118,7 @@ public class FileUtils {
Files.createDirectory(directory);
return true;
} catch (IOException e) {
LOG.error("Error creating directory {}", directory, e);// don't send
LogManager.logStackTrace("Error creating directory " + directory, e, false);
}
return false;
@ -133,14 +129,14 @@ public class FileUtils {
}
public static boolean copyFile(Path from, Path to, boolean withFilename) {
LOG.debug("Copying file from {} to {}", from, to);
LogManager.debug("Copying file from " + from + " to " + to);
if (!Files.isRegularFile(from)) {
LOG.error("File {} cannot be copied to {} as it isn't a file!", from, to);
LogManager.error("File " + from + " cannot be copied to " + to + " as it isn't a file!");
return false;
}
if (!Files.exists(from)) {
LOG.error("File {} cannot be copied to {} as it doesn't exist!", from, to);
LogManager.error("File " + from + " cannot be copied to " + to + " as it doesn't exist!");
return false;
}
@ -160,14 +156,14 @@ public class FileUtils {
return from.toFile().renameTo(to.toFile());
}
} catch (IOException e) {
LOG.error("Failed to copy file " + from + " to " + to, e);
LogManager.logStackTrace("Failed to copy file " + from + " to " + to, e);
return false;
}
try {
Files.copy(from, to, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOG.error("Failed to copy file " + from + " to " + to, e);
LogManager.logStackTrace("Failed to copy file " + from + " to " + to, e);
return false;
}
@ -187,11 +183,11 @@ public class FileUtils {
FileUtils.delete(from);
}
} catch (IOException e) {
LOG.error("Couldn't delete file " + from + " while renaming to " + to, e);
LogManager.logStackTrace("Couldn't delete file " + from + " while renaming to " + to, e);
}
return true;
} else {
LOG.error("Couldn't move file {} to {}", from, to);
LogManager.error("Couldn't move file " + from + " to " + to);
return false;
}
}

View file

@ -22,16 +22,16 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import com.atlauncher.managers.LogManager;
import com.google.common.hash.HashCode;
import com.sangupta.murmur.Murmur2;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.hash.HashCode;
import com.sangupta.murmur.Murmur2;
public final class Hashing {
private static final Logger LOG = LogManager.getLogger(Hashing.class);
public static final HashCode EMPTY_HASH_CODE = HashCode.fromBytes(new byte[1]);
public static HashCode md5(String str) {
@ -50,7 +50,7 @@ public final class Hashing {
try {
return com.google.common.io.Files.asByteSource(file.toFile()).hash(com.google.common.hash.Hashing.md5());
} catch (IOException e) {
LOG.error("Error hashing (MD5) file " + file.toAbsolutePath().toString(), e);
LogManager.logStackTrace("Error hashing (MD5) file " + file.toAbsolutePath().toString(), e);
return EMPTY_HASH_CODE;
}
}
@ -63,7 +63,7 @@ public final class Hashing {
try {
return com.google.common.io.Files.asByteSource(file.toFile()).hash(com.google.common.hash.Hashing.sha1());
} catch (IOException e) {
LOG.error("Error hashing (SHA1) file " + file.toAbsolutePath().toString(), e);
LogManager.logStackTrace("Error hashing (SHA1) file " + file.toAbsolutePath().toString(), e);
return EMPTY_HASH_CODE;
}
}
@ -76,7 +76,7 @@ public final class Hashing {
try {
return com.google.common.io.Files.asByteSource(file.toFile()).hash(com.google.common.hash.Hashing.sha512());
} catch (IOException e) {
LOG.error("Error hashing (SHA512) file " + file.toAbsolutePath().toString(), e);
LogManager.logStackTrace("Error hashing (SHA512) file " + file.toAbsolutePath().toString(), e);
return EMPTY_HASH_CODE;
}
}

View file

@ -28,9 +28,6 @@ import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Gsons;
import com.atlauncher.data.curseforge.CurseForgeFile;
@ -43,11 +40,10 @@ import com.atlauncher.data.modrinth.pack.ModrinthModpackManifest;
import com.atlauncher.data.multimc.MultiMCInstanceConfig;
import com.atlauncher.data.multimc.MultiMCManifest;
import com.atlauncher.gui.dialogs.InstanceInstallerDialog;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
public class ImportPackUtils {
private static final Logger LOG = LogManager.getLogger(ImportPackUtils.class);
public static boolean loadFromUrl(String url) {
if (url.startsWith("https://www.curseforge.com/minecraft/modpacks")) {
return loadFromCurseForgeUrl(url);
@ -64,14 +60,14 @@ public class ImportPackUtils {
return loadFromFile(saveTo.toFile());
} catch (IOException e) {
LOG.error("Failed to download modpack file");
LogManager.error("Failed to download modpack file");
return false;
}
}
public static boolean loadFromCurseForgeUrl(String url) {
if (!url.startsWith("https://www.curseforge.com/minecraft/modpacks")) {
LOG.error("Cannot install as the url was not a CurseForge modpack url");
LogManager.error("Cannot install as the url was not a CurseForge modpack url");
return false;
}
@ -80,7 +76,7 @@ public class ImportPackUtils {
Matcher matcher = pattern.matcher(url);
if (!matcher.find() || matcher.groupCount() < 2) {
LOG.error("Cannot install as the url was not a valid CurseForge modpack url");
LogManager.error("Cannot install as the url was not a valid CurseForge modpack url");
return false;
}
@ -88,23 +84,25 @@ public class ImportPackUtils {
Integer projectId = null;
Integer fileId = null;
LOG.debug("{}", matcher.groupCount());
LogManager.debug(matcher.groupCount() + "");
if (matcher.groupCount() == 2 && matcher.group(2) != null) {
fileId = Integer.parseInt(matcher.group(2));
}
LOG.debug("Found pack with slug " + packSlug + " and file id of " + fileId);
LogManager.debug("Found pack with slug " + packSlug + " and file id of " + fileId);
CurseForgeProject project = CurseForgeApi.getModPackBySlug(packSlug);
projectId = project.id;
fileId = project.mainFileId;
if (projectId == null || fileId == null) {
LOG.error("Cannot install as the id's couldn't be found. Try using a specific files install link instead.");
LogManager.error(
"Cannot install as the id's couldn't be found. Try using a specific files install link instead.");
return false;
}
LOG.debug("Resolved to project id {} and file id of {}", projectId, fileId);
LogManager.debug("Resolved to project id " + projectId + " and file id of " + fileId);
CurseForgeFile curseFile = CurseForgeApi.getFileForProject(projectId, fileId);
Path tempZip = FileSystem.TEMP.resolve(curseFile.fileName);
@ -128,7 +126,7 @@ public class ImportPackUtils {
download.downloadFile();
} catch (IOException e) {
LOG.error("Failed to download modpack file from CurseForge");
LogManager.error("Failed to download modpack file from CurseForge");
return false;
}
@ -137,7 +135,7 @@ public class ImportPackUtils {
public static boolean loadFromModrinthUrl(String url) {
if (!url.startsWith("https://modrinth.com/modpack")) {
LOG.error("Cannot install as the url was not a Modrinth modpack url");
LogManager.error("Cannot install as the url was not a Modrinth modpack url");
return false;
}
@ -146,25 +144,25 @@ public class ImportPackUtils {
Matcher matcher = pattern.matcher(url);
if (!matcher.find() || matcher.groupCount() < 1) {
LOG.error("Cannot install as the url was not a valid Modrinth modpack url");
LogManager.error("Cannot install as the url was not a valid Modrinth modpack url");
return false;
}
String packSlug = matcher.group(1);
LOG.debug("Found pack with slug " + packSlug);
LogManager.debug("Found pack with slug " + packSlug);
try {
ModrinthProject modrinthProject = ModrinthApi.getProject(packSlug);
if (modrinthProject == null) {
LOG.info("Failed to get pack from Modrinth");
LogManager.info("Failed to get pack from Modrinth");
return false;
}
new InstanceInstallerDialog(modrinthProject);
} catch (Exception e) {
LOG.error("Failed to install Modrinth pack from URL", e);
LogManager.logStackTrace("Failed to install Modrinth pack from URL", e);
return false;
}
@ -196,9 +194,9 @@ public class ImportPackUtils {
FileUtils.deleteDirectory(tmpDir);
LOG.error("Unknown format for importing");
LogManager.error("Unknown format for importing");
} catch (Throwable t) {
LOG.error("Error in zip file for import", t);
LogManager.logStackTrace("Error in zip file for import", t);
}
return false;
@ -206,7 +204,7 @@ public class ImportPackUtils {
public static boolean loadCurseForgeFormat(File file, Integer projectId, Integer fileId) {
if (!file.getName().endsWith(".zip")) {
LOG.error("Cannot install as the file was not a zip file");
LogManager.error("Cannot install as the file was not a zip file");
return false;
}
@ -225,19 +223,19 @@ public class ImportPackUtils {
}
if (!manifest.manifestType.equals("minecraftModpack")) {
LOG.error("Cannot install as the manifest is not a Minecraft Modpack");
LogManager.error("Cannot install as the manifest is not a Minecraft Modpack");
return false;
}
if (manifest.manifestVersion != 1) {
LOG.warn("Manifest is version {} which may be an issue!", manifest.manifestVersion);
LogManager.warn("Manifest is version " + manifest.manifestVersion + " which may be an issue!");
}
ArchiveUtils.extract(file.toPath(), tmpDir);
new InstanceInstallerDialog(manifest, tmpDir);
} catch (Exception e) {
LOG.error("Failed to install CurseForge pack", e);
LogManager.logStackTrace("Failed to install CurseForge pack", e);
FileUtils.deleteDirectory(tmpDir);
return false;
}
@ -247,7 +245,7 @@ public class ImportPackUtils {
public static boolean loadModrinthFormat(File file) {
if (!file.getName().endsWith(".mrpack")) {
LOG.error("Cannot install as the file was not a mrpack file");
LogManager.error("Cannot install as the file was not a mrpack file");
return false;
}
@ -262,7 +260,7 @@ public class ImportPackUtils {
return true;
}
} catch (Exception e) {
LOG.error("Failed to install Modrinth pack", e);
LogManager.logStackTrace("Failed to install Modrinth pack", e);
return false;
}
}
@ -275,24 +273,25 @@ public class ImportPackUtils {
ModrinthModpackManifest.class);
if (!manifest.game.equals("minecraft")) {
LOG.error("Cannot install as the manifest is for game {} and not for Minecraft", manifest.game);
LogManager.error(
"Cannot install as the manifest is for game " + manifest.game + " and not for Minecraft");
return false;
}
if (!manifest.dependencies.containsKey("minecraft")) {
LOG.error("Cannot install as the manifest doesn't contain a minecraft dependency");
LogManager.error("Cannot install as the manifest doesn't contain a minecraft dependency");
return false;
}
if (manifest.formatVersion != 1) {
LOG.warn("Manifest is version " + manifest.formatVersion + " which may be an issue!");
LogManager.warn("Manifest is version " + manifest.formatVersion + " which may be an issue!");
}
ArchiveUtils.extract(file.toPath(), tmpDir);
new InstanceInstallerDialog(manifest, tmpDir);
} catch (Exception e) {
LOG.error("Failed to install Modrinth pack", e);
LogManager.logStackTrace("Failed to install Modrinth pack", e);
FileUtils.deleteDirectory(tmpDir);
return false;
}
@ -310,13 +309,14 @@ public class ImportPackUtils {
manifest.config = new MultiMCInstanceConfig(props);
if (manifest.formatVersion != 1) {
LOG.error("Cannot install as the format is version {} which I cannot install", manifest.formatVersion);
LogManager.error("Cannot install as the format is version " + manifest.formatVersion
+ " which I cannot install");
return false;
}
new InstanceInstallerDialog(manifest, extractedPath);
} catch (Exception e) {
LOG.error("Failed to install MultiMC pack", e);
LogManager.logStackTrace("Failed to install MultiMC pack", e);
return false;
}

View file

@ -40,11 +40,9 @@ import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.FileSystem;
import com.atlauncher.Network;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.PerformanceManager;
import com.atlauncher.utils.javafinder.JavaFinder;
import com.atlauncher.utils.javafinder.JavaInfo;
@ -52,8 +50,6 @@ import com.atlauncher.utils.javafinder.JavaInfo;
import okhttp3.tls.Certificates;
public class Java {
private static final Logger LOG = LogManager.getLogger(Java.class);
/**
* Get the Java version that the launcher runs on.
*
@ -95,13 +91,13 @@ public class Java {
}
}
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
LOG.debug("Got version '{}' for Java at path '{}'", version, executablePath);
LogManager.debug(String.format("Got version \"%s\" for Java at path \"%s\"", version, executablePath));
if (version.equals("Unknown")) {
LOG.warn("Cannot get Java version from the output of \"{} -version\"", folder.getAbsolutePath());
LogManager.warn("Cannot get Java version from the output of \"" + folder.getAbsolutePath() + " -version\"");
}
return version;
@ -203,7 +199,7 @@ public class Java {
}
}
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
}
@ -246,7 +242,7 @@ public class Java {
}
private static void injectLetsEncryptCerts() {
LOG.info("Injecting Lets Encrypt Certificate");
LogManager.info("Injecting Lets Encrypt Certificate");
Network.addTrustedCertificate(Certificates.decodeCertificatePem("-----BEGIN CERTIFICATE-----\n"
+ "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n"
+ "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n"
@ -289,7 +285,7 @@ public class Java {
try {
return keyStore.getCertificate(alias);
} catch (Exception e) {
LOG.error("Failed to get certificate", e);
LogManager.logStackTrace("Failed to get certificate", e);
return null;
}
}));
@ -303,7 +299,7 @@ public class Java {
try {
return leKS.getCertificate(alias);
} catch (KeyStoreException e) {
LOG.error("Failed to get certificate", e);
LogManager.logStackTrace("Failed to get certificate", e);
return null;
}
}));
@ -322,14 +318,14 @@ public class Java {
SSLContext tls = SSLContext.getInstance("TLS");
tls.init(null, instance.getTrustManagers(), null);
HttpsURLConnection.setDefaultSSLSocketFactory(tls.getSocketFactory());
LOG.info("Injected new root certificates");
LogManager.info("Injected new root certificates");
} catch (Exception e) {
LOG.error("Failed to inject new root certificates. Problems might happen", e);
LogManager.logStackTrace("Failed to inject new root certificates. Problems might happen", e);
}
}
private static void injectDigiCertG2Certs() {
LOG.info("Injecting DigiCert G2 Certificate");
LogManager.info("Injecting DigiCert G2 Certificate");
Network.addTrustedCertificate(Certificates.decodeCertificatePem("-----BEGIN CERTIFICATE-----\n"
+ "MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh\n"
+ "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"

View file

@ -1,151 +0,0 @@
/*
* ATLauncher - https://github.com/ATLauncher/ATLauncher
* Copyright (C) 2013-2022 ATLauncher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.atlauncher.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public final class LoggingUtils {
private static final Pattern LOG4J_THREAD_REGEX = Pattern.compile("<log4j:Event.*?thread=\"(.*?)\".*?>");
private static final Pattern LOG4J_LEVEL_REGEX = Pattern.compile("<log4j:Event.*?level=\"(.*?)\".*?>");
private static final Pattern LOG4J_MESSAGE_REGEX = Pattern
.compile("<log4j:Message><!\\[CDATA\\[(.*?)\\]\\]></log4j:Message>");
private static final Logger MINECRAFT_LOG = LogManager.getLogger("Minecraft");
private LoggingUtils() {
}
public static void redirectSystemOutLogs() {
System.setOut(SystemOutInterceptor.asDebug(System.out));
System.setErr(SystemOutInterceptor.asError(System.err));
}
public static void minecraft(String line) {
if (line.contains("[INFO] [STDERR]")) {
MINECRAFT_LOG.warn(line.substring(line.indexOf("[INFO] [STDERR]")));
} else if (line.contains("[INFO]")) {
line = line.substring(line.indexOf("[INFO]"));
if (line.contains("CONFLICT")) {
MINECRAFT_LOG.error(line);
} else if (line.contains("overwriting existing item")) {
MINECRAFT_LOG.warn(line);
} else {
MINECRAFT_LOG.info(line);
}
} else if (line.contains("[WARNING]")) {
line = line.substring(line.indexOf("[WARNING]"));
MINECRAFT_LOG.warn(line);
} else if (line.contains("WARNING:")) {
line = line.substring(line.indexOf("WARNING:"));
MINECRAFT_LOG.warn(line);
} else if (line.contains("INFO:")) {
line = line.substring(line.indexOf("INFO:"));
MINECRAFT_LOG.info(line);
} else if (line.contains("Exception")) {
line = line;
MINECRAFT_LOG.error(line);
} else if (line.contains("[SEVERE]")) {
line = line.substring(line.indexOf("[SEVERE]"));
MINECRAFT_LOG.error(line);
} else if (line.contains("[Sound Library Loader/ERROR]")) {
line = line.substring(line.indexOf("[Sound Library Loader/ERROR]"));
MINECRAFT_LOG.error(line);
} else if (line.contains("[Sound Library Loader/WARN]")) {
line = line.substring(line.indexOf("[Sound Library Loader/WARN]"));
MINECRAFT_LOG.warn(line);
} else if (line.contains("[Sound Library Loader/INFO]")) {
line = line.substring(line.indexOf("[Sound Library Loader/INFO]"));
MINECRAFT_LOG.info(line);
} else if (line.contains("[MCO Availability Checker #1/ERROR]")) {
line = line.substring(line.indexOf("[MCO Availability Checker #1/ERROR]"));
MINECRAFT_LOG.error(line);
} else if (line.contains("[MCO Availability Checker #1/WARN]")) {
line = line.substring(line.indexOf("[MCO Availability Checker #1/WARN]"));
MINECRAFT_LOG.warn(line);
} else if (line.contains("[MCO Availability Checker #1/INFO]")) {
line = line.substring(line.indexOf("[MCO Availability Checker #1/INFO]"));
MINECRAFT_LOG.info(line);
} else if (line.contains("[Client thread/ERROR]")) {
line = line.substring(line.indexOf("[Client thread/ERROR]"));
MINECRAFT_LOG.error(line);
} else if (line.contains("[Client thread/WARN]")) {
line = line.substring(line.indexOf("[Client thread/WARN]"));
MINECRAFT_LOG.warn(line);
} else if (line.contains("[Client thread/INFO]")) {
line = line.substring(line.indexOf("[Client thread/INFO]"));
MINECRAFT_LOG.info(line);
} else if (line.contains("[Server thread/ERROR]")) {
line = line.substring(line.indexOf("[Server thread/ERROR]"));
MINECRAFT_LOG.error(line);
} else if (line.contains("[Server thread/WARN]")) {
line = line.substring(line.indexOf("[Server thread/WARN]"));
MINECRAFT_LOG.warn(line);
} else if (line.contains("[Server thread/INFO]")) {
line = line.substring(line.indexOf("[Server thread/INFO]"));
MINECRAFT_LOG.info(line);
} else if (line.contains("[main/ERROR]")) {
line = line.substring(line.indexOf("[main/ERROR]"));
MINECRAFT_LOG.error(line);
} else if (line.contains("[main/WARN]")) {
line = line.substring(line.indexOf("[main/WARN]"));
MINECRAFT_LOG.warn(line);
} else if (line.contains("[main/INFO]")) {
line = line.substring(line.indexOf("[main/INFO]"));
MINECRAFT_LOG.info(line);
} else {
MINECRAFT_LOG.info(line);
}
}
public static void minecraftLog4j(String string) {
String thread = "";
String message = "";
String levelString = "";
Level level = Level.INFO;
Matcher threadMatcher = LOG4J_THREAD_REGEX.matcher(string);
if (threadMatcher.find()) {
thread = threadMatcher.group(1);
}
Matcher levelMatcher = LOG4J_LEVEL_REGEX.matcher(string);
if (levelMatcher.find()) {
levelString = levelMatcher.group(1);
if (levelString.equalsIgnoreCase("INFO")) {
level = Level.INFO;
} else if (levelString.equalsIgnoreCase("ERROR") || levelString.equalsIgnoreCase("SEVERE")) {
level = Level.ERROR;
} else if (levelString.equalsIgnoreCase("WARN")) {
level = Level.WARN;
}
}
Matcher messageMatcher = LOG4J_MESSAGE_REGEX.matcher(string);
if (messageMatcher.find()) {
message = messageMatcher.group(1);
}
MINECRAFT_LOG.log(level, String.format("[%s/%s] %s", thread, levelString, message));
}
}

View file

@ -22,13 +22,11 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.constants.Constants;
import com.atlauncher.data.modpacksch.ModpacksChPackList;
import com.atlauncher.data.modpacksch.ModpacksChPackManifest;
import com.atlauncher.data.modpacksch.ModpacksChPackVersionModsManifest;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import okhttp3.CacheControl;
@ -37,8 +35,6 @@ import okhttp3.CacheControl;
* Various utility methods for interacting with the Modpacks.ch API.
*/
public class ModpacksChApi {
private static final Logger LOG = LogManager.getLogger(ModpacksChApi.class);
public static List<ModpacksChPackManifest> searchModPacks(String query, int page) {
String url = String.format("%s/modpack/search/50", Constants.MODPACKS_CH_API_URL);
@ -102,7 +98,7 @@ public class ModpacksChApi {
return modsManifest;
} catch (Exception e) {
LOG.error("Error calling mods endpoint for Modpacks.ch", e);
LogManager.logStackTrace("Error calling mods endpoint for Modpacks.ch", e);
}
return null;

View file

@ -30,9 +30,6 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.Gsons;
import com.atlauncher.constants.Constants;
import com.atlauncher.data.minecraft.loaders.LoaderVersion;
@ -41,6 +38,7 @@ import com.atlauncher.data.modrinth.ModrinthProject;
import com.atlauncher.data.modrinth.ModrinthProjectType;
import com.atlauncher.data.modrinth.ModrinthSearchResult;
import com.atlauncher.data.modrinth.ModrinthVersion;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import com.atlauncher.network.DownloadException;
import com.google.gson.reflect.TypeToken;
@ -53,8 +51,6 @@ import okhttp3.RequestBody;
* Various utility methods for interacting with the Modrinth API.
*/
public class ModrinthApi {
private static final Logger LOG = LogManager.getLogger(ModrinthApi.class);
public static ModrinthSearchResult searchModrinth(List<String> gameVersions, String query, int page, String index,
List<String> categories, ModrinthProjectType projectType) {
try {
@ -88,7 +84,7 @@ public class ModrinthApi {
return Download.build().cached(new CacheControl.Builder().maxStale(10, TimeUnit.MINUTES).build())
.setUrl(url).asClass(ModrinthSearchResult.class);
} catch (UnsupportedEncodingException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return null;
@ -216,7 +212,7 @@ public class ModrinthApi {
} catch (DownloadException e) {
// 404 is fine from this endpoint, so anything else, log it
if (e.statusCode != 404) {
LOG.error(e);
LogManager.logStackTrace(e);
}
return null;
@ -275,7 +271,7 @@ public class ModrinthApi {
return projects.stream().distinct().collect(Collectors.toMap(p -> p.id, p -> p, (existing, replacement) -> existing));
}
} catch (Throwable t) {
LOG.error("Error trying to get Modrinth projects as map", t);
LogManager.logStackTrace("Error trying to get Modrinth projects as map", t);
}
return null;

View file

@ -21,13 +21,11 @@ import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.Gsons;
import com.atlauncher.data.AbstractAccount;
import com.atlauncher.data.mojang.api.NameHistory;
import com.atlauncher.data.mojang.api.ProfileResponse;
import com.atlauncher.managers.LogManager;
import com.atlauncher.network.Download;
import com.atlauncher.network.DownloadException;
import com.google.gson.JsonObject;
@ -41,8 +39,6 @@ import okhttp3.RequestBody;
* Various utility methods for interacting with the Mojang API.
*/
public class MojangAPIUtils {
private static final Logger LOG = LogManager.getLogger(MojangAPIUtils.class);
/**
* Gets a UUID of a Minecraft account from a given username.
*
@ -71,13 +67,13 @@ public class MojangAPIUtils {
.header("Content-Type", "multipart/form-data").post(body)
.asClassWithThrow(JsonObject.class);
LOG.info(Gsons.DEFAULT.toJson(response));
LogManager.info(Gsons.DEFAULT.toJson(response));
return true;
} catch (DownloadException e) {
LOG.error("Error updating skin. Response was {}", e.response);
LogManager.error("Error updating skin. Response was " + e.response);
} catch (IOException e) {
LOG.error("Error updating skin", e);
LogManager.logStackTrace("Error updating skin", e);
}
return false;

View file

@ -46,13 +46,11 @@ import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.App;
import com.atlauncher.FileSystem;
import com.atlauncher.Update;
import com.atlauncher.constants.Constants;
import com.atlauncher.managers.LogManager;
import com.atlauncher.managers.PerformanceManager;
import com.atlauncher.network.Analytics;
import com.atlauncher.utils.javafinder.JavaInfo;
@ -67,8 +65,6 @@ import oshi.software.os.OperatingSystem.ProcessSorting;
public enum OS {
LINUX, WINDOWS, OSX;
private static final Logger LOG = LogManager.getLogger(OS.class);
private static int memory = 0;
private static SystemInfo systemInfo = null;
private static List<OSProcess> antivirusProcesses = null;
@ -152,7 +148,7 @@ public enum OS {
try {
OS.openWebBrowser(new URI(url));
} catch (Exception e) {
LOG.error("Error opening web browser!", e);
LogManager.logStackTrace("Error opening web browser!", e);
}
}
@ -163,7 +159,7 @@ public enum OS {
try {
OS.openWebBrowser(url.toURI());
} catch (URISyntaxException e) {
LOG.error("Error opening web browser!", e);
LogManager.logStackTrace("Error opening web browser!", e);
}
}
@ -178,10 +174,10 @@ public enum OS {
} else if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
} else {
LOG.error("Cannot open web browser as no supported methods were found");
LogManager.error("Cannot open web browser as no supported methods were found");
}
} catch (Exception e) {
LOG.error("Error opening web browser!", e);
LogManager.logStackTrace("Error opening web browser!", e);
}
}
@ -195,7 +191,6 @@ public enum OS {
public static void openFileExplorer(Path path, boolean toFile) {
try {
if ((toFile || !Files.isDirectory(path)) && OS.isWindows()) {
LOG.info("/select,{}", path.toAbsolutePath());
Runtime.getRuntime().exec("explorer /select," + path.toAbsolutePath());
} else {
Path pathToOpen = path;
@ -210,11 +205,11 @@ public enum OS {
|| Files.exists(Paths.get("/usr/local/bin/xdg-open")))) {
Runtime.getRuntime().exec("xdg-open " + pathToOpen.toString());
} else {
LOG.error("Cannot open file explorer as no supported methods were found");
LogManager.error("Cannot open file explorer as no supported methods were found");
}
}
} catch (Exception e) {
LOG.error("Error opening file explorer!", e);
LogManager.logStackTrace("Error opening file explorer!", e);
}
}
@ -364,7 +359,7 @@ public enum OS {
}
} catch (SecurityException | InvocationTargetException | IllegalAccessException | IllegalArgumentException
| NoSuchMethodException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
PerformanceManager.end();
return ram;
@ -385,7 +380,7 @@ public enum OS {
ram = (int) (globalMemory.getTotal() / 1048576);
} catch (Throwable t) {
LOG.error("error", t);
LogManager.logStackTrace(t);
}
PerformanceManager.end();
@ -495,7 +490,7 @@ public enum OS {
path = thisFile.getCanonicalPath();
path = URLDecoder.decode(path, "UTF-8");
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
List<String> arguments = new ArrayList<>();

View file

@ -23,14 +23,10 @@ import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.exceptions.ChunkyException;
import com.atlauncher.managers.LogManager;
public final class Resources {
private static final Logger LOG = LogManager.getLogger(Resources.class);
private static final Map<String, Object> resources = new HashMap<>();
public static final String[] FONT_FAMILIES = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
@ -66,7 +62,7 @@ public final class Resources {
} else {
URL url = Resources.class.getResource("/assets/font/" + name + ".ttf");
if (url == null) {
LOG.error("Cannot find font {}", name);
LogManager.error("Cannot find font " + name);
return new Font("Sans-Serif", Font.PLAIN, 0);
} else {
Font f = Font.createFont(Font.TRUETYPE_FONT, url.openStream());
@ -76,7 +72,7 @@ public final class Resources {
}
}
} catch (Exception ex) {
LOG.error("Cannot find font " + name, ex);
LogManager.logStackTrace("Cannot find font " + name, ex);
return new Font("Sans-Serif", Font.PLAIN, 0);
}
}

View file

@ -26,12 +26,9 @@ import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.atlauncher.managers.LogManager;
public class SkinUtils {
private static final Logger LOG = LogManager.getLogger(SkinUtils.class);
public static ImageIcon getDefaultHead() {
return getHead(Utils.getImage("/assets/image/skins/default.png"));
}
@ -55,7 +52,7 @@ public class SkinUtils {
try {
image = ImageIO.read(file);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
if (image == null) {
@ -65,7 +62,7 @@ public class SkinUtils {
try {
image = ImageIO.read(file);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return getHead(image);
@ -129,7 +126,7 @@ public class SkinUtils {
try {
image = ImageIO.read(file);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
if (image == null) {
@ -139,7 +136,7 @@ public class SkinUtils {
try {
image = ImageIO.read(file);
} catch (IOException e) {
LOG.error("error", e);
LogManager.logStackTrace(e);
}
return getSkin(image);

Some files were not shown because too many files have changed in this diff Show more