diff options
Diffstat (limited to 'src/main/java/com/keuin/kbackupfabric')
23 files changed, 98 insertions, 312 deletions
diff --git a/src/main/java/com/keuin/kbackupfabric/KBCommandsRegister.java b/src/main/java/com/keuin/kbackupfabric/KBCommandsRegister.java index b502ad5..154a39f 100644 --- a/src/main/java/com/keuin/kbackupfabric/KBCommandsRegister.java +++ b/src/main/java/com/keuin/kbackupfabric/KBCommandsRegister.java @@ -85,7 +85,5 @@ public final class KBCommandsRegister { .requires(Permissions.require("kb.prev", DEFAULT_REQUIRED_LEVEL)) .executes(KBCommands::prev))); -// // register /kb setMethod for selecting backup method (zip, incremental) -// dispatcher.register(CommandManager.literal("kb").then(CommandManager.literal("setMethod").then(CommandManager.argument("backupMethod", StringArgumentType.string()).suggests(BackupMethodSuggestionProvider.getProvider()).requires(PermissionValidator::op).executes(KBCommands::setMethod)))); } } diff --git a/src/main/java/com/keuin/kbackupfabric/KBConfiguration.java b/src/main/java/com/keuin/kbackupfabric/KBConfiguration.java index 3744430..54b4348 100644 --- a/src/main/java/com/keuin/kbackupfabric/KBConfiguration.java +++ b/src/main/java/com/keuin/kbackupfabric/KBConfiguration.java @@ -6,7 +6,7 @@ package com.keuin.kbackupfabric; public class KBConfiguration { // auto backup interval in seconds. Set this to a negative value to disable auto backup. private final int autoBackupIntervalSeconds; - // name of backup created automatically. By default it is `auto-backup` + // name of backup created automatically. By default, it is `auto-backup` private final String autoBackupName; // if no player has logged in since previous backup, we skip this backup private final boolean skipAutoBackupIfNoPlayerLoggedIn; diff --git a/src/main/java/com/keuin/kbackupfabric/KBPluginEvents.java b/src/main/java/com/keuin/kbackupfabric/KBPluginEvents.java index 2b2865e..d09b9e9 100644 --- a/src/main/java/com/keuin/kbackupfabric/KBPluginEvents.java +++ b/src/main/java/com/keuin/kbackupfabric/KBPluginEvents.java @@ -60,7 +60,7 @@ public final class KBPluginEvents implements ModInitializer, ServerStartCallback // Check if we have just recovered from a previous backup. If so, print message. try { - File levelDirectory = new File(server.getRunDirectory(), ((MinecraftDedicatedServer) server).getLevelName()); + File levelDirectory = new File(server.getRunDirectory(), server.getLevelName()); File metadataFile = new File(levelDirectory, BackupMetadata.metadataFileName); if (metadataFile.exists()) { // Metadata exists. Deserialize. diff --git a/src/main/java/com/keuin/kbackupfabric/backup/BackupFilesystemUtil.java b/src/main/java/com/keuin/kbackupfabric/backup/BackupFilesystemUtil.java index eac7ce9..519951a 100644 --- a/src/main/java/com/keuin/kbackupfabric/backup/BackupFilesystemUtil.java +++ b/src/main/java/com/keuin/kbackupfabric/backup/BackupFilesystemUtil.java @@ -26,17 +26,6 @@ public final class BackupFilesystemUtil { return backupFileNamePrefix; } - -// @Deprecated -// public static String getBackupName(String backupFileName) { -// try { -// if (backupFileName.matches(backupFileNamePrefix + ".+\\.zip")) -// return backupFileName.substring(backupFileNamePrefix.length(), backupFileName.length() - 4); -// } catch (IndexOutOfBoundsException ignored) { -// } -// return backupFileName; -// } - public static boolean isBackupFileExists(String backupFileName, MinecraftServer server) { File backupFile = new File(getBackupSaveDirectory(server), backupFileName); return backupFile.isFile(); diff --git a/src/main/java/com/keuin/kbackupfabric/backup/incremental/ObjectCollectionFactory.java b/src/main/java/com/keuin/kbackupfabric/backup/incremental/ObjectCollectionFactory.java index 04ae96e..095108b 100644 --- a/src/main/java/com/keuin/kbackupfabric/backup/incremental/ObjectCollectionFactory.java +++ b/src/main/java/com/keuin/kbackupfabric/backup/incremental/ObjectCollectionFactory.java @@ -13,6 +13,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Consumer; import java.util.function.Supplier; +import java.util.stream.Stream; /** * Incremental backup is implemented as git-like file collection. @@ -45,17 +46,19 @@ public class ObjectCollectionFactory<T extends ObjectIdentifier> { throw new IllegalArgumentException("given file is not a directory"); Set<File> files = new HashSet<>(); - for (Iterator<Path> iter = Files.walk(directory.toPath(), 1).iterator(); iter.hasNext(); ) { - Path path = iter.next(); - if (Files.isSameFile(path, directory.toPath())) - continue; - File file = path.toFile(); - if (file.isDirectory()) { - subCollections.put(file.getName(), fromDirectory(file, ignoredFiles)); - } else if (!ignoredFiles.contains(file.getName())) { - files.add(file); // add to the set to be processed - } else { - PrintUtil.info(String.format("Skipping file %s.", file.getName())); + try (Stream<Path> walk = Files.walk(directory.toPath(), 1)) { + for (Iterator<Path> iter = walk.iterator(); iter.hasNext(); ) { + Path path = iter.next(); + if (Files.isSameFile(path, directory.toPath())) + continue; + File file = path.toFile(); + if (file.isDirectory()) { + subCollections.put(file.getName(), fromDirectory(file, ignoredFiles)); + } else if (!ignoredFiles.contains(file.getName())) { + files.add(file); // add to the set to be processed + } else { + PrintUtil.info(String.format("Skipping file %s.", file.getName())); + } } } @@ -125,7 +128,7 @@ public class ObjectCollectionFactory<T extends ObjectIdentifier> { public void process() { workers.clear(); for (int i = 0; i < threads; i++) { - ParallelWorker<Res> worker = new ParallelWorker<Res>(taskList, consumer, i); + ParallelWorker<Res> worker = new ParallelWorker<>(taskList, consumer, i); workers.add(worker); worker.start(); } diff --git a/src/main/java/com/keuin/kbackupfabric/backup/incremental/ObjectCollectionSerializer.java b/src/main/java/com/keuin/kbackupfabric/backup/incremental/ObjectCollectionSerializer.java index 42e7c0c..7a395d8 100644 --- a/src/main/java/com/keuin/kbackupfabric/backup/incremental/ObjectCollectionSerializer.java +++ b/src/main/java/com/keuin/kbackupfabric/backup/incremental/ObjectCollectionSerializer.java @@ -21,17 +21,6 @@ public class ObjectCollectionSerializer { @Deprecated public static ObjectCollection2 fromFile(File file) throws IOException { throw new RuntimeException("This method has been depreciated."); -// Objects.requireNonNull(file); -// ObjectCollection2 collection; -// try (FileInputStream fileInputStream = new FileInputStream(file)) { -// try (ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) { -// collection = (ObjectCollection2) objectInputStream.readObject(); -// } catch (ClassNotFoundException ignored) { -// // this should not happen -// return null; -// } -// } -// return collection; } /** diff --git a/src/main/java/com/keuin/kbackupfabric/backup/incremental/identifier/Sha256Identifier.java b/src/main/java/com/keuin/kbackupfabric/backup/incremental/identifier/Sha256Identifier.java index 50e6aa4..21111a0 100644 --- a/src/main/java/com/keuin/kbackupfabric/backup/incremental/identifier/Sha256Identifier.java +++ b/src/main/java/com/keuin/kbackupfabric/backup/incremental/identifier/Sha256Identifier.java @@ -54,27 +54,20 @@ public class Sha256Identifier extends SingleHashIdentifier { @Override protected byte[] hash(File file) throws IOException { + return sha256Hash(file); + } + + public static byte[] sha256Hash(File file) throws IOException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); try (FileInputStream inputStream = new FileInputStream(file)) { - // This does not work. I don't know why -// FileChannel channel = inputStream.getChannel(); -// ByteBuffer buffer = ByteBuffer.allocate(128); -// int readLength; -// while ((readLength = channel.read(buffer)) > 0) -// digest.update(buffer); - - // This also works, without warnings byte[] readBuffer = new byte[1024 * 1024]; + int readLength; - while ((readLength = inputStream.read(readBuffer)) > 0) + while ((readLength = inputStream.read(readBuffer)) > 0) { digest.update(readBuffer, 0, readLength); - - // The below lines also works, but the IDE will complain about the while loop -// DigestInputStream digestInputStream = new DigestInputStream(inputStream, digest); -// while(digestInputStream.read() > 0) -// ; + } return digest.digest(); } diff --git a/src/main/java/com/keuin/kbackupfabric/backup/incremental/manager/IncrementalBackupStorageManager.java b/src/main/java/com/keuin/kbackupfabric/backup/incremental/manager/IncrementalBackupStorageManager.java index b18c119..7870620 100644 --- a/src/main/java/com/keuin/kbackupfabric/backup/incremental/manager/IncrementalBackupStorageManager.java +++ b/src/main/java/com/keuin/kbackupfabric/backup/incremental/manager/IncrementalBackupStorageManager.java @@ -47,7 +47,7 @@ public class IncrementalBackupStorageManager { * Check whether the storage contains all files in the given collection. * * @param collection the collection. - * @return whether all files exists. + * @return whether all files exist. */ public boolean contains(@NotNull ObjectCollection2 collection) { Objects.requireNonNull(collection); @@ -60,7 +60,7 @@ public class IncrementalBackupStorageManager { } /** - * Add a object collection to storage base and copy files to the storage. + * Add an object collection to storage base and copy files to the storage. * * @param collection the collection. * @return objects copied to the base. diff --git a/src/main/java/com/keuin/kbackupfabric/backup/incremental/serializer/IncBackupInfoSerializer.java b/src/main/java/com/keuin/kbackupfabric/backup/incremental/serializer/IncBackupInfoSerializer.java index f17217a..c5d1115 100644 --- a/src/main/java/com/keuin/kbackupfabric/backup/incremental/serializer/IncBackupInfoSerializer.java +++ b/src/main/java/com/keuin/kbackupfabric/backup/incremental/serializer/IncBackupInfoSerializer.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.stream.Stream; public class IncBackupInfoSerializer { /** @@ -77,10 +78,12 @@ public class IncBackupInfoSerializer { throw new IllegalArgumentException("Given directory is invalid."); } List<Path> pathList = new ArrayList<>(); - Files.walk(directory.toPath(), 1).filter(p -> { - File f = p.toFile(); - return f.isFile() && f.getName().endsWith(".kbi"); - }).forEach(pathList::add); + try (Stream<Path> walk = Files.walk(directory.toPath(), 1)) { + walk.filter(p -> { + File f = p.toFile(); + return f.isFile() && f.getName().endsWith(".kbi"); + }).forEach(pathList::add); + } List<SavedIncrementalBackup> objectList = new ArrayList<>(); for (Path path : pathList) { SavedIncrementalBackup info = IncBackupInfoSerializer.fromFile(path.toFile()); diff --git a/src/main/java/com/keuin/kbackupfabric/backup/suggestion/BackupNameSuggestionProvider.java b/src/main/java/com/keuin/kbackupfabric/backup/suggestion/BackupNameSuggestionProvider.java index 9c0c1c2..fa38979 100644 --- a/src/main/java/com/keuin/kbackupfabric/backup/suggestion/BackupNameSuggestionProvider.java +++ b/src/main/java/com/keuin/kbackupfabric/backup/suggestion/BackupNameSuggestionProvider.java @@ -47,11 +47,6 @@ public class BackupNameSuggestionProvider { } } -// private static void updateCandidateList(Collection<String> stringCollection) { -// candidateList.clear(); -// candidateList.addAll(stringCollection); -// } - public static SuggestionProvider<ServerCommandSource> getProvider() { // return (context, builder) -> getCompletableFuture(builder); return (context, builder) -> { @@ -61,24 +56,6 @@ public class BackupNameSuggestionProvider { }; } -// private static CompletableFuture<Suggestions> getCompletableFuture(SuggestionsBuilder builder) { -// if (isCacheExpired()) -// updateCandidateList(); -// String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); -// synchronized (syncCache) { -// if (candidateCacheList.isEmpty()) { // If the list is empty then return no suggestions -// return Suggestions.empty(); // No suggestions -// } -// -// for (String string : candidateCacheList) { // Iterate through the supplied list -// if (string.toLowerCase(Locale.ROOT).startsWith(remaining)) { -// builder.suggest(string); // Add every single entry to suggestions list. -// } -// } -// } -// return builder.buildFuture(); // Create the CompletableFuture containing all the suggestions -// } - private static boolean isCacheExpired() { return ((int) System.currentTimeMillis()) - cacheUpdateTime > CACHE_TTL || cacheUpdateTime == 0; } diff --git a/src/main/java/com/keuin/kbackupfabric/notification/DistinctNotifiable.java b/src/main/java/com/keuin/kbackupfabric/notification/DistinctNotifiable.java index b44bfce..6d45e26 100644 --- a/src/main/java/com/keuin/kbackupfabric/notification/DistinctNotifiable.java +++ b/src/main/java/com/keuin/kbackupfabric/notification/DistinctNotifiable.java @@ -17,7 +17,7 @@ public interface DistinctNotifiable { void notify(Text text); /** - * Get an unique, non-null object that identifies this notifiable instance. + * Get a unique, non-null object that identifies this notifiable instance. * The identifier must be immutable and implement their own equals method. * * @return the identifier. diff --git a/src/main/java/com/keuin/kbackupfabric/operation/BackupOperation.java b/src/main/java/com/keuin/kbackupfabric/operation/BackupOperation.java index 1798fb7..3fec8b9 100644 --- a/src/main/java/com/keuin/kbackupfabric/operation/BackupOperation.java +++ b/src/main/java/com/keuin/kbackupfabric/operation/BackupOperation.java @@ -33,7 +33,7 @@ public class BackupOperation extends InvokableAsyncBlockingOperation { protected void async() { String backupSaveDirectory = ""; MinecraftServer server = context.getSource().getMinecraftServer(); - boolean success = false; // only success when everything is done + boolean success; // only success when everything is done try { //// Do our main backup logic diff --git a/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java b/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java index bb0c704..2dac710 100644 --- a/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java +++ b/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractAsyncOperation.java @@ -2,7 +2,7 @@ package com.keuin.kbackupfabric.operation.abstracts; /** * A basic async operation, but not invokable. - * If you want a invokable interface (InvokableOperation), use InvokableAsyncOperation instead. + * If you want an invokable interface (InvokableOperation), use InvokableAsyncOperation instead. */ public abstract class AbstractAsyncOperation extends AbstractSerialOperation { diff --git a/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractSerialOperation.java b/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractSerialOperation.java index 92dfb53..db5433f 100644 --- a/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractSerialOperation.java +++ b/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractSerialOperation.java @@ -2,7 +2,7 @@ package com.keuin.kbackupfabric.operation.abstracts; /** * The most basic operation abstraction. - * This class represents an serial operation, which is limited in a non-public method. + * This class represents a serial operation, which is limited in a non-public method. * Note that the operation is not invokable by default, you should use InvokableOperation in order to provide a public method for users to call. */ public abstract class AbstractSerialOperation { diff --git a/src/main/java/com/keuin/kbackupfabric/operation/backup/method/ConfiguredIncrementalBackupMethod.java b/src/main/java/com/keuin/kbackupfabric/operation/backup/method/ConfiguredIncrementalBackupMethod.java index 2cc0765..cfc9b81 100644 --- a/src/main/java/com/keuin/kbackupfabric/operation/backup/method/ConfiguredIncrementalBackupMethod.java +++ b/src/main/java/com/keuin/kbackupfabric/operation/backup/method/ConfiguredIncrementalBackupMethod.java @@ -99,7 +99,6 @@ public class ConfiguredIncrementalBackupMethod implements ConfiguredBackupMethod PrintUtil.info("Incremental backup finished."); feedback = new IncrementalBackupFeedback(true, copyResult); } catch (IOException e) { -// e.printStackTrace(); // stack trace has been passed to backup feedback. No need to print here. feedback = new IncrementalBackupFeedback(e); } @@ -119,7 +118,7 @@ public class ConfiguredIncrementalBackupMethod implements ConfiguredBackupMethod // remove unused object files in the base if (collection != null) { try { - // collection may have been copied (partially) to the base, but we may not need them + // collection may have been copied (partially) to the base, but we may not need them, // so we perform a clean here // perform a clean-up Iterable<ObjectCollection2> backups = ObjectCollectionSerializer.fromDirectory(new File(backupIndexFileSaveDirectory)); diff --git a/src/main/java/com/keuin/kbackupfabric/ui/BackupManager.java b/src/main/java/com/keuin/kbackupfabric/ui/BackupManager.java index d4081c6..7ee46f9 100644 --- a/src/main/java/com/keuin/kbackupfabric/ui/BackupManager.java +++ b/src/main/java/com/keuin/kbackupfabric/ui/BackupManager.java @@ -1,7 +1,5 @@ package com.keuin.kbackupfabric.ui; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.io.IOException; import java.util.Arrays; @@ -28,51 +26,47 @@ public class BackupManager { * @return all backups. */ public Iterable<BackupInfo> getAllBackups() { - return new Iterable<BackupInfo>() { - @NotNull - @Override - public Iterator<BackupInfo> iterator() { - if (backupStorageDirectory.exists()) { - if (!backupStorageDirectory.isDirectory()) { - throw new RuntimeException("Backup directory is not a directory."); - } - } else { - if (!backupStorageDirectory.mkdirs()) { - throw new RuntimeException("Backup directory does not exist and cannot be created."); - } + return () -> { + if (backupStorageDirectory.exists()) { + if (!backupStorageDirectory.isDirectory()) { + throw new RuntimeException("Backup directory is not a directory."); } - File[] backupFiles = backupStorageDirectory.listFiles(); - if (backupFiles == null) { - throw new RuntimeException("Cannot list files in backup directory."); + } else { + if (!backupStorageDirectory.mkdirs()) { + throw new RuntimeException("Backup directory does not exist and cannot be created."); } + } + File[] backupFiles = backupStorageDirectory.listFiles(); + if (backupFiles == null) { + throw new RuntimeException("Cannot list files in backup directory."); + } - return new Iterator<BackupInfo>() { - private final Iterator<File> fileIterator = Arrays.stream(backupFiles).filter(file -> { - String name = file.getName().toLowerCase(); - return name.endsWith(".zip") || name.endsWith(".kbi"); - }).iterator(); + return new Iterator<BackupInfo>() { + private final Iterator<File> fileIterator = Arrays.stream(backupFiles).filter(file -> { + String name = file.getName().toLowerCase(); + return name.endsWith(".zip") || name.endsWith(".kbi"); + }).iterator(); - @Override - public boolean hasNext() { - return fileIterator.hasNext(); - } + @Override + public boolean hasNext() { + return fileIterator.hasNext(); + } - @Override - public BackupInfo next() { - try { - File backupFile = fileIterator.next(); - String fileName = backupFile.getName().toLowerCase(); - if (fileName.endsWith(".zip")) - return PrimitiveBackupInfo.fromFile(backupFile); - if (fileName.endsWith(".kbi")) - return IncrementalBackupInfo.fromFile(backupFile); - throw new RuntimeException("Invalid backup file extname"); - } catch (IOException e) { - throw new RuntimeException(e); - } + @Override + public BackupInfo next() { + try { + File backupFile = fileIterator.next(); + String fileName = backupFile.getName().toLowerCase(); + if (fileName.endsWith(".zip")) + return PrimitiveBackupInfo.fromFile(backupFile); + if (fileName.endsWith(".kbi")) + return IncrementalBackupInfo.fromFile(backupFile); + throw new RuntimeException("Invalid backup file extname"); + } catch (IOException e) { + throw new RuntimeException(e); } - }; - } + } + }; }; } } diff --git a/src/main/java/com/keuin/kbackupfabric/ui/KBCommands.java b/src/main/java/com/keuin/kbackupfabric/ui/KBCommands.java index e148f24..d23a6fd 100644 --- a/src/main/java/com/keuin/kbackupfabric/ui/KBCommands.java +++ b/src/main/java/com/keuin/kbackupfabric/ui/KBCommands.java @@ -40,12 +40,8 @@ public final class KBCommands { private static MinecraftServer server; private static BackupManager backupManager; private static final Object managerCreatorLock = new Object(); - - //private static final Logger LOGGER = LogManager.getLogger(); - private static final List<BackupInfo> backupList = new ArrayList<>(); // index -> backupName private static Invokable pendingOperation = null; - //private static BackupMethod activatedBackupMethod = new PrimitiveBackupMethod(); // The backup method we currently using public static void setServer(MinecraftServer server) { KBCommands.server = server; @@ -124,21 +120,6 @@ public final class KBCommands { // TODO: Show concrete info from metadata for `.zip` backup // MinecraftServer server = context.getSource().getMinecraftServer(); // TODO: refactor this to use {@link ObjectCollectionSerializer#fromDirectory} -// File[] files = getBackupSaveDirectory(server).listFiles( -// (dir, name) -> dir.isDirectory() && -// (name.toLowerCase().endsWith(".zip") && name.toLowerCase().startsWith(getBackupFileNamePrefix()) -// || name.toLowerCase().endsWith(".kbi")) -// ); - -// Function<File, String> backupInformationProvider = file -> { -// Objects.requireNonNull(file); -// if (file.getName().toLowerCase().endsWith(".zip")) -// return getPrimitiveBackupInformationString(file.getName(), file.length()); -// // TODO: refactor this to use {@link ObjectCollectionSerializer#fromDirectory} -// else if (file.getName().toLowerCase().endsWith(".kbi")) -// return getIncrementalBackupInformationString(file); -// return file.getName(); -// }; updateBackupList(); synchronized (backupList) { @@ -150,22 +131,6 @@ public final class KBCommands { BackupInfo info = backupList.get(i); printBackupInfo(context, info, i); } -// if (files != null) { -// if (files.length != 0) { -// msgInfo(context, "Available backups: (file is not checked, manipulation may affect this plugin)"); -// } else { -// msgInfo(context, "There are no available backups. To make a new backup, run /kb backup."); -// } -// int i = 0; -// for (File file : files) { -// ++i; -// String backupFileName = file.getName(); -// msgInfo(context, String.format("[%d] %s", i, backupInformationProvider.apply(file))); -// backupFileNameList.add(backupFileName); -// } -// } else { -// msgErr(context, "Error: failed to list files in backup folder."); -// } } return SUCCESS; } @@ -230,21 +195,6 @@ public final class KBCommands { } -// public static int incrementalBackup(CommandContext<ServerCommandSource> context) { -// //KBMain.backup("name") -// String backupName = StringArgumentType.getString(context, "backupName"); -// if (backupName.matches("[0-9]*")) { -// // Numeric param is not allowed -// backupName = String.format("a%s", backupName); -// msgWarn(context, String.format("Pure numeric name is not allowed. Renaming to %s", backupName)); -// } -// return doBackup(context, backupName, IncrementalBackupMethod.getInstance()); -// } -// -// public static int incrementalBackupWithDefaultName(CommandContext<ServerCommandSource> context) { -// return doBackup(context, DEFAULT_BACKUP_NAME, IncrementalBackupMethod.getInstance()); -// } - /** * Delete an existing backup with context parameter backupName. * Simply set the pending backupName to given backupName, for the second confirmation. @@ -390,7 +340,7 @@ public final class KBCommands { // By the way, update suggestion list. BackupNameSuggestionProvider.updateCandidateList(); - return returnValue ? SUCCESS : FAILED; // block compiler's complain. + return returnValue ? SUCCESS : FAILED; // block compiler's complaint. } /** @@ -401,7 +351,7 @@ public final class KBCommands { */ public static int cancel(CommandContext<ServerCommandSource> context) { if (pendingOperation != null) { - PrintUtil.msgInfo(context, String.format("The %s has been cancelled.", pendingOperation.toString()), true); + PrintUtil.msgInfo(context, String.format("The %s has been cancelled.", pendingOperation), true); pendingOperation = null; return SUCCESS; } else { @@ -422,22 +372,6 @@ public final class KBCommands { try { // List all backups updateBackupList(); -// MinecraftServer server = context.getSource().getMinecraftServer(); -// List<File> files = Arrays.asList(Objects.requireNonNull(getBackupSaveDirectory(server).listFiles())); -// files.removeIf(f -> !f.getName().startsWith(BackupFilesystemUtil.getBackupFileNamePrefix())); -// files.sort((x, y) -> (int) (BackupFilesystemUtil.getBackupTimeFromBackupFileName(y.getName()) - BackupFilesystemUtil.getBackupTimeFromBackupFileName(x.getName()))); -// File prevBackupFile = files.get(0); -// String backupFileName = prevBackupFile.getName(); -// int i; -// synchronized (backupList) { -// i = backupList.indexOf(backupFileName); -// if (i == -1) { -// backupList.add(backupFileName); -// i = backupList.size(); -// } else { -// ++i; -// } -// } synchronized (backupList) { if (!backupList.isEmpty()) { BackupInfo info = backupList.get(0); @@ -454,47 +388,6 @@ public final class KBCommands { return SUCCESS; } -// private static String getPrimitiveBackupInformationString(String backupFileName, long backupFileSizeBytes) { -// return String.format( -// "(ZIP) %s , size: %s", -// PrimitiveBackupFileNameEncoder.INSTANCE.decode(backupFileName), -// getFriendlyFileSizeString(backupFileSizeBytes) -// ); -// } - -// private static String getIncrementalBackupInformationString(File backupFile) { -// try { -// SavedIncrementalBackup info = IncBackupInfoSerializer.fromFile(backupFile); -// return "(Incremental) " + info.getBackupName() -// + ", " + DateUtil.getString(info.getBackupTime()) -// + ((info.getTotalSizeBytes() > 0) ? -// (" size: " + BackupFilesystemUtil.getFriendlyFileSizeString(info.getTotalSizeBytes())) : ""); -// } catch (IOException e) { -// e.printStackTrace(); -// return "(Incremental) " + backupFile.getName(); -// } -// } - -// /** -// * Select the backup method we use. -// * @param context the context. -// * @return stat code. -// */ -// public static int setMethod(CommandContext<ServerCommandSource> context) { -// String desiredMethodName = StringArgumentType.getString(context, "backupMethod"); -// List<BackupType> backupMethods = Arrays.asList(BackupType.PRIMITIVE_ZIP_BACKUP, BackupType.OBJECT_TREE_BACKUP); -// for (BackupType method : backupMethods) { -// if(method.getName().equals(desiredMethodName)) { -// // Incremental backup -//// activatedBackupMethod = -// msgInfo(context, String.format("Backup method is set to: %s", desiredMethodName)); -// return SUCCESS; -// } -// } -// -// return SUCCESS; -// } - private static String parseBackupFileName(CommandContext<ServerCommandSource> context, String userInput) { try { diff --git a/src/main/java/com/keuin/kbackupfabric/ui/PrimitiveBackupInfo.java b/src/main/java/com/keuin/kbackupfabric/ui/PrimitiveBackupInfo.java index 1895647..e3a0060 100644 --- a/src/main/java/com/keuin/kbackupfabric/ui/PrimitiveBackupInfo.java +++ b/src/main/java/com/keuin/kbackupfabric/ui/PrimitiveBackupInfo.java @@ -38,11 +38,6 @@ public class PrimitiveBackupInfo implements BackupInfo { public static PrimitiveBackupInfo fromFile(File zipFile) { // TODO: fix this, use metadata file instead -// fileName = zipFile.getName(); -// BackupFileNameEncoder.BackupBasicInformation info = PrimitiveBackupFileNameEncoder.INSTANCE.decode(fileName); -// if (info == null) -// throw new IllegalArgumentException("Invalid file name."); -// return new PrimitiveBackupInfo(info.customName, info.time, FilesystemUtil.getFileSizeBytes(zipFile)); return new PrimitiveBackupInfo(zipFile.getName(), FilesystemUtil.getFileSizeBytes(zipFile)); } diff --git a/src/main/java/com/keuin/kbackupfabric/util/ReflectionUtils.java b/src/main/java/com/keuin/kbackupfabric/util/ReflectionUtils.java index 2acc562..6fb1e3f 100644 --- a/src/main/java/com/keuin/kbackupfabric/util/ReflectionUtils.java +++ b/src/main/java/com/keuin/kbackupfabric/util/ReflectionUtils.java @@ -12,11 +12,7 @@ import java.lang.reflect.Method; public final class ReflectionUtils { /** - * 获取私有成员变量的值 - * - * @param instance - * @param filedName - * @return + * Read private fields. */ public static Object getPrivateField(Object instance, String filedName) throws NoSuchFieldException, IllegalAccessException { Field field = instance.getClass().getDeclaredField(filedName); @@ -25,13 +21,7 @@ public final class ReflectionUtils { } /** - * 设置私有成员的值 - * - * @param instance - * @param fieldName - * @param value - * @throws NoSuchFieldException - * @throws IllegalAccessException + * Modify private fields. */ public static void setPrivateField(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { Field field = instance.getClass().getDeclaredField(fieldName); @@ -40,18 +30,10 @@ public final class ReflectionUtils { } /** - * 访问私有方法 - * - * @param instance - * @param methodName - * @param classes - * @param objects - * @return - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException + * Call private methods. */ - public static Object invokePrivateMethod(Object instance, String methodName, Class[] classes, String objects) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + public static Object invokePrivateMethod(Object instance, String methodName, Class<?>[] classes, String objects) + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method method = instance.getClass().getDeclaredMethod(methodName, classes); method.setAccessible(true); return method.invoke(instance, objects); diff --git a/src/main/java/com/keuin/kbackupfabric/util/ZipUtil.java b/src/main/java/com/keuin/kbackupfabric/util/ZipUtil.java index eea1148..ce14c8a 100644 --- a/src/main/java/com/keuin/kbackupfabric/util/ZipUtil.java +++ b/src/main/java/com/keuin/kbackupfabric/util/ZipUtil.java @@ -4,6 +4,7 @@ import com.keuin.kbackupfabric.exception.ZipUtilException; import com.keuin.kbackupfabric.metadata.BackupMetadata; import java.io.*; +import java.nio.file.Files; import java.util.*; import java.util.zip.*; @@ -46,7 +47,7 @@ public final class ZipUtil { ZipEntry entry = new ZipEntry(subPath); zipOutputStream.putNextEntry(entry); // BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); - try (InputStream inputStream = new FileInputStream(file)) { + try (InputStream inputStream = Files.newInputStream(file.toPath())) { while ((count = inputStream.read(buffer, 0, zipBufferSize)) != -1) { zipOutputStream.write(buffer, 0, count); } @@ -100,7 +101,7 @@ public final class ZipUtil { File zipDir = new File(zipPath); if (!zipDir.exists() || !zipDir.isDirectory()) { if (!zipDir.mkdirs()) { - throw new IOException(String.format("Failed to make directory tree %s", zipDir.toString())); + throw new IOException(String.format("Failed to make directory tree %s", zipDir)); } } @@ -110,7 +111,7 @@ public final class ZipUtil { if (zipFile.exists()) { //删除已存在的目标文件 if (!zipFile.delete()) { - throw new IOException(String.format("Failed to delete existing file %s", zipFile.toString())); + throw new IOException(String.format("Failed to delete existing file %s", zipFile)); } } @@ -175,7 +176,7 @@ public final class ZipUtil { File unzipFileDir = new File(unzipFilePath); if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) { if (!unzipFileDir.mkdirs()) - throw new IOException(String.format("Failed to make directory tree %s", unzipFileDir.toString())); + throw new IOException(String.format("Failed to make directory tree %s", unzipFileDir)); } // 开始解压 @@ -202,7 +203,7 @@ public final class ZipUtil { // 如果文件夹路径不存在,则创建文件夹 if (!entryDir.exists() || !entryDir.isDirectory()) { if (!entryDir.mkdirs()) - throw new IOException(String.format("Failed to make directory tree %s", entryDir.toString())); + throw new IOException(String.format("Failed to make directory tree %s", entryDir)); } // 创建解压文件 @@ -213,16 +214,16 @@ public final class ZipUtil { securityManager.checkDelete(entryFilePath); // 删除已存在的目标文件 if (!entryFile.delete()) - throw new IOException(String.format("Failed to delete existing file %s", entryFile.toString())); + throw new IOException(String.format("Failed to delete existing file %s", entryFile)); } if (entry.isDirectory()) { // If the entry is a directory, we make its corresponding directory. if (!entryFile.mkdir()) - throw new IOException(String.format("Failed to create directory %s", entryFile.toString())); + throw new IOException(String.format("Failed to create directory %s", entryFile)); } else { // Is a file, we write the data // 写入文件 - try (OutputStream outputStream = new FileOutputStream(entryFile); + try (OutputStream outputStream = Files.newOutputStream(entryFile.toPath()); InputStream inputStream = zip.getInputStream(entry)) { while ((count = inputStream.read(buffer, 0, unzipBufferSize)) != -1) { outputStream.write(buffer, 0, count); diff --git a/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/ObjectCollection.java b/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/ObjectCollection.java index 0cd36a0..38b96ab 100644 --- a/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/ObjectCollection.java +++ b/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/ObjectCollection.java @@ -8,7 +8,7 @@ import java.util.*; * or it will not be compatible with old backups. * It remains only to keep a backward compatibility, and should be converted to `ObjectCollection2` as soon as possible. * Thus, this class is marked as `Depreciated`. However, it should not be removed since it is needed to read legacy - * backups correctly. But new codes should not use this class any more. + * backups correctly. But new codes should not use this class anymore. */ @Deprecated public class ObjectCollection implements Serializable { diff --git a/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/identifier/Sha256Identifier.java b/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/identifier/Sha256Identifier.java index 31cde29..c640c0b 100644 --- a/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/identifier/Sha256Identifier.java +++ b/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/identifier/Sha256Identifier.java @@ -3,12 +3,11 @@ package com.keuin.kbackupfabric.util.backup.incremental.identifier; import com.keuin.kbackupfabric.util.BytesUtil; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Objects; +import static com.keuin.kbackupfabric.backup.incremental.identifier.Sha256Identifier.sha256Hash; + /** * Identifier based on sha256. * Immutable. @@ -50,35 +49,7 @@ public class Sha256Identifier extends SingleHashIdentifier { @Override protected byte[] hash(File file) throws IOException { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - - try (FileInputStream inputStream = new FileInputStream(file)) { - // This does not work. I don't know why -// FileChannel channel = inputStream.getChannel(); -// ByteBuffer buffer = ByteBuffer.allocate(128); -// int readLength; -// while ((readLength = channel.read(buffer)) > 0) -// digest.update(buffer); - - // This also works, without warnings - byte[] readBuffer = new byte[1024 * 1024]; - int readLength; - while ((readLength = inputStream.read(readBuffer)) > 0) - digest.update(readBuffer, 0, readLength); - - // The below lines also works, but the IDE will complain about the while loop -// DigestInputStream digestInputStream = new DigestInputStream(inputStream, digest); -// while(digestInputStream.read() > 0) -// ; - - return digest.digest(); - } - - } catch (NoSuchAlgorithmException ignored) { - // this shouldn't happen - return new byte[SHA256_LENGTH]; - } + return sha256Hash(file); } }
\ No newline at end of file diff --git a/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/identifier/SingleHashIdentifier.java b/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/identifier/SingleHashIdentifier.java index 6c67918..285c6ce 100644 --- a/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/identifier/SingleHashIdentifier.java +++ b/src/main/java/com/keuin/kbackupfabric/util/backup/incremental/identifier/SingleHashIdentifier.java @@ -12,7 +12,6 @@ import java.util.Objects; * Immutable. */ public abstract class SingleHashIdentifier implements ObjectIdentifier { - private final byte[] hash; private final String type; @@ -37,11 +36,11 @@ public abstract class SingleHashIdentifier implements ObjectIdentifier { } @Override - public boolean equals(Object obj) { - if (!(obj instanceof com.keuin.kbackupfabric.backup.incremental.identifier.SingleHashIdentifier)) { - return false; - } - return Arrays.equals(hash, ((SingleHashIdentifier) obj).hash); + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SingleHashIdentifier that = (SingleHashIdentifier) o; + return Arrays.equals(hash, that.hash) && type.equals(that.type); } @Override |