From 7c00af18febf6c0b833c7633b4fb60a9a1bb93af Mon Sep 17 00:00:00 2001 From: IRONM00N <64110067+IRONM00N@users.noreply.github.com> Date: Sat, 16 Oct 2021 15:50:41 -0400 Subject: Code Clean Up (#2) * intellij code clean up * optimize imports * format * intellij suggestions * fix empty catch issues --- .../moulberry/notenoughupdates/NEUManager.java | 541 +++++++++++---------- 1 file changed, 277 insertions(+), 264 deletions(-) (limited to 'src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java') diff --git a/src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java b/src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java index 5fef4c62..59332f23 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java @@ -40,10 +40,10 @@ public class NEUManager { public final Gson gson; public final APIManager auctionManager; - private TreeMap itemMap = new TreeMap<>(); + private final TreeMap itemMap = new TreeMap<>(); - private TreeMap>> titleWordMap = new TreeMap<>(); - private TreeMap>> loreWordMap = new TreeMap<>(); + private final TreeMap>> titleWordMap = new TreeMap<>(); + private final TreeMap>> loreWordMap = new TreeMap<>(); public final KeyBinding keybindGive = new KeyBinding("Add item to inventory (Creative-only)", Keyboard.KEY_L, "NotEnoughUpdates"); public final KeyBinding keybindFavourite = new KeyBinding("Set item as favourite", Keyboard.KEY_F, "NotEnoughUpdates"); @@ -52,23 +52,23 @@ public class NEUManager { public final KeyBinding keybindToggleDisplay = new KeyBinding("Toggle NEU overlay", 0, "NotEnoughUpdates"); public final KeyBinding keybindClosePanes = new KeyBinding("Close NEU panes", 0, "NotEnoughUpdates"); public final KeyBinding keybindItemSelect = new KeyBinding("Select Item", -98 /*middle*/, "NotEnoughUpdates"); - public final KeyBinding[] keybinds = new KeyBinding[]{ keybindGive, keybindFavourite, keybindViewUsages, keybindViewRecipe, + public final KeyBinding[] keybinds = new KeyBinding[]{keybindGive, keybindFavourite, keybindViewUsages, keybindViewRecipe, keybindToggleDisplay, keybindClosePanes, keybindItemSelect}; public String viewItemAttemptID = null; public long viewItemAttemptTime = 0; private String currentProfile = ""; - private String currentProfileBackup = ""; + private final String currentProfileBackup = ""; public final HypixelApi hypixelApi = new HypixelApi(); - private Map itemstackCache = new HashMap<>(); + private final Map itemstackCache = new HashMap<>(); - private ExecutorService repoLoaderES = Executors.newSingleThreadExecutor(); + private final ExecutorService repoLoaderES = Executors.newSingleThreadExecutor(); private static String GIT_COMMITS_URL; - private HashMap> usagesMap = new HashMap<>(); + private final HashMap> usagesMap = new HashMap<>(); public String latestRepoCommit = null; @@ -97,25 +97,33 @@ public class NEUManager { } public T getJsonFromFile(File file, Class clazz) { - try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { T obj = gson.fromJson(reader, clazz); return obj; - } catch(Exception e) { return null; } + } catch (Exception e) { + return null; + } } /** * Parses a file in to a JsonObject. */ public JsonObject getJsonFromFile(File file) { - try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { JsonObject json = gson.fromJson(reader, JsonObject.class); return json; - } catch(Exception e) { return null; } + } catch (Exception e) { + return null; + } } public void resetRepo() { - try { Utils.recursiveDelete(new File(configLocation, "repo")); } catch(Exception e) {} - try { new File(configLocation, "currentCommit.json").delete(); } catch(Exception e) {} + try { + Utils.recursiveDelete(new File(configLocation, "repo")); + } catch (Exception ignored) {} + try { + new File(configLocation, "currentCommit.json").delete(); + } catch (Exception ignored) {} } /** @@ -158,27 +166,27 @@ public class NEUManager { repoLoaderES.submit(() -> { JDialog dialog = null; try { - if(NotEnoughUpdates.INSTANCE.config.hidden.autoupdate) { + if (NotEnoughUpdates.INSTANCE.config.hidden.autoupdate) { JOptionPane pane = new JOptionPane("Getting items to download from remote repository."); dialog = pane.createDialog("NotEnoughUpdates Remote Sync"); dialog.setModal(false); - if(NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); + if (NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); if (Display.isActive()) dialog.toFront(); JsonObject currentCommitJSON = getJsonFromFile(new File(configLocation, "currentCommit.json")); latestRepoCommit = null; - try(Reader inReader = new InputStreamReader(new URL(GIT_COMMITS_URL).openStream())) { + try (Reader inReader = new InputStreamReader(new URL(GIT_COMMITS_URL).openStream())) { JsonObject commits = gson.fromJson(inReader, JsonObject.class); latestRepoCommit = commits.get("sha").getAsString(); } catch (Exception e) { e.printStackTrace(); } - if(latestRepoCommit == null || latestRepoCommit.isEmpty()) return; + if (latestRepoCommit == null || latestRepoCommit.isEmpty()) return; - if(new File(configLocation, "repo").exists() && new File(configLocation, "repo/items").exists()) { - if(currentCommitJSON != null && currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { + if (new File(configLocation, "repo").exists() && new File(configLocation, "repo/items").exists()) { + if (currentCommitJSON != null && currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { dialog.setVisible(false); return; } @@ -189,12 +197,11 @@ public class NEUManager { Utils.recursiveDelete(repoLocation); repoLocation.mkdirs(); - String dlUrl = neu.config.hidden.repoURL; pane.setMessage("Downloading NEU Master Archive. (DL# >20)"); dialog.pack(); - if(NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); + if (NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); if (Display.isActive()) dialog.toFront(); File itemsZip = new File(repoLocation, "neu-items-master.zip"); @@ -204,13 +211,12 @@ public class NEUManager { return; } - URL url = new URL(dlUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(30000); - try(InputStream is = urlConnection.getInputStream()) { + try (InputStream is = urlConnection.getInputStream()) { FileUtils.copyInputStreamToFile(is, itemsZip); } catch (IOException e) { dialog.dispose(); @@ -237,29 +243,28 @@ public class NEUManager { unzipIgnoreFirstFolder(itemsZip.getAbsolutePath(), repoLocation.getAbsolutePath()); - if(currentCommitJSON == null || !currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { + if (currentCommitJSON == null || !currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { JsonObject newCurrentCommitJSON = new JsonObject(); newCurrentCommitJSON.addProperty("sha", latestRepoCommit); try { writeJson(newCurrentCommitJSON, new File(configLocation, "currentCommit.json")); - } catch (IOException e) { - } + } catch (IOException ignored) {} } } - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } finally { - if(dialog != null) dialog.dispose(); + if (dialog != null) dialog.dispose(); } File items = new File(repoLocation, "items"); - if(items.exists()) { + if (items.exists()) { File[] itemFiles = new File(repoLocation, "items").listFiles(); - if(itemFiles != null) { - for(File f : itemFiles) { - String internalname = f.getName().substring(0, f.getName().length()-5); - synchronized(itemMap) { - if(!itemMap.keySet().contains(internalname)) { + if (itemFiles != null) { + for (File f : itemFiles) { + String internalname = f.getName().substring(0, f.getName().length() - 5); + synchronized (itemMap) { + if (!itemMap.containsKey(internalname)) { loadItem(internalname); } } @@ -269,19 +274,19 @@ public class NEUManager { try { Constants.reload(); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } }); File items = new File(repoLocation, "items"); - if(items.exists()) { + if (items.exists()) { File[] itemFiles = new File(repoLocation, "items").listFiles(); - if(itemFiles != null) { - for(File f : itemFiles) { - String internalname = f.getName().substring(0, f.getName().length()-5); - synchronized(itemMap) { - if(!itemMap.keySet().contains(internalname)) { + if (itemFiles != null) { + for (File f : itemFiles) { + String internalname = f.getName().substring(0, f.getName().length() - 5); + synchronized (itemMap) { + if (!itemMap.containsKey(internalname)) { loadItem(internalname); } } @@ -291,7 +296,7 @@ public class NEUManager { try { Constants.reload(); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -299,41 +304,42 @@ public class NEUManager { /** * Loads the item in to the itemMap and also stores various words associated with this item * in to titleWordMap and loreWordMap. These maps are used in the searching algorithm. + * * @param internalName */ public void loadItem(String internalName) { itemstackCache.remove(internalName); try { JsonObject json = getJsonFromFile(new File(new File(repoLocation, "items"), internalName + ".json")); - if(json == null) { + if (json == null) { return; } - if(json.get("itemid") == null) return; + if (json.get("itemid") == null) return; String itemid = json.get("itemid").getAsString(); Item mcitem = Item.getByNameOrId(itemid); - if(mcitem != null) { + if (mcitem != null) { itemid = mcitem.getRegistryName(); } json.addProperty("itemid", itemid); itemMap.put(internalName, json); - if(json.has("recipe")) { - synchronized(usagesMap) { + if (json.has("recipe")) { + synchronized (usagesMap) { JsonObject recipe = json.get("recipe").getAsJsonObject(); - String[] x = {"1","2","3"}; - String[] y = {"A","B","C"}; - for(int i=0; i<9; i++) { - String name = y[i/3]+x[i%3]; + String[] x = {"1", "2", "3"}; + String[] y = {"A", "B", "C"}; + for (int i = 0; i < 9; i++) { + String name = y[i / 3] + x[i % 3]; String itemS = recipe.get(name).getAsString(); - if(itemS != null && itemS.split(":").length == 2) { + if (itemS != null && itemS.split(":").length == 2) { itemS = itemS.split(":")[0]; } - if(!usagesMap.containsKey(itemS)) { + if (!usagesMap.containsKey(itemS)) { usagesMap.put(itemS, new HashSet<>()); } usagesMap.get(itemS).add(internalName); @@ -341,15 +347,15 @@ public class NEUManager { } } - if(json.has("displayname")) { - synchronized(titleWordMap) { - int wordIndex=0; - for(String str : json.get("displayname").getAsString().split(" ")) { + if (json.has("displayname")) { + synchronized (titleWordMap) { + int wordIndex = 0; + for (String str : json.get("displayname").getAsString().split(" ")) { str = clean(str); - if(!titleWordMap.containsKey(str)) { + if (!titleWordMap.containsKey(str)) { titleWordMap.put(str, new HashMap<>()); } - if(!titleWordMap.get(str).containsKey(internalName)) { + if (!titleWordMap.get(str).containsKey(internalName)) { titleWordMap.get(str).put(internalName, new ArrayList<>()); } titleWordMap.get(str).get(internalName).add(wordIndex); @@ -358,16 +364,16 @@ public class NEUManager { } } - if(json.has("lore")) { - synchronized(loreWordMap) { - int wordIndex=0; - for(JsonElement element : json.get("lore").getAsJsonArray()) { - for(String str : element.getAsString().split(" ")) { + if (json.has("lore")) { + synchronized (loreWordMap) { + int wordIndex = 0; + for (JsonElement element : json.get("lore").getAsJsonArray()) { + for (String str : element.getAsString().split(" ")) { str = clean(str); - if(!loreWordMap.containsKey(str)) { + if (!loreWordMap.containsKey(str)) { loreWordMap.put(str, new HashMap<>()); } - if(!loreWordMap.get(str).containsKey(internalName)) { + if (!loreWordMap.get(str).containsKey(internalName)) { loreWordMap.get(str).put(internalName, new ArrayList<>()); } loreWordMap.get(str).get(internalName).add(wordIndex); @@ -376,11 +382,11 @@ public class NEUManager { } } } - } catch(Exception e) { - synchronized(loreWordMap) { + } catch (Exception e) { + synchronized (loreWordMap) { System.out.println("loreWordMap is : " + loreWordMap); } - synchronized(titleWordMap) { + synchronized (titleWordMap) { System.out.println("titleWordMap is : " + titleWordMap); } System.out.println("internalName is : " + internalName); @@ -399,9 +405,9 @@ public class NEUManager { query = clean(query).toLowerCase(); String[] splitToSeach = toSearch.split(" "); out: - for(String s : query.split(" ")) { - for(int i=0; i search(String query, boolean multi) { - if(multi) { + if (multi) { Set result = new HashSet<>(); StringBuilder query2 = new StringBuilder(); char lastOp = '|'; - for(char c : query.toCharArray()) { - if(c == '|' || c == '&') { - if(lastOp == '|') { + for (char c : query.toCharArray()) { + if (c == '|' || c == '&') { + if (lastOp == '|') { result.addAll(search(query2.toString())); - } else if(lastOp == '&') { + } else if (lastOp == '&') { result.retainAll(search(query2.toString())); } @@ -493,9 +499,9 @@ public class NEUManager { query2.append(c); } } - if(lastOp == '|') { + if (lastOp == '|') { result.addAll(search(query2.toString())); - } else if(lastOp == '&') { + } else if (lastOp == '&') { result.retainAll(search(query2.toString())); } @@ -543,22 +549,22 @@ public class NEUManager { public Set search(String query) { query = query.trim(); boolean negate = query.startsWith("!"); - if(negate) query = query.substring(1); + if (negate) query = query.substring(1); LinkedHashSet results = new LinkedHashSet<>(); - if(query.startsWith("title:")) { + if (query.startsWith("title:")) { query = query.substring(6); results.addAll(new TreeSet<>(search(query, titleWordMap))); - } else if(query.startsWith("desc:")) { + } else if (query.startsWith("desc:")) { query = query.substring(5); results.addAll(new TreeSet<>(search(query, loreWordMap))); - } else if(query.startsWith("id:")) { + } else if (query.startsWith("id:")) { query = query.substring(3); results.addAll(new TreeSet<>(subMapWithKeysThatAreSuffixes(query.toUpperCase(), itemMap).keySet())); } else { - if(!query.trim().contains(" ")) { + if (!query.trim().contains(" ")) { StringBuilder sb = new StringBuilder(); - for(char c : query.toCharArray()) { + for (char c : query.toCharArray()) { sb.append(c).append(" "); } results.addAll(new TreeSet<>(search(sb.toString(), titleWordMap))); @@ -566,11 +572,11 @@ public class NEUManager { results.addAll(new TreeSet<>(search(query, titleWordMap))); results.addAll(new TreeSet<>(search(query, loreWordMap))); } - if(!negate) { + if (!negate) { return results; } else { Set negatedResults = new HashSet<>(); - for(String internalname : itemMap.keySet()) { + for (String internalname : itemMap.keySet()) { negatedResults.add(internalname); } negatedResults.removeAll(results); @@ -589,24 +595,24 @@ public class NEUManager { HashMap> matches = null; query = clean(query).toLowerCase(); - for(String queryWord : query.split(" ")) { + for (String queryWord : query.split(" ")) { HashMap> matchesToKeep = new HashMap<>(); - for(HashMap> wordMatches : subMapWithKeysThatAreSuffixes(queryWord, wordMap).values()) { - if(wordMatches != null && !wordMatches.isEmpty()) { - if(matches == null) { + for (HashMap> wordMatches : subMapWithKeysThatAreSuffixes(queryWord, wordMap).values()) { + if (wordMatches != null && !wordMatches.isEmpty()) { + if (matches == null) { //Copy all wordMatches to titleMatches - for(String internalname : wordMatches.keySet()) { - if(!matchesToKeep.containsKey(internalname)) { + for (String internalname : wordMatches.keySet()) { + if (!matchesToKeep.containsKey(internalname)) { matchesToKeep.put(internalname, new ArrayList<>()); } matchesToKeep.get(internalname).addAll(wordMatches.get(internalname)); } } else { - for(String internalname : matches.keySet()) { - if(wordMatches.containsKey(internalname)) { - for(Integer newIndex : wordMatches.get(internalname)) { - if(matches.get(internalname).contains(newIndex-1)) { - if(!matchesToKeep.containsKey(internalname)) { + for (String internalname : matches.keySet()) { + if (wordMatches.containsKey(internalname)) { + for (Integer newIndex : wordMatches.get(internalname)) { + if (matches.get(internalname).contains(newIndex - 1)) { + if (!matchesToKeep.containsKey(internalname)) { matchesToKeep.put(internalname, new ArrayList<>()); } matchesToKeep.get(internalname).add(newIndex); @@ -617,7 +623,7 @@ public class NEUManager { } } } - if(matchesToKeep.isEmpty()) return new HashSet<>(); + if (matchesToKeep.isEmpty()) return new HashSet<>(); matches = matchesToKeep; } @@ -634,11 +640,11 @@ public class NEUManager { } public String createLexicographicallyNextStringOfTheSameLength(String input) { - final int lastCharPosition = input.length()-1; + final int lastCharPosition = input.length() - 1; String inputWithoutLastChar = input.substring(0, lastCharPosition); - char lastChar = input.charAt(lastCharPosition) ; + char lastChar = input.charAt(lastCharPosition); char incrementedLastChar = (char) (lastChar + 1); - return inputWithoutLastChar+incrementedLastChar; + return inputWithoutLastChar + incrementedLastChar; } public JsonObject getJsonFromItemBytes(String item_bytes) { @@ -646,7 +652,7 @@ public class NEUManager { NBTTagCompound tag = CompressedStreamTools.readCompressed(new ByteArrayInputStream(Base64.getDecoder().decode(item_bytes))); //System.out.println(tag.toString()); return getJsonFromNBT(tag); - } catch(IOException e) { + } catch (IOException e) { return null; } } @@ -665,41 +671,47 @@ public class NEUManager { public String getInternalnameFromNBT(NBTTagCompound tag) { String internalname = null; - if(tag != null && tag.hasKey("ExtraAttributes", 10)) { + if (tag != null && tag.hasKey("ExtraAttributes", 10)) { NBTTagCompound ea = tag.getCompoundTag("ExtraAttributes"); - if(ea.hasKey("id", 8)) { + if (ea.hasKey("id", 8)) { internalname = ea.getString("id").replaceAll(":", "-"); } else { return null; } - if("PET".equals(internalname)) { + if ("PET".equals(internalname)) { String petInfo = ea.getString("petInfo"); - if(petInfo.length() > 0) { + if (petInfo.length() > 0) { JsonObject petInfoObject = gson.fromJson(petInfo, JsonObject.class); internalname = petInfoObject.get("type").getAsString(); String tier = petInfoObject.get("tier").getAsString(); - switch(tier) { + switch (tier) { case "COMMON": - internalname += ";0"; break; + internalname += ";0"; + break; case "UNCOMMON": - internalname += ";1"; break; + internalname += ";1"; + break; case "RARE": - internalname += ";2"; break; + internalname += ";2"; + break; case "EPIC": - internalname += ";3"; break; + internalname += ";3"; + break; case "LEGENDARY": - internalname += ";4"; break; + internalname += ";4"; + break; case "MYTHIC": - internalname += ";5"; break; + internalname += ";5"; + break; } } } - if("ENCHANTED_BOOK".equals(internalname)) { + if ("ENCHANTED_BOOK".equals(internalname)) { NBTTagCompound enchants = ea.getCompoundTag("enchantments"); - for(String enchname : enchants.getKeySet()) { + for (String enchname : enchants.getKeySet()) { internalname = enchname.toUpperCase() + ";" + enchants.getInteger(enchname); break; } @@ -713,10 +725,10 @@ public class NEUManager { String[] lore = new String[0]; NBTTagCompound display = tag.getCompoundTag("display"); - if(display.hasKey("Lore", 9)) { + if (display.hasKey("Lore", 9)) { NBTTagList list = display.getTagList("Lore", 8); lore = new String[list.tagCount()]; - for(int k=0; k 0) { + if (lore != null && lore.length > 0) { JsonArray jsonLore = new JsonArray(); for (String line : lore) { jsonLore.add(new JsonPrimitive(line)); @@ -788,7 +800,7 @@ public class NEUManager { } item.addProperty("damage", damage); - if(count > 1) item.addProperty("count", count); + if (count > 1) item.addProperty("count", count); item.addProperty("nbttag", tag.toString()); return item; @@ -800,22 +812,22 @@ public class NEUManager { public void showRecipe(JsonObject item) { ContainerChest container = null; - if(Minecraft.getMinecraft().thePlayer.openContainer instanceof ContainerChest) + if (Minecraft.getMinecraft().thePlayer.openContainer instanceof ContainerChest) container = (ContainerChest) Minecraft.getMinecraft().thePlayer.openContainer; if (item.has("recipe") && container != null && container.getLowerChestInventory().getDisplayName().getUnformattedText().equals("Craft Item")) { CraftingOverlay.updateItem(item); - } else if(item.has("useneucraft") && item.get("useneucraft").getAsBoolean()) { + } else if (item.has("useneucraft") && item.get("useneucraft").getAsBoolean()) { displayGuiItemRecipe(item.get("internalname").getAsString(), ""); - } else if(item.has("clickcommand")) { + } else if (item.has("clickcommand")) { String clickcommand = item.get("clickcommand").getAsString(); - if(clickcommand.equals("viewrecipe")) { + if (clickcommand.equals("viewrecipe")) { neu.sendChatMessage( "/" + clickcommand + " " + item.get("internalname").getAsString().split(";")[0]); viewItemAttemptID = item.get("internalname").getAsString(); viewItemAttemptTime = System.currentTimeMillis(); - } else if(clickcommand.equals("viewpotion")) { + } else if (clickcommand.equals("viewpotion")) { neu.sendChatMessage( "/" + clickcommand + " " + item.get("internalname").getAsString().split(";")[0].toLowerCase()); @@ -833,26 +845,26 @@ public class NEUManager { //Item lore String[] lore = new String[0]; - if(tag.hasKey("display", 10)) { + if (tag.hasKey("display", 10)) { NBTTagCompound display = tag.getCompoundTag("display"); - if(display.hasKey("Lore", 9)) { + if (display.hasKey("Lore", 9)) { NBTTagList list = display.getTagList("Lore", 8); lore = new String[list.tagCount()]; - for(int i=0; i 0 && (lore[lore.length-1].contains("Click to view recipes!") || - lore[lore.length-1].contains("Click to view recipe!"))) { - String[] lore2 = new String[lore.length-2]; - System.arraycopy(lore, 0, lore2, 0, lore.length-2); + if (lore.length > 0 && (lore[lore.length - 1].contains("Click to view recipes!") || + lore[lore.length - 1].contains("Click to view recipe!"))) { + String[] lore2 = new String[lore.length - 2]; + System.arraycopy(lore, 0, lore2, 0, lore.length - 2); lore = lore2; } @@ -863,7 +875,7 @@ public class NEUManager { json.addProperty("damage", stack.getItemDamage()); JsonArray jsonlore = new JsonArray(); - for(String line : lore) { + for (String line : lore) { jsonlore.add(new JsonPrimitive(line)); } json.add("lore", jsonlore); @@ -872,13 +884,13 @@ public class NEUManager { } public String getInternalNameForItem(ItemStack stack) { - if(stack == null) return null; + if (stack == null) return null; NBTTagCompound tag = stack.getTagCompound(); return getInternalnameFromNBT(tag); } public String getUUIDForItem(ItemStack stack) { - if(stack == null) return null; + if (stack == null) return null; NBTTagCompound tag = stack.getTagCompound(); return getUUIDFromNBT(tag); } @@ -886,7 +898,7 @@ public class NEUManager { public void writeItemToFile(ItemStack stack) { String internalname = getInternalNameForItem(stack); - if(internalname == null) { + if (internalname == null) { return; } @@ -896,8 +908,8 @@ public class NEUManager { json.addProperty("modver", NotEnoughUpdates.VERSION); try { - writeJson(json, new File(new File(repoLocation, "items"), internalname+".json")); - } catch (IOException e) {} + writeJson(json, new File(new File(repoLocation, "items"), internalname + ".json")); + } catch (IOException ignored) {} loadItem(internalname); } @@ -907,33 +919,33 @@ public class NEUManager { */ public boolean displayGuiItemUsages(String internalName) { List craftMatrices = new ArrayList<>(); - List results = new ArrayList<>(); + List results = new ArrayList<>(); - if(!usagesMap.containsKey(internalName)) { + if (!usagesMap.containsKey(internalName)) { return false; } - for(String internalNameResult : usagesMap.get(internalName)) { + for (String internalNameResult : usagesMap.get(internalName)) { JsonObject item = getItemInformation().get(internalNameResult); results.add(item); - if(item != null && item.has("recipe")) { + if (item != null && item.has("recipe")) { JsonObject recipe = item.get("recipe").getAsJsonObject(); ItemStack[] craftMatrix = new ItemStack[9]; - String[] x = {"1","2","3"}; - String[] y = {"A","B","C"}; - for(int i=0; i<9; i++) { - String name = y[i/3]+x[i%3]; + String[] x = {"1", "2", "3"}; + String[] y = {"A", "B", "C"}; + for (int i = 0; i < 9; i++) { + String name = y[i / 3] + x[i % 3]; String itemS = recipe.get(name).getAsString(); int count = 1; - if(itemS != null && itemS.split(":").length == 2) { - count = Integer.valueOf(itemS.split(":")[1]); + if (itemS != null && itemS.split(":").length == 2) { + count = Integer.parseInt(itemS.split(":")[1]); itemS = itemS.split(":")[0]; } JsonObject craft = getItemInformation().get(itemS); - if(craft != null) { + if (craft != null) { ItemStack stack = jsonToStack(craft); stack.stackSize = count; craftMatrix[i] = stack; @@ -944,7 +956,7 @@ public class NEUManager { } } - if(craftMatrices.size() > 0) { + if (craftMatrices.size() > 0) { Minecraft.getMinecraft().displayGuiScreen(new GuiItemRecipe("Item Usages", craftMatrices, results, this)); return true; } @@ -956,23 +968,23 @@ public class NEUManager { */ public boolean displayGuiItemRecipe(String internalName, String text) { JsonObject item = getItemInformation().get(internalName); - if(item != null && item.has("recipe")) { + if (item != null && item.has("recipe")) { JsonObject recipe = item.get("recipe").getAsJsonObject(); ItemStack[] craftMatrix = new ItemStack[9]; - String[] x = {"1","2","3"}; - String[] y = {"A","B","C"}; - for(int i=0; i<9; i++) { - String name = y[i/3]+x[i%3]; + String[] x = {"1", "2", "3"}; + String[] y = {"A", "B", "C"}; + for (int i = 0; i < 9; i++) { + String name = y[i / 3] + x[i % 3]; String itemS = recipe.get(name).getAsString(); int count = 1; - if(itemS != null && itemS.split(":").length == 2) { - count = Integer.valueOf(itemS.split(":")[1]); + if (itemS != null && itemS.split(":").length == 2) { + count = Integer.parseInt(itemS.split(":")[1]); itemS = itemS.split(":")[0]; } JsonObject craft = getItemInformation().get(itemS); - if(craft != null) { + if (craft != null) { ItemStack stack = jsonToStack(craft); stack.stackSize = count; craftMatrix[i] = stack; @@ -981,7 +993,7 @@ public class NEUManager { Minecraft.getMinecraft().thePlayer.sendQueue.addToSendQueue(new C0DPacketCloseWindow( Minecraft.getMinecraft().thePlayer.openContainer.windowId)); - Minecraft.getMinecraft().displayGuiScreen(new GuiItemRecipe(text!=null?text:"Item Recipe", + Minecraft.getMinecraft().displayGuiScreen(new GuiItemRecipe(text != null ? text : "Item Recipe", Lists.newArrayList(craftMatrix), Lists.newArrayList(item), this)); return true; } @@ -993,8 +1005,8 @@ public class NEUManager { * unlocked. See NotEnoughUpdates#onGuiChat for where this method is called. */ public boolean failViewItem(String text) { - if(viewItemAttemptID != null && !viewItemAttemptID.isEmpty()) { - if(System.currentTimeMillis() - viewItemAttemptTime < 500) { + if (viewItemAttemptID != null && !viewItemAttemptID.isEmpty()) { + if (System.currentTimeMillis() - viewItemAttemptTime < 500) { return displayGuiItemRecipe(viewItemAttemptID, text); } } @@ -1005,8 +1017,8 @@ public class NEUManager { * Downloads a web file, appending some HTML attributes that makes wikia give us the raw wiki syntax. */ public File getWebFile(String url) { - File f = new File(configLocation, "tmp/"+Base64.getEncoder().encodeToString(url.getBytes())+".html"); - if(f.exists()) { + File f = new File(configLocation, "tmp/" + Base64.getEncoder().encodeToString(url.getBytes()) + ".html"); + if (f.exists()) { return f; } @@ -1017,9 +1029,9 @@ public class NEUManager { } catch (IOException e) { return null; } - try (BufferedInputStream inStream = new BufferedInputStream(new URL(url+"?action=raw&templates=expand").openStream()); + try (BufferedInputStream inStream = new BufferedInputStream(new URL(url + "?action=raw&templates=expand").openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) { - byte dataBuffer[] = new byte[1024]; + byte[] dataBuffer = new byte[1024]; int bytesRead; while ((bytesRead = inStream.read(dataBuffer, 0, 1024)) != -1) { fileOutputStream.write(dataBuffer, 0, bytesRead); @@ -1032,14 +1044,13 @@ public class NEUManager { return f; } - /** * Modified from https://www.journaldev.com/960/java-unzip-file-example */ private static void unzipIgnoreFirstFolder(String zipFilePath, String destDir) { File dir = new File(destDir); // create output directory if it doesn't exist - if(!dir.exists()) dir.mkdirs(); + if (!dir.exists()) dir.mkdirs(); FileInputStream fis; //buffer for read and write data to file byte[] buffer = new byte[1024]; @@ -1047,10 +1058,10 @@ public class NEUManager { fis = new FileInputStream(zipFilePath); ZipInputStream zis = new ZipInputStream(fis); ZipEntry ze = zis.getNextEntry(); - while(ze != null){ - if(!ze.isDirectory()) { + while (ze != null) { + if (!ze.isDirectory()) { String fileName = ze.getName(); - fileName = fileName.substring(fileName.split("/")[0].length()+1); + fileName = fileName.substring(fileName.split("/")[0].length() + 1); File newFile = new File(destDir + File.separator + fileName); //create directories for sub directories in zip new File(newFile.getParent()).mkdirs(); @@ -1083,8 +1094,8 @@ public class NEUManager { try { ZipInputStream zis = new ZipInputStream(src); ZipEntry ze = zis.getNextEntry(); - while(ze != null){ - if(!ze.isDirectory()) { + while (ze != null) { + if (!ze.isDirectory()) { String fileName = ze.getName(); File newFile = new File(dest, fileName); //create directories for sub directories in zip @@ -1121,7 +1132,7 @@ public class NEUManager { public JsonObject createItemJson(JsonObject base, String internalname, String itemid, String displayname, String[] lore, String crafttext, String infoType, String[] info, String clickcommand, int damage, NBTTagCompound nbttag) { - if(internalname == null || internalname.isEmpty()) { + if (internalname == null || internalname.isEmpty()) { return null; } @@ -1134,9 +1145,9 @@ public class NEUManager { json.addProperty("damage", damage); json.addProperty("nbttag", nbttag.toString()); json.addProperty("modver", NotEnoughUpdates.VERSION); - json.addProperty("infoType", infoType.toString()); + json.addProperty("infoType", infoType); - if(info != null && info.length > 0) { + if (info != null && info.length > 0) { JsonArray jsoninfo = new JsonArray(); for (String line : info) { jsoninfo.add(new JsonPrimitive(line)); @@ -1145,7 +1156,7 @@ public class NEUManager { } JsonArray jsonlore = new JsonArray(); - for(String line : lore) { + for (String line : lore) { jsonlore.add(new JsonPrimitive(line)); } json.add("lore", jsonlore); @@ -1161,13 +1172,13 @@ public class NEUManager { public boolean writeItemJson(JsonObject base, String internalname, String itemid, String displayname, String[] lore, String crafttext, String infoType, String[] info, String clickcommand, int damage, NBTTagCompound nbttag) { JsonObject json = createItemJson(base, internalname, itemid, displayname, lore, crafttext, infoType, info, clickcommand, damage, nbttag); - if(json == null) { + if (json == null) { return false; } try { - writeJsonDefaultDir(json, internalname+".json"); - } catch(IOException e) { + writeJsonDefaultDir(json, internalname + ".json"); + } catch (IOException e) { return false; } @@ -1178,7 +1189,7 @@ public class NEUManager { public void writeJson(JsonObject json, File file) throws IOException { file.createNewFile(); - try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { + try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { writer.write(gson.toJson(json)); } } @@ -1193,8 +1204,8 @@ public class NEUManager { } public String removeUnusedDecimal(double num) { - if(num % 1 == 0) { - return String.valueOf((int)num); + if (num % 1 == 0) { + return String.valueOf((int) num); } else { return String.valueOf(num); } @@ -1202,58 +1213,57 @@ public class NEUManager { public HashMap getLoreReplacements(String petname, String tier, int level) { JsonObject petnums = null; - if(petname != null && tier != null) { + if (petname != null && tier != null) { petnums = Constants.PETNUMS; } HashMap replacements = new HashMap<>(); - if(level < 1) { - if (Constants.PETS.has("custom_pet_leveling") && Constants.PETS.getAsJsonObject("custom_pet_leveling").has(petname) && Constants.PETS.getAsJsonObject("custom_pet_leveling").getAsJsonObject(petname).has("max_level")){ + if (level < 1) { + if (Constants.PETS.has("custom_pet_leveling") && Constants.PETS.getAsJsonObject("custom_pet_leveling").has(petname) && Constants.PETS.getAsJsonObject("custom_pet_leveling").getAsJsonObject(petname).has("max_level")) { int maxLvl = Constants.PETS.getAsJsonObject("custom_pet_leveling").getAsJsonObject(petname).get("max_level").getAsInt(); - replacements.put("LVL", "1\u27A1"+maxLvl); + replacements.put("LVL", "1\u27A1" + maxLvl); } else { replacements.put("LVL", "1\u27A1100"); } } else { - replacements.put("LVL", ""+level); + replacements.put("LVL", "" + level); } - - if(petnums != null) { - if(petnums.has(petname)) { + if (petnums != null) { + if (petnums.has(petname)) { JsonObject petInfo = petnums.get(petname).getAsJsonObject(); - if(petInfo.has(tier)) { + if (petInfo.has(tier)) { JsonObject petInfoTier = petInfo.get(tier).getAsJsonObject(); - if(petInfoTier == null || !petInfoTier.has("1") || !petInfoTier.has("100")) { + if (petInfoTier == null || !petInfoTier.has("1") || !petInfoTier.has("100")) { return replacements; } JsonObject min = petInfoTier.get("1").getAsJsonObject(); JsonObject max = petInfoTier.get("100").getAsJsonObject(); - if(level < 1) { + if (level < 1) { JsonArray otherNumsMin = min.get("otherNums").getAsJsonArray(); JsonArray otherNumsMax = max.get("otherNums").getAsJsonArray(); boolean addZero = false; - if(petInfoTier.has("stats_levelling_curve")){ + if (petInfoTier.has("stats_levelling_curve")) { String[] stringArray = petInfoTier.get("stats_levelling_curve").getAsString().split(":"); - if(stringArray.length == 3) { + if (stringArray.length == 3) { int type = Integer.parseInt(stringArray[2]); - if(type == 1){ + if (type == 1) { addZero = true; } } } - for(int i=0; i entry : max.get("statNums").getAsJsonObject().entrySet()) { - int statMax = (int)Math.floor(entry.getValue().getAsFloat()); - int statMin = (int)Math.floor(min.get("statNums").getAsJsonObject().get(entry.getKey()).getAsFloat()); - String statStr = (statMin>0?"+":"")+statMin+"\u27A1"+statMax; - statStr = (addZero?"0\u27A1":"")+statStr; + for (Map.Entry entry : max.get("statNums").getAsJsonObject().entrySet()) { + int statMax = (int) Math.floor(entry.getValue().getAsFloat()); + int statMin = (int) Math.floor(min.get("statNums").getAsJsonObject().get(entry.getKey()).getAsFloat()); + String statStr = (statMin > 0 ? "+" : "") + statMin + "\u27A1" + statMax; + statStr = (addZero ? "0\u27A1" : "") + statStr; replacements.put(entry.getKey(), statStr); } } else { @@ -1264,8 +1274,7 @@ public class NEUManager { int statsLevel = level; - - if(petInfoTier.has("stats_levelling_curve")) { + if (petInfoTier.has("stats_levelling_curve")) { String[] stringArray = petInfoTier.get("stats_levelling_curve").getAsString().split(":"); if (stringArray.length == 3) { minStatsLevel = Integer.parseInt(stringArray[0]); @@ -1287,22 +1296,22 @@ public class NEUManager { } } } - float minMix = (maxStatsLevel-(minStatsLevel-(statsLevelingType==-1?0:1))-statsLevel)/99f; - float maxMix = (statsLevel-1)/99f; + float minMix = (maxStatsLevel - (minStatsLevel - (statsLevelingType == -1 ? 0 : 1)) - statsLevel) / 99f; + float maxMix = (statsLevel - 1) / 99f; JsonArray otherNumsMin = min.get("otherNums").getAsJsonArray(); JsonArray otherNumsMax = max.get("otherNums").getAsJsonArray(); - for(int i=0; i entry : max.get("statNums").getAsJsonObject().entrySet()) { - if(statsLevelingType == 1 && level < minStatsLevel) { + for (Map.Entry entry : max.get("statNums").getAsJsonObject().entrySet()) { + if (statsLevelingType == 1 && level < minStatsLevel) { replacements.put(entry.getKey(), "0"); } else { float statMax = entry.getValue().getAsFloat(); @@ -1323,27 +1332,32 @@ public class NEUManager { public HashMap getLoreReplacements(NBTTagCompound tag, int level) { String petname = null; String tier = null; - if(tag != null && tag.hasKey("ExtraAttributes")) { + if (tag != null && tag.hasKey("ExtraAttributes")) { NBTTagCompound ea = tag.getCompoundTag("ExtraAttributes"); - if(ea.hasKey("petInfo")) { + if (ea.hasKey("petInfo")) { String petInfoStr = ea.getString("petInfo"); JsonObject petInfo = gson.fromJson(petInfoStr, JsonObject.class); petname = petInfo.get("type").getAsString(); tier = petInfo.get("tier").getAsString(); - if(petInfo.has("heldItem")) { + if (petInfo.has("heldItem")) { String heldItem = petInfo.get("heldItem").getAsString(); - if(heldItem.equals("PET_ITEM_TIER_BOOST")) { - switch(tier) { + if (heldItem.equals("PET_ITEM_TIER_BOOST")) { + switch (tier) { case "COMMON": - tier = "UNCOMMON"; break; + tier = "UNCOMMON"; + break; case "UNCOMMON": - tier = "RARE"; break; + tier = "RARE"; + break; case "RARE": - tier = "EPIC"; break; + tier = "EPIC"; + break; case "EPIC": - tier = "LEGENDARY"; break; + tier = "LEGENDARY"; + break; case "LEGENDARY": - tier = "MYTHIC"; break; + tier = "MYTHIC"; + break; } } } @@ -1354,12 +1368,12 @@ public class NEUManager { public NBTTagList processLore(JsonArray lore, HashMap replacements) { NBTTagList nbtLore = new NBTTagList(); - for(JsonElement line : lore) { + for (JsonElement line : lore) { String lineStr = line.getAsString(); - if(!lineStr.contains("Click to view recipes!") && + if (!lineStr.contains("Click to view recipes!") && !lineStr.contains("Click to view recipe!")) { - for(Map.Entry entry : replacements.entrySet()) { - lineStr = lineStr.replace("{"+entry.getKey()+"}", entry.getValue()); + for (Map.Entry entry : replacements.entrySet()) { + lineStr = lineStr.replace("{" + entry.getKey() + "}", entry.getValue()); } nbtLore.appendTag(new NBTTagString(lineStr)); } @@ -1380,13 +1394,13 @@ public class NEUManager { } public ItemStack jsonToStack(JsonObject json, boolean useCache, boolean useReplacements, boolean copyStack) { - if(json == null) return new ItemStack(Items.painting, 1, 10); + if (json == null) return new ItemStack(Items.painting, 1, 10); String internalname = json.get("internalname").getAsString(); - if(useCache) { + if (useCache) { ItemStack stack = itemstackCache.get(internalname); - if(stack != null) { - if(copyStack) { + if (stack != null) { + if (copyStack) { return stack.copy(); } else { return stack; @@ -1397,40 +1411,39 @@ public class NEUManager { ItemStack stack = new ItemStack(Item.itemRegistry.getObject( new ResourceLocation(json.get("itemid").getAsString()))); - if(json.has("count")) { + if (json.has("count")) { stack.stackSize = json.get("count").getAsInt(); } - if(stack.getItem() == null) { + if (stack.getItem() == null) { stack = new ItemStack(Item.getItemFromBlock(Blocks.stone), 0, 255); //Purple broken texture item } else { - if(json.has("damage")) { + if (json.has("damage")) { stack.setItemDamage(json.get("damage").getAsInt()); } - if(json.has("nbttag")) { + if (json.has("nbttag")) { try { NBTTagCompound tag = JsonToNBT.getTagFromJson(json.get("nbttag").getAsString()); stack.setTagCompound(tag); - } catch(NBTException e) { - } + } catch (NBTException ignored) {} } HashMap replacements = new HashMap<>(); - if(useReplacements) { + if (useReplacements) { replacements = getLoreReplacements(stack.getTagCompound(), -1); String displayname = json.get("displayname").getAsString(); - for(Map.Entry entry : replacements.entrySet()) { - displayname = displayname.replace("{"+entry.getKey()+"}", entry.getValue()); + for (Map.Entry entry : replacements.entrySet()) { + displayname = displayname.replace("{" + entry.getKey() + "}", entry.getValue()); } stack.setStackDisplayName(displayname); } - if(json.has("lore")) { + if (json.has("lore")) { NBTTagCompound display = new NBTTagCompound(); - if(stack.getTagCompound() != null && stack.getTagCompound().hasKey("display")) { + if (stack.getTagCompound() != null && stack.getTagCompound().hasKey("display")) { display = stack.getTagCompound().getCompoundTag("display"); } display.setTag("Lore", processLore(json.get("lore").getAsJsonArray(), replacements)); @@ -1440,8 +1453,8 @@ public class NEUManager { } } - if(useCache) itemstackCache.put(internalname, stack); - if(copyStack) { + if (useCache) itemstackCache.put(internalname, stack); + if (copyStack) { return stack.copy(); } else { return stack; -- cgit From f7e8edf3357db624212af5f24b74e7763c678fba Mon Sep 17 00:00:00 2001 From: nopothegamer <40329022+nopothegamer@users.noreply.github.com> Date: Thu, 18 Nov 2021 09:58:28 +1100 Subject: Added blocking clicks back to the enchanting minigames (#19) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * idk where im commiting to * idk where im commiting to * made tita overlay and waypoints work with dwarven overlay off "fixed" divan rarity in neuah made eitherwarp block overlay turn off able * Added change notes * i stopped being pepega and worked out how neu config works * Added mining skill overlay * fixed mining overlay * add option to hide Mining waypoints in Dwarven mines when at location * better check location * Make cata xp in /pv be calculated on how many runs you have * Added master cata xp rates * Make gitignore not show as changed * Added warnings to some things in /neu * maybe fix hiding waypoints * Added a fishing ski