[FEATURE] Replaced String.format to formatted (#665)

This commit is contained in:
microwin7 2023-07-16 09:11:45 +03:00 committed by GitHub
parent 9d49eebffe
commit b12c43676b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 52 additions and 53 deletions

View file

@ -512,7 +512,7 @@ public void collect() {
launcherPackDir = getPath(LAUNCHERPACK_NAME);
if (keyDirectory == null) keyDirectory = getPath(KEY_NAME);
if (tmpDir == null)
tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).resolve(String.format("launchserver-%s", SecurityHelper.randomStringToken()));
tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).resolve("launchserver-%s".formatted(SecurityHelper.randomStringToken()));
}
private Path getPath(String dirName) {

View file

@ -92,7 +92,7 @@ public void visit(final String name, final Object value) {
if ("value".equals(name)) {
if (value.getClass() != String.class)
throw new IllegalArgumentException(
String.format("Invalid annotation with value class %s", field.getClass().getName()));
"Invalid annotation with value class %s".formatted(field.getClass().getName()));
valueName.set(value.toString());
}
}
@ -126,7 +126,7 @@ public void visit(final String name, final Object value) {
}
} else {
if (initMethod == null) {
throw new IllegalArgumentException(String.format("Not found init in target: %s", classNode.name));
throw new IllegalArgumentException("Not found init in target: %s".formatted(classNode.name));
}
List<FieldInsnNode> putFieldNodes = Arrays.stream(initMethod.instructions.toArray())
.filter(node -> node instanceof FieldInsnNode && node.getOpcode() == Opcodes.PUTFIELD).map(p -> (FieldInsnNode) p)
@ -173,8 +173,7 @@ private static InsnList serializeValue(Object value) {
return ((Serializer) serializerEntry.getValue()).serialize(value);
}
}
throw new UnsupportedOperationException(String.format("Serialization of type %s is not supported",
value.getClass()));
throw new UnsupportedOperationException("Serialization of type %s is not supported".formatted(value.getClass()));
}
public static boolean isSerializableValue(Object value) {

View file

@ -72,11 +72,11 @@ public final void link(LaunchServer srv) {
links.forEach((k, v) -> {
AuthProviderPair pair = srv.config.getAuthProviderPair(v);
if (pair == null) {
throw new NullPointerException(String.format("Auth %s link failed. Pair %s not found", name, v));
throw new NullPointerException("Auth %s link failed. Pair %s not found".formatted(name, v));
}
if ("core".equals(k)) {
if (pair.core == null)
throw new NullPointerException(String.format("Auth %s link failed. %s.core is null", name, v));
throw new NullPointerException("Auth %s link failed. %s.core is null".formatted(name, v));
core = pair.core;
}
});

View file

@ -170,20 +170,20 @@ public void init(LaunchServer server) {
if (table == null) logger.error("table cannot be null");
// Prepare SQL queries
String userInfoCols = makeUserCols();
queryByUUIDSQL = customQueryByUUIDSQL != null ? customQueryByUUIDSQL : String.format("SELECT %s FROM %s WHERE %s=? LIMIT 1", userInfoCols,
table, uuidColumn);
queryByUsernameSQL = customQueryByUsernameSQL != null ? customQueryByUsernameSQL : String.format("SELECT %s FROM %s WHERE %s=? LIMIT 1",
userInfoCols, table, usernameColumn);
queryByUUIDSQL = customQueryByUUIDSQL != null ? customQueryByUUIDSQL :
"SELECT %s FROM %s WHERE %s=? LIMIT 1".formatted(userInfoCols, table, uuidColumn);
queryByUsernameSQL = customQueryByUsernameSQL != null ? customQueryByUsernameSQL :
"SELECT %s FROM %s WHERE %s=? LIMIT 1".formatted(userInfoCols, table, usernameColumn);
queryByLoginSQL = customQueryByLoginSQL != null ? customQueryByLoginSQL : queryByUsernameSQL;
updateAuthSQL = customUpdateAuthSQL != null ? customUpdateAuthSQL : String.format("UPDATE %s SET %s=?, %s=NULL WHERE %s=?",
table, accessTokenColumn, serverIDColumn, uuidColumn);
updateServerIDSQL = customUpdateServerIdSQL != null ? customUpdateServerIdSQL : String.format("UPDATE %s SET %s=? WHERE %s=?",
table, serverIDColumn, uuidColumn);
updateAuthSQL = customUpdateAuthSQL != null ? customUpdateAuthSQL :
"UPDATE %s SET %s=?, %s=NULL WHERE %s=?".formatted(table, accessTokenColumn, serverIDColumn, uuidColumn);
updateServerIDSQL = customUpdateServerIdSQL != null ? customUpdateServerIdSQL :
"UPDATE %s SET %s=? WHERE %s=?".formatted(table, serverIDColumn, uuidColumn);
if (isEnabledPermissions()) {
if(isEnabledRoles()) {
queryPermissionsByUUIDSQL = customQueryPermissionsByUUIDSQL != null ? customQueryPermissionsByUUIDSQL :
@ -198,14 +198,14 @@ public void init(LaunchServer server) {
"INNER JOIN " + permissionsTable + " pr ON r." + rolesUUIDColumn + "=substring(pr." + permissionsPermissionColumn + " from 6) or r." + rolesNameColumn + "=substring(pr." + permissionsPermissionColumn + " from 6)\n" +
"WHERE pr." + permissionsUUIDColumn + " = ?";
} else {
queryPermissionsByUUIDSQL = customQueryPermissionsByUUIDSQL != null ? customQueryPermissionsByUUIDSQL : String.format("SELECT (%s) FROM %s WHERE %s=?",
permissionsPermissionColumn, permissionsTable, permissionsUUIDColumn);
queryPermissionsByUUIDSQL = customQueryPermissionsByUUIDSQL != null ? customQueryPermissionsByUUIDSQL :
"SELECT (%s) FROM %s WHERE %s=?".formatted(permissionsPermissionColumn, permissionsTable, permissionsUUIDColumn);
}
}
}
protected String makeUserCols() {
return String.format("%s, %s, %s, %s, %s", uuidColumn, usernameColumn, accessTokenColumn, serverIDColumn, passwordColumn);
return "%s, %s, %s, %s, %s".formatted(uuidColumn, usernameColumn, accessTokenColumn, serverIDColumn, passwordColumn);
}
protected void updateAuth(User user, String accessToken) throws IOException {

View file

@ -46,21 +46,21 @@ public void init(LaunchServer server) {
String userInfoCols = makeUserCols();
String hardwareInfoCols = "id, hwDiskId, baseboardSerialNumber, displayId, bitness, totalMemory, logicalProcessors, physicalProcessors, processorMaxFreq, battery, id, graphicCard, banned, publicKey";
if (sqlFindHardwareByPublicKey == null)
sqlFindHardwareByPublicKey = String.format("SELECT %s FROM %s WHERE `publicKey` = ?", hardwareInfoCols, tableHWID);
sqlFindHardwareByPublicKey = "SELECT %s FROM %s WHERE `publicKey` = ?".formatted(hardwareInfoCols, tableHWID);
if (sqlFindHardwareById == null)
sqlFindHardwareById = String.format("SELECT %s FROM %s WHERE `id` = ?", hardwareInfoCols, tableHWID);
sqlFindHardwareById = "SELECT %s FROM %s WHERE `id` = ?".formatted(hardwareInfoCols, tableHWID);
if (sqlUsersByHwidId == null)
sqlUsersByHwidId = String.format("SELECT %s FROM %s WHERE `%s` = ?", userInfoCols, table, hardwareIdColumn);
sqlUsersByHwidId = "SELECT %s FROM %s WHERE `%s` = ?".formatted(userInfoCols, table, hardwareIdColumn);
if (sqlFindHardwareByData == null)
sqlFindHardwareByData = String.format("SELECT %s FROM %s", hardwareInfoCols, tableHWID);
sqlFindHardwareByData = "SELECT %s FROM %s".formatted(hardwareInfoCols, tableHWID);
if (sqlCreateHardware == null)
sqlCreateHardware = String.format("INSERT INTO `%s` (`publickey`, `hwDiskId`, `baseboardSerialNumber`, `displayId`, `bitness`, `totalMemory`, `logicalProcessors`, `physicalProcessors`, `processorMaxFreq`, `graphicCard`, `battery`, `banned`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')", tableHWID);
sqlCreateHardware = "INSERT INTO `%s` (`publickey`, `hwDiskId`, `baseboardSerialNumber`, `displayId`, `bitness`, `totalMemory`, `logicalProcessors`, `physicalProcessors`, `processorMaxFreq`, `graphicCard`, `battery`, `banned`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0')".formatted(tableHWID);
if (sqlCreateHWIDLog == null)
sqlCreateHWIDLog = String.format("INSERT INTO %s (`hwidId`, `newPublicKey`) VALUES (?, ?)", tableHWIDLog);
sqlCreateHWIDLog = "INSERT INTO %s (`hwidId`, `newPublicKey`) VALUES (?, ?)".formatted(tableHWIDLog);
if (sqlUpdateHardwarePublicKey == null)
sqlUpdateHardwarePublicKey = String.format("UPDATE %s SET `publicKey` = ? WHERE `id` = ?", tableHWID);
sqlUpdateHardwareBanned = String.format("UPDATE %s SET `banned` = ? WHERE `id` = ?", tableHWID);
sqlUpdateUsers = String.format("UPDATE %s SET `%s` = ? WHERE `%s` = ?", table, hardwareIdColumn, uuidColumn);
sqlUpdateHardwarePublicKey = "UPDATE %s SET `publicKey` = ? WHERE `id` = ?".formatted(tableHWID);
sqlUpdateHardwareBanned = "UPDATE %s SET `banned` = ? WHERE `id` = ?".formatted(tableHWID);
sqlUpdateUsers = "UPDATE %s SET `%s` = ? WHERE `%s` = ?".formatted(table, hardwareIdColumn, uuidColumn);
}
@Override

View file

@ -44,11 +44,11 @@ public boolean canGetUpdates(String updatesDirName, Client client) {
private boolean isWhitelisted(String property, ClientProfile profile, Client client) {
if (client.permissions != null) {
String permByUUID = String.format(property, profile.getUUID());
String permByUUID = property.formatted(profile.getUUID());
if (client.permissions.hasPerm(permByUUID)) {
return true;
}
String permByTitle = String.format(property, profile.getTitle().toLowerCase(Locale.ROOT));
String permByTitle = property.formatted(profile.getTitle().toLowerCase(Locale.ROOT));
if (client.permissions.hasPerm(permByTitle)) {
return true;
}

View file

@ -98,7 +98,7 @@ public void build(Path target, boolean deleteTempFiles) throws IOException {
}
public String nextName(String taskName) {
return String.format(nameFormat, taskName, count.getAndIncrement());
return nameFormat.formatted(taskName, count.getAndIncrement());
}
public Path nextPath(String taskName) {

View file

@ -27,7 +27,7 @@ public Launch4JTask(LaunchServer launchServer) {
}
public static String formatVars(String mask) {
return String.format(mask, VERSION, BUILD);
return mask.formatted(VERSION, BUILD);
}
@Override

View file

@ -59,7 +59,7 @@ protected Downloader downloadWithProgressBar(String taskName, List<AsyncDownload
.setStyle(ProgressBarStyle.COLORFUL_UNICODE_BLOCK)
.setUnit("MB", 1024 * 1024)
.build();
bar.setExtraMessage(String.format(" [0/%d]", totalFiles));
bar.setExtraMessage(" [0/%d]".formatted(totalFiles));
Downloader downloader = Downloader.downloadList(list, baseUrl, targetDir, new Downloader.DownloadCallback() {
@Override
public void apply(long fullDiff) {
@ -69,7 +69,7 @@ public void apply(long fullDiff) {
@Override
public void onComplete(Path path) {
bar.setExtraMessage(String.format(" [%d/%d]", currentFiles.incrementAndGet(), totalFiles));
bar.setExtraMessage(" [%d/%d]".formatted(currentFiles.incrementAndGet(), totalFiles));
}
}, null, 4);
downloader.getFuture().handle((v, e) -> {

View file

@ -38,11 +38,11 @@ public SecurityCheckCommand(LaunchServer server) {
public static void printCheckResult(String module, String comment, Boolean status) {
if (status == null) {
logger.warn(String.format("[%s] %s", module, comment));
logger.warn("[%s] %s".formatted(module, comment));
} else if (status) {
logger.info(String.format("[%s] %s OK", module, comment));
logger.info("[%s] %s OK".formatted(module, comment));
} else {
logger.error(String.format("[%s] %s", module, comment));
logger.error("[%s] %s".formatted(module, comment));
}
}
@ -153,11 +153,11 @@ public void invoke(String... args) {
//Profiles
for (ClientProfile profile : server.getProfiles()) {
boolean bad = false;
String profileModuleName = String.format("profiles.%s", profile.getTitle());
String profileModuleName = "profiles.%s".formatted(profile.getTitle());
for (String exc : profile.getUpdateExclusions()) {
StringTokenizer tokenizer = new StringTokenizer(exc, "/");
if (exc.endsWith(".jar")) {
printCheckResult(profileModuleName, String.format("updateExclusions %s not safe. Cheats may be injected very easy!", exc), false);
printCheckResult(profileModuleName, "updateExclusions %s not safe. Cheats may be injected very easy!".formatted(exc), false);
bad = true;
continue;
}
@ -165,12 +165,12 @@ public void invoke(String... args) {
String nextToken = tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) {
if (!exc.endsWith("/")) {
printCheckResult(profileModuleName, String.format("updateExclusions %s not safe. Cheats may be injected very easy!", exc), false);
printCheckResult(profileModuleName, "updateExclusions %s not safe. Cheats may be injected very easy!".formatted(exc), false);
bad = true;
}
} else {
if (nextToken.equals("memory_repo") || nextToken.equals(profile.getVersion().toString())) {
printCheckResult(profileModuleName, String.format("updateExclusions %s not safe. Cheats may be injected very easy!", exc), false);
printCheckResult(profileModuleName, "updateExclusions %s not safe. Cheats may be injected very easy!".formatted(exc), false);
bad = true;
}
}

View file

@ -34,7 +34,7 @@ public void invoke(String... args) throws Exception {
verifyArgs(args, 1);
Path targetDir = Paths.get(args[0]);
if (!IOHelper.isDir(targetDir))
throw new IllegalArgumentException(String.format("%s not directory", targetDir));
throw new IllegalArgumentException("%s not directory".formatted(targetDir));
Optional<SignJarTask> task = server.launcherBinary.getTaskByClass(SignJarTask.class);
if (task.isEmpty()) throw new IllegalStateException("SignJarTask not found");
IOHelper.walk(targetDir, new SignJarVisitor(task.get()), true);

View file

@ -133,7 +133,7 @@ public Path process(Path inputFile) throws IOException {
if (component.enabled) {
Configuration proguard_cfg = new Configuration();
if (!checkJMods(IOHelper.JVM_DIR.resolve("jmods"))) {
throw new RuntimeException(String.format("Java path: %s is not JDK! Please install JDK", IOHelper.JVM_DIR));
throw new RuntimeException("Java path: %s is not JDK! Please install JDK".formatted(IOHelper.JVM_DIR));
}
Path jfxPath = tryFindOpenJFXPath(IOHelper.JVM_DIR);
if (checkFXJMods(IOHelper.JVM_DIR.resolve("jmods"))) {
@ -212,7 +212,7 @@ public String[] buildConfig(Path inputJar, Path outputJar, Path[] jfxPath) {
Collections.addAll(confStrs, JAVA9_OPTS);
if (jfxPath != null) {
for (Path path : jfxPath) {
confStrs.add(String.format("-libraryjars '%s'", path.toAbsolutePath()));
confStrs.add("-libraryjars '%s'".formatted(path.toAbsolutePath()));
}
}
srv.launcherBinary.coreLibs.stream()

View file

@ -108,7 +108,7 @@ public T getOrThrow() throws RequestException {
if (isSuccessful()) {
return result;
} else {
throw new RequestException(error == null ? String.format("statusCode %d", statusCode) : error.toString());
throw new RequestException(error == null ? "statusCode %d".formatted(statusCode) : error.toString());
}
}
}

View file

@ -41,7 +41,7 @@ public static String makeRefreshTokenFromPassword(String username, String rawPas
rawPassword = "";
}
return SecurityHelper.toHex(SecurityHelper.digest(SecurityHelper.DigestAlgorithm.SHA256,
String.format("%s.%s.%s.%s", secretSalt, username, rawPassword, secretSalt)));
"%s.%s.%s.%s".formatted(secretSalt, username, rawPassword, secretSalt)));
}
public record JwtTokenInfo(String username, UUID uuid) {

View file

@ -313,7 +313,7 @@ public boolean accept(Client client, AuthProviderPair pair, String extendedToken
client.auth = server.config.getAuthProviderPair(info.authId);
if (client.permissions == null) client.permissions = new ClientPermissions();
client.permissions.addPerm("launchserver.checkserver");
client.permissions.addPerm(String.format("launchserver.profile.%s.show", info.serverName));
client.permissions.addPerm("launchserver.profile.%s.show".formatted(info.serverName));
client.setProperty("launchserver.serverName", info.serverName);
return true;
}

View file

@ -75,7 +75,7 @@ public void downloadZip(Path path, String mask, Object... args) throws IOExcepti
if (downloadZip(mirror, path, mask, args)) return;
}
}
throw new IOException(String.format("Error download %s. All mirrors return error", path.toString()));
throw new IOException("Error download %s. All mirrors return error".formatted(path.toString()));
}
public JsonElement jsonRequest(Mirror mirror, JsonElement request, String method, String mask, Object... args) throws IOException {
@ -111,7 +111,7 @@ public static class Mirror {
private URL formatArgs(String mask, Object... args) throws MalformedURLException {
Object[] data = Arrays.stream(args).map(e -> IOHelper.urlEncode(e.toString())).toArray();
return new URL(baseUrl.concat(String.format(mask, data)));
return new URL(baseUrl.concat(mask.formatted(data)));
}
public URL getURL(String mask, Object... args) throws MalformedURLException {

View file

@ -14,7 +14,7 @@ public class ReconfigurableManager {
public void registerReconfigurable(String name, Reconfigurable reconfigurable) {
VerifyHelper.putIfAbsent(RECONFIGURABLE, name.toLowerCase(), new ReconfigurableVirtualCommand(reconfigurable.getCommands()),
String.format("Reconfigurable has been already registered: '%s'", name));
"Reconfigurable has been already registered: '%s'".formatted(name));
}
public void unregisterReconfigurable(String name) {
@ -23,15 +23,15 @@ public void unregisterReconfigurable(String name) {
public void call(String name, String action, String[] args) throws Exception {
Command commands = RECONFIGURABLE.get(name);
if (commands == null) throw new CommandException(String.format("Reconfigurable %s not found", name));
if (commands == null) throw new CommandException("Reconfigurable %s not found".formatted(name));
Command command = commands.childCommands.get(action);
if (command == null) throw new CommandException(String.format("Action %s.%s not found", name, action));
if (command == null) throw new CommandException("Action %s.%s not found".formatted(name, action));
command.invoke(args);
}
public void printHelp(String name) throws CommandException {
Command commands = RECONFIGURABLE.get(name);
if (commands == null) throw new CommandException(String.format("Reconfigurable %s not found", name));
if (commands == null) throw new CommandException("Reconfigurable %s not found".formatted(name));
HelpCommand.printSubCommandsHelp(name, commands);
}

View file

@ -29,7 +29,7 @@ public void execute(ChannelHandlerContext ctx, Client client) {
}
HashedDir dir = server.updatesManager.getUpdate(dirName);
if (dir == null) {
sendError(String.format("Directory %s not found", dirName));
sendError("Directory %s not found".formatted(dirName));
return;
}
String url = server.config.netty.downloadURL.replace("%dirname%", IOHelper.urlEncode(dirName));