Fixes some warnings

This commit is contained in:
Kristian Knarvik 2024-09-07 01:27:00 +02:00
parent 0f76c8f869
commit e482e494f8
12 changed files with 44 additions and 36 deletions

View File

@ -143,7 +143,7 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.13.1</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -46,6 +46,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder; import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getErrorColor; import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getErrorColor;
@ -244,8 +245,8 @@ public class BooksWithoutBorders extends JavaPlugin {
sendErrorMessage(consoleSender, "Saving failed! Aborting..."); sendErrorMessage(consoleSender, "Saving failed! Aborting...");
return false; return false;
} }
} catch (Exception e) { } catch (Exception exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to create necessary folders");
return false; return false;
} }
} }
@ -255,8 +256,8 @@ public class BooksWithoutBorders extends JavaPlugin {
sendErrorMessage(consoleSender, "Saving failed! Aborting..."); sendErrorMessage(consoleSender, "Saving failed! Aborting...");
return false; return false;
} }
} catch (Exception e) { } catch (Exception exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to create necessary folders");
return false; return false;
} }
} }

View File

@ -20,6 +20,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getCommandColor; import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getCommandColor;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getErrorColor; import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getErrorColor;
@ -142,8 +143,8 @@ public class CommandSave implements TabExecutor {
//Update the relevant book list //Update the relevant book list
BooksWithoutBorders.updateBooks(player, saveToPublicFolder); BooksWithoutBorders.updateBooks(player, saveToPublicFolder);
BooksWithoutBorders.sendSuccessMessage(player, "Book Saved as \"" + fileName + "\""); BooksWithoutBorders.sendSuccessMessage(player, "Book Saved as \"" + fileName + "\"");
} catch (IOException e) { } catch (IOException exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to save book");
} }
} }

View File

@ -7,6 +7,7 @@ import org.bukkit.Material;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.Configuration; import org.bukkit.configuration.Configuration;
import java.nio.file.FileSystems;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -22,7 +23,7 @@ public class BooksWithoutBordersConfig {
private static final ChatColor errorColor = ChatColor.RED; private static final ChatColor errorColor = ChatColor.RED;
private static final ChatColor successColor = ChatColor.GREEN; private static final ChatColor successColor = ChatColor.GREEN;
private static final ChatColor commandColor = ChatColor.YELLOW; private static final ChatColor commandColor = ChatColor.YELLOW;
private static final String SLASH = System.getProperty("file.separator"); private static final String SLASH = FileSystems.getDefault().getSeparator();
private static boolean isInitialized; private static boolean isInitialized;
public static String bookFolder; public static String bookFolder;

View File

@ -1,5 +1,7 @@
package net.knarcraft.bookswithoutborders.encryption; package net.knarcraft.bookswithoutborders.encryption;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import javax.crypto.BadPaddingException; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException; import javax.crypto.IllegalBlockSizeException;
@ -15,6 +17,7 @@ import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import java.util.Base64; import java.util.Base64;
import java.util.logging.Level;
/** /**
* This class represents and AES encryptor/decryptor * This class represents and AES encryptor/decryptor
@ -66,16 +69,16 @@ public class AES {
//Initialize cipher //Initialize cipher
try { try {
aes.init(mode, secretKeySpec, ivParameterSpec); aes.init(mode, secretKeySpec, ivParameterSpec);
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) { } catch (InvalidKeyException | InvalidAlgorithmParameterException exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES input given!");
return null; return null;
} }
//Perform encryption/decryption and output result //Perform encryption/decryption and output result
try { try {
byte[] output = aes.doFinal(getInputBytes(input, encrypt)); byte[] output = aes.doFinal(getInputBytes(input, encrypt));
return createResult(output, encrypt); return createResult(output, encrypt);
} catch (IllegalBlockSizeException | BadPaddingException e) { } catch (IllegalBlockSizeException | BadPaddingException exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES block size or padding");
return null; return null;
} }
} }
@ -131,8 +134,8 @@ public class AES {
Cipher aes; Cipher aes;
try { try {
aes = Cipher.getInstance("AES/CBC/PKCS5Padding"); aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) { } catch (NoSuchAlgorithmException | NoSuchPaddingException exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES algorithm or padding");
return null; return null;
} }
return aes; return aes;
@ -149,15 +152,15 @@ public class AES {
SecretKeyFactory keyFactory; SecretKeyFactory keyFactory;
try { try {
keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES algorithm");
return null; return null;
} }
SecretKey tmp; SecretKey tmp;
try { try {
tmp = keyFactory.generateSecret(spec); tmp = keyFactory.generateSecret(spec);
} catch (InvalidKeySpecException e) { } catch (InvalidKeySpecException exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Invalid AES key specification");
return null; return null;
} }
return new SecretKeySpec(tmp.getEncoded(), "AES"); return new SecretKeySpec(tmp.getEncoded(), "AES");

View File

@ -33,7 +33,7 @@ public class GenenCrypt {
for (int j = 0; j < 4; j++) { for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) { for (int k = 0; k < 4; k++) {
for (int l = 0; l < 4; l++) { for (int l = 0; l < 4; l++) {
originalCodonList.add("" + bases[i] + bases[j] + bases[k] + bases[l]); originalCodonList.add(bases[i] + bases[j] + bases[k] + bases[l]);
} }
} }
} }
@ -49,7 +49,7 @@ public class GenenCrypt {
// use the random number generator and the originalCodonList to make a shuffled list // use the random number generator and the originalCodonList to make a shuffled list
ArrayList<String> shuffledCodonList = new ArrayList<>(); ArrayList<String> shuffledCodonList = new ArrayList<>();
while (originalCodonList.size() > 0) { while (!originalCodonList.isEmpty()) {
int index = ranGen.nextInt(originalCodonList.size()); int index = ranGen.nextInt(originalCodonList.size());
shuffledCodonList.add(originalCodonList.get(index)); shuffledCodonList.add(originalCodonList.get(index));
originalCodonList.remove(index); originalCodonList.remove(index);

View File

@ -19,7 +19,7 @@ public class SubstitutionCipher {
// original message is offset by // original message is offset by
public String encrypt(String in, String key) { public String encrypt(String in, String key) {
StringBuilder output = new StringBuilder(); StringBuilder output = new StringBuilder();
if (key != null && key.length() > 0) { if (key != null && !key.isEmpty()) {
StringTokenizer tokenizer = new StringTokenizer(key, ", "); // tokenizes the key StringTokenizer tokenizer = new StringTokenizer(key, ", "); // tokenizes the key
// converts each number in the key to an integer and adds to an array // converts each number in the key to an integer and adds to an array
int[] offsetArray = new int[tokenizer.countTokens()]; int[] offsetArray = new int[tokenizer.countTokens()];
@ -55,7 +55,7 @@ public class SubstitutionCipher {
@SuppressWarnings("unused") @SuppressWarnings("unused")
public String decrypt(String in, String key) { public String decrypt(String in, String key) {
StringBuilder output = new StringBuilder(); StringBuilder output = new StringBuilder();
if (key != null && key.length() > 0) { if (key != null && !key.isEmpty()) {
StringTokenizer tokenizer = new StringTokenizer(key, ", "); // tokenizes the key StringTokenizer tokenizer = new StringTokenizer(key, ", "); // tokenizes the key
// converts each number in the key to an integer and adds to an array // converts each number in the key to an integer and adds to an array
int[] offsetArray = new int[tokenizer.countTokens()]; int[] offsetArray = new int[tokenizer.countTokens()];

View File

@ -33,7 +33,8 @@ public class BookshelfListener implements Listener {
Player player = event.getPlayer(); Player player = event.getPlayer();
// If left-clicking a chiseled bookshelf and sneaking, display contents // If left-clicking a chiseled bookshelf and sneaking, display contents
if (!event.hasBlock() || !(event.getClickedBlock().getState() instanceof ChiseledBookshelf chiseledBookshelf) || if (!event.hasBlock() || event.getClickedBlock() == null ||
!(event.getClickedBlock().getState() instanceof ChiseledBookshelf chiseledBookshelf) ||
event.getAction() != Action.LEFT_CLICK_BLOCK || !player.isSneaking()) { event.getAction() != Action.LEFT_CLICK_BLOCK || !player.isSneaking()) {
return; return;
} }

View File

@ -57,7 +57,7 @@ public class SignEventListener implements Listener {
//Check if the sign is of a valid type //Check if the sign is of a valid type
if (!((lines[1].equalsIgnoreCase("[Encrypt]") || lines[1].equalsIgnoreCase("[Decrypt]") || if (!((lines[1].equalsIgnoreCase("[Encrypt]") || lines[1].equalsIgnoreCase("[Decrypt]") ||
lines[1].equalsIgnoreCase("[Give]")) && lines[2].trim().length() > 0)) { lines[1].equalsIgnoreCase("[Give]")) && !lines[2].trim().isEmpty())) {
//Mark the second line as invalid //Mark the second line as invalid
event.setLine(1, ChatColor.DARK_RED + lines[1]); event.setLine(1, ChatColor.DARK_RED + lines[1]);
return; return;

View File

@ -1,5 +1,6 @@
package net.knarcraft.bookswithoutborders.utility; package net.knarcraft.bookswithoutborders.utility;
import net.knarcraft.bookswithoutborders.BooksWithoutBorders;
import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig; import net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig;
import net.knarcraft.knarlib.util.FileHelper; import net.knarcraft.knarlib.util.FileHelper;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
@ -15,6 +16,7 @@ import java.io.PrintWriter;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import static net.knarcraft.bookswithoutborders.utility.BookHelper.authorFromUUID; import static net.knarcraft.bookswithoutborders.utility.BookHelper.authorFromUUID;
import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.fixName; import static net.knarcraft.bookswithoutborders.utility.InputCleaningHelper.fixName;
@ -157,13 +159,13 @@ public final class BookToFromTextHelper {
List<String> rawPages; List<String> rawPages;
try { try {
rawPages = readTextFile(file); rawPages = readTextFile(file);
} catch (IOException e) { } catch (IOException exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to read text file");
return null; return null;
} }
//Parse the generation from the book data //Parse the generation from the book data
if (rawPages != null && rawPages.size() > 0 && rawPages.get(0).startsWith("Generation:")) { if (rawPages != null && !rawPages.isEmpty() && rawPages.get(0).startsWith("Generation:")) {
bookMetadata.setGeneration(BookMeta.Generation.valueOf(rawPages.get(0).split(":")[1])); bookMetadata.setGeneration(BookMeta.Generation.valueOf(rawPages.get(0).split(":")[1]));
rawPages.remove(0); rawPages.remove(0);
} }

View File

@ -16,6 +16,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder; import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getBookFolder;
import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getSlash; import static net.knarcraft.bookswithoutborders.config.BooksWithoutBordersConfig.getSlash;
@ -255,8 +256,8 @@ public final class EncryptionHelper {
BooksWithoutBorders.sendErrorMessage(BooksWithoutBorders.getConsoleSender(), "Unable to create encryption group folder!"); BooksWithoutBorders.sendErrorMessage(BooksWithoutBorders.getConsoleSender(), "Unable to create encryption group folder!");
return null; return null;
} }
} catch (Exception e) { } catch (Exception exception) {
e.printStackTrace(); BooksWithoutBorders.getInstance().getLogger().log(Level.SEVERE, "Unable to save group encrypted book");
return null; return null;
} }
} }
@ -279,8 +280,7 @@ public final class EncryptionHelper {
if (!file.isFile()) { if (!file.isFile()) {
try { try {
BookToFromTextHelper.bookToYml(path, fileName, bookMetadata); BookToFromTextHelper.bookToYml(path, fileName, bookMetadata);
} catch (IOException e) { } catch (IOException exception) {
e.printStackTrace();
BooksWithoutBorders.sendErrorMessage(player, "Group encrypted failed!"); BooksWithoutBorders.sendErrorMessage(player, "Group encrypted failed!");
return null; return null;
} }
@ -312,8 +312,7 @@ public final class EncryptionHelper {
try { try {
BookToFromTextHelper.bookToYml(path, fileName, bookMetaData); BookToFromTextHelper.bookToYml(path, fileName, bookMetaData);
} catch (IOException e) { } catch (IOException exception) {
e.printStackTrace();
BooksWithoutBorders.sendErrorMessage(player, "Encryption failed!"); BooksWithoutBorders.sendErrorMessage(player, "Encryption failed!");
return false; return false;
} }

View File

@ -1,9 +1,9 @@
package net.knarcraft.bookswithoutborders.encryption; package net.knarcraft.bookswithoutborders.encryption;
import junit.framework.Assert;
import org.junit.Test; import org.junit.Test;
import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
public class AESTest { public class AESTest {
@ -15,7 +15,7 @@ public class AESTest {
AES aes = new AES(AES.generateIV(), AES.generateIV()); AES aes = new AES(AES.generateIV(), AES.generateIV());
String encrypted = aes.encryptDecryptText(plainText, password, true); String encrypted = aes.encryptDecryptText(plainText, password, true);
Assert.assertNotSame(encrypted, plainText); assertNotSame(encrypted, plainText);
String decrypted = aes.encryptDecryptText(encrypted, password, false); String decrypted = aes.encryptDecryptText(encrypted, password, false);
assertEquals(plainText, decrypted); assertEquals(plainText, decrypted);
} }