Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Thread Creation to ThreadFactory for better Thread namings #466

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/api/version/v7.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ public void run() {
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
```

Expand Down Expand Up @@ -443,7 +443,7 @@ class BasicThread implements Runnable {
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
```

Expand Down
4 changes: 2 additions & 2 deletions docs/api/version/v8.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ public void run() {
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
```

Expand Down Expand Up @@ -443,7 +443,7 @@ class BasicThread implements Runnable {
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
```

Expand Down
4 changes: 2 additions & 2 deletions docs/api/version/v9.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ public void run() {
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
```

Expand Down Expand Up @@ -497,7 +497,7 @@ class BasicThread implements Runnable {
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
```

Expand Down
27 changes: 13 additions & 14 deletions src/main/java/net/coreprotect/CoreProtect.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
package net.coreprotect;

import java.io.File;
import java.util.Iterator;
import java.util.Map.Entry;

import org.bstats.bukkit.MetricsLite;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;

import net.coreprotect.command.CommandHandler;
import net.coreprotect.command.TabHandler;
import net.coreprotect.config.Config;
Expand All @@ -30,6 +18,17 @@
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Teleport;
import net.coreprotect.utility.Util;
import org.bstats.bukkit.MetricsLite;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.util.Iterator;
import java.util.Map.Entry;

public final class CoreProtect extends JavaPlugin {

Expand Down Expand Up @@ -102,15 +101,15 @@

Scheduler.scheduleSyncDelayedTask(this, () -> {
try {
Thread networkHandler = new Thread(new NetworkHandler(true, true));
Thread networkHandler = Util.THREAD_FACTORY.newThread(new NetworkHandler(true, true));
networkHandler.start();
}
catch (Exception e) {
e.printStackTrace();
}
}, 0);

Thread cacheCleanUpThread = new Thread(new CacheHandler());
Thread cacheCleanUpThread = Util.THREAD_FACTORY.newThread(new CacheHandler());
cacheCleanUpThread.start();

Consumer.startConsumer();
Expand Down Expand Up @@ -164,62 +163,62 @@
return true;
}

private static void safeShutdown(CoreProtect plugin) {
try {
/* if server is stopping, log disconnections of online players */
if (ConfigHandler.serverRunning && PaperAdapter.ADAPTER.isStopping(plugin.getServer())) {
for (Player player : plugin.getServer().getOnlinePlayers()) {
PlayerQuitListener.queuePlayerQuit(player);
}
}

if (!ConfigHandler.isFolia) {
Iterator<Entry<Location, BlockData>> iterator = Teleport.revertBlocks.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Location, BlockData> entry = iterator.next();
entry.getKey().getBlock().setBlockData(entry.getValue());
iterator.remove();
}
}

ConfigHandler.serverRunning = false;
long shutdownTime = System.currentTimeMillis();
long alertTime = shutdownTime + (10 * 1000);
if (ConfigHandler.converterRunning) {
Chat.console(Phrase.build(Phrase.FINISHING_CONVERSION));
}
else {
Chat.console(Phrase.build(Phrase.FINISHING_LOGGING));
}

while ((Consumer.isRunning() || ConfigHandler.converterRunning) && !ConfigHandler.purgeRunning) {
long time = System.currentTimeMillis();
if (time >= alertTime) {
if (!ConfigHandler.converterRunning) {
int consumerId = (Consumer.currentConsumer == 1) ? 1 : 0;
int consumerCount = Consumer.getConsumerSize(consumerId) + Process.getCurrentConsumerSize();
Chat.console(Phrase.build(Phrase.LOGGING_ITEMS, String.format("%,d", consumerCount)));
}
alertTime = alertTime + (30 * 1000);
}
else if (!ConfigHandler.databaseReachable && (time - shutdownTime) >= (5 * 60 * 1000)) {
Chat.console(Phrase.build(Phrase.DATABASE_UNREACHABLE));
break;
}
else if ((time - shutdownTime) >= (15 * 60 * 1000)) {
Chat.console(Phrase.build(Phrase.LOGGING_TIME_LIMIT));
break;
}

Thread.sleep(100);
}

ConfigHandler.performDisable();
Chat.console(Phrase.build(Phrase.DISABLE_SUCCESS, "CoreProtect v" + plugin.getDescription().getVersion()));
}
catch (Exception e) {
e.printStackTrace();
}
}

Check notice on line 223 in src/main/java/net/coreprotect/CoreProtect.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/CoreProtect.java#L166-L223

Complex Method
}
35 changes: 14 additions & 21 deletions src/main/java/net/coreprotect/command/CommandHandler.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,5 @@
package net.coreprotect.command;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;

import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
Expand All @@ -30,6 +10,19 @@
import net.coreprotect.utility.Chat;
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CommandHandler implements CommandExecutor {
private static CommandHandler instance;
Expand All @@ -51,194 +44,194 @@
return argumentArray;
}

protected static List<Integer> parseAction(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
List<Integer> result = new ArrayList<>();
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("a:") || argument.equals("action:")) {
next = 1;
}
else if (next == 1 || argument.startsWith("a:") || argument.startsWith("action:")) {
result.clear();
argument = argument.replaceAll("action:", "");
argument = argument.replaceAll("a:", "");
if (argument.startsWith("#")) {
argument = argument.replaceFirst("#", "");
}
if (argument.equals("broke") || argument.equals("break") || argument.equals("remove") || argument.equals("destroy") || argument.equals("block-break") || argument.equals("block-remove") || argument.equals("-block") || argument.equals("-blocks") || argument.equals("block-")) {
result.add(0);
}
else if (argument.equals("placed") || argument.equals("place") || argument.equals("block-place") || argument.equals("+block") || argument.equals("+blocks") || argument.equals("block+")) {
result.add(1);
}
else if (argument.equals("block") || argument.equals("blocks") || argument.equals("block-change") || argument.equals("change") || argument.equals("changes")) {
result.add(0);
result.add(1);
}
else if (argument.equals("click") || argument.equals("clicks") || argument.equals("interact") || argument.equals("interaction") || argument.equals("player-interact") || argument.equals("player-interaction") || argument.equals("player-click")) {
result.add(2);
}
else if (argument.equals("death") || argument.equals("deaths") || argument.equals("entity-death") || argument.equals("entity-deaths") || argument.equals("kill") || argument.equals("kills") || argument.equals("entity-kill") || argument.equals("entity-kills")) {
result.add(3);
}
else if (argument.equals("container") || argument.equals("container-change") || argument.equals("containers") || argument.equals("chest") || argument.equals("transaction") || argument.equals("transactions")) {
result.add(4);
}
else if (argument.equals("-container") || argument.equals("container-") || argument.equals("remove-container")) {
result.add(4);
result.add(0);
}
else if (argument.equals("+container") || argument.equals("container+") || argument.equals("container-add") || argument.equals("add-container")) {
result.add(4);
result.add(1);
}
else if (argument.equals("chat") || argument.equals("chats")) {
result.add(6);
}
else if (argument.equals("command") || argument.equals("commands")) {
result.add(7);
}
else if (argument.equals("logins") || argument.equals("login") || argument.equals("+session") || argument.equals("+sessions") || argument.equals("session+") || argument.equals("+connection") || argument.equals("connection+")) {
result.add(8);
result.add(1);
}
else if (argument.equals("logout") || argument.equals("logouts") || argument.equals("-session") || argument.equals("-sessions") || argument.equals("session-") || argument.equals("-connection") || argument.equals("connection-")) {
result.add(8);
result.add(0);
}
else if (argument.equals("session") || argument.equals("sessions") || argument.equals("connection") || argument.equals("connections")) {
result.add(8);
}
else if (argument.equals("username") || argument.equals("usernames") || argument.equals("user") || argument.equals("users") || argument.equals("name") || argument.equals("names") || argument.equals("uuid") || argument.equals("uuids") || argument.equals("username-change") || argument.equals("username-changes") || argument.equals("name-change") || argument.equals("name-changes")) {
result.add(9);
}
else if (argument.equals("sign") || argument.equals("signs")) {
result.add(10);
}
else if (argument.equals("inv") || argument.equals("inventory") || argument.equals("inventories")) {
result.add(4); // container
result.add(11); // item
}
else if (argument.equals("-inv") || argument.equals("inv-") || argument.equals("-inventory") || argument.equals("inventory-") || argument.equals("-inventories")) {
result.add(4);
result.add(11);
result.add(1);
}
else if (argument.equals("+inv") || argument.equals("inv+") || argument.equals("+inventory") || argument.equals("inventory+") || argument.equals("+inventories")) {
result.add(4);
result.add(11);
result.add(0);
}
else if (argument.equals("item") || argument.equals("items")) {
result.add(11);
}
else if (argument.equals("-item") || argument.equals("item-") || argument.equals("-items") || argument.equals("items-") || argument.equals("drop") || argument.equals("drops") || argument.equals("deposit") || argument.equals("deposits") || argument.equals("deposited")) {
result.add(11);
result.add(0);
}
else if (argument.equals("+item") || argument.equals("item+") || argument.equals("+items") || argument.equals("items+") || argument.equals("pickup") || argument.equals("pickups") || argument.equals("withdraw") || argument.equals("withdraws") || argument.equals("withdrew")) {
result.add(11);
result.add(1);
}
else {
result.add(-1);
}
next = 0;
}
else {
next = 0;
}
}
count++;
}
return result;
}

Check failure on line 156 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L47-L156

Very Complex Method
protected static Location parseCoordinates(Location location, String[] inputArguments, int worldId) {
String[] argumentArray = inputArguments.clone();
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("position:") || argument.equals("location:") || argument.equals("c:") || argument.equals("coord:") || argument.equals("coords:") || argument.equals("cord:") || argument.equals("cords:") || argument.equals("coordinate:") || argument.equals("coordinates:") || argument.equals("cordinate:") || argument.equals("cordinates:")) {
next = 2;
}
else if (next == 2 || argument.startsWith("c:") || argument.startsWith("coord:") || argument.startsWith("coords:") || argument.startsWith("cord:") || argument.startsWith("cords:") || argument.startsWith("coordinate:") || argument.startsWith("coordinates:") || argument.startsWith("cordinate:") || argument.startsWith("cordinates:")) {
argument = argument.replaceAll("coordinates:", "");
argument = argument.replaceAll("coordinate:", "");
argument = argument.replaceAll("cordinates:", "");
argument = argument.replaceAll("cordinate:", "");
argument = argument.replaceAll("coords:", "");
argument = argument.replaceAll("coord:", "");
argument = argument.replaceAll("cords:", "");
argument = argument.replaceAll("cord:", "");
argument = argument.replaceAll("c:", "");
if (argument.contains(",")) {
String[] i2 = argument.split(",");
double x = 0.00;
double y = 0.00;
double z = 0.00;
int cCount = 0;
for (String coord : i2) {
coord = coord.replaceAll("[^0-9.\\-]", "");
if (coord.length() > 0 && !coord.equals(".") && !coord.equals("-") && coord.indexOf('.') == coord.lastIndexOf('.')) {
double parsedCoord = Double.parseDouble(coord);
if (cCount == 0) {
x = parsedCoord;
}
else if (cCount == 1) {
z = parsedCoord;
}
else if (cCount == 2) {
y = z;
z = parsedCoord;
}
cCount++;
}
}
if (cCount > 1) {
if (location == null && worldId > 0) {
location = new Location(Bukkit.getWorld(Util.getWorldName(worldId)), 0, 0, 0);
}
if (location != null) {
int worldMaxHeight = location.getWorld().getMaxHeight() - 1;
int worldMinHeight = BukkitAdapter.ADAPTER.getMinHeight(location.getWorld());

if (y < worldMinHeight) {
y = Double.valueOf(worldMinHeight);
}
if (y > worldMaxHeight) {
y = Double.valueOf(worldMaxHeight);
}

location.setX(x);
location.setY(y);
location.setZ(z);
}
}
}
next = 0;
}
else {
next = 0;
}
}
count++;
}
return location;
}

Check notice on line 234 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L157-L234

Complex Method
protected static boolean parseCount(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
boolean result = false;
Expand All @@ -257,203 +250,203 @@
return result;
}

protected static Map<Object, Boolean> parseExcluded(CommandSender player, String[] inputArguments, List<Integer> argAction) {
String[] argumentArray = inputArguments.clone();
Map<Object, Boolean> excluded = new HashMap<>();
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("e:") || argument.equals("exclude:")) {
next = 5;
}
else if (next == 5 || argument.startsWith("e:") || argument.startsWith("exclude:")) {
argument = argument.replaceAll("exclude:", "");
argument = argument.replaceAll("e:", "");
if (argument.contains(",")) {
String[] i2 = argument.split(",");
for (String i3 : i2) {
if (i3.equals("#natural")) {
for (Material block : naturalBlocks) {
excluded.put(block, false);
}
}
else {
Material i3_material = Util.getType(i3);
if (i3_material != null && (i3_material.isBlock() || argAction.contains(4))) {
excluded.put(i3_material, false);
}
else {
EntityType i3_entity = Util.getEntityType(i3);
if (i3_entity != null) {
excluded.put(i3_entity, false);
}
else if (i3_material != null) {
excluded.put(i3_material, false);
}
}
}
}
if (argument.endsWith(",")) {
next = 5;
}
else {
next = 0;
}
}
else {
if (argument.equals("#natural")) {
for (Material block : naturalBlocks) {
excluded.put(block, false);
}
}
else {
Material iMaterial = Util.getType(argument);
if (iMaterial != null && (iMaterial.isBlock() || argAction.contains(4))) {
excluded.put(iMaterial, false);
}
else {
EntityType iEntity = Util.getEntityType(argument);
if (iEntity != null) {
excluded.put(iEntity, false);
}
else if (iMaterial != null) {
excluded.put(iMaterial, false);
}
}
}
next = 0;
}
}
else {
next = 0;
}
}
count++;
}
return excluded;
}

Check notice on line 333 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L253-L333

Complex Method
protected static List<String> parseExcludedUsers(CommandSender player, String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
List<String> excluded = new ArrayList<>();
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("e:") || argument.equals("exclude:")) {
next = 5;
}
else if (next == 5 || argument.startsWith("e:") || argument.startsWith("exclude:")) {
argument = argument.replaceAll("exclude:", "");
argument = argument.replaceAll("e:", "");
if (argument.contains(",")) {
String[] i2 = argument.split(",");
for (String i3 : i2) {
boolean isBlock = false;
if (i3.equals("#natural")) {
isBlock = true;
}
else {
Material i3_material = Util.getType(i3);
if (i3_material != null) {
isBlock = true;
}
else {
EntityType i3Entity = Util.getEntityType(i3);
if (i3Entity != null) {
isBlock = true;
}
}
}
if (!isBlock) {
excluded.add(i3);
}
}
if (argument.endsWith(",")) {
next = 5;
}
else {
next = 0;
}
}
else {
boolean isBlock = false;
if (argument.equals("#natural")) {
isBlock = true;
}
else {
Material iMaterial = Util.getType(argument);
if (iMaterial != null) {
isBlock = true;
}
else {
EntityType entityType = Util.getEntityType(argument);
if (entityType != null) {
isBlock = true;
}
}
}
if (!isBlock) {
excluded.add(argument);
}
next = 0;
}
}
else {
next = 0;
}
}
count++;
}
return excluded;
}

Check notice on line 412 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L334-L412

Complex Method
protected static boolean parseForceGlobal(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
boolean result = false;
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("r:") || argument.equals("radius:")) {
next = 2;
}
else if (next == 2 || argument.startsWith("r:") || argument.startsWith("radius:")) {
argument = argument.replaceAll("radius:", "");
argument = argument.replaceAll("r:", "");
if (argument.equals("#global") || argument.equals("global") || argument.equals("off") || argument.equals("-1") || argument.equals("none") || argument.equals("false")) {
result = true;
}
else if (argument.startsWith("#")) {
int worldId = Util.matchWorld(argument);
if (worldId > 0) {
result = true;
}
}
next = 0;
}
else {
next = 0;
}
}
count++;
}
return result;
}

Check notice on line 449 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L413-L449

Complex Method
protected static Location parseLocation(CommandSender user, String[] argumentArray) {
Location location = null;
if (user instanceof Player) {
Expand Down Expand Up @@ -512,419 +505,419 @@
return result;
}

protected static Integer[] parseRadius(String[] inputArguments, CommandSender user, Location location) {
String[] argumentArray = inputArguments.clone();
Integer[] radius = null;
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("r:") || argument.equals("radius:")) {
next = 2;
}
else if (next == 2 || argument.startsWith("r:") || argument.startsWith("radius:")) {
argument = argument.replaceAll("radius:", "");
argument = argument.replaceAll("r:", "");
if (argument.equals("#worldedit") || argument.equals("#we")) {
if (user.getServer().getPluginManager().getPlugin("WorldEdit") != null) {
Integer[] worldEditResult = WorldEditHandler.runWorldEditCommand(user);
if (worldEditResult != null) {
radius = worldEditResult;
}
}
}
else if ((argument.startsWith("#") && argument.length() > 1) || argument.equals("global") || argument.equals("off") || argument.equals("-1") || argument.equals("none") || argument.equals("false")) {
// radius = -2;
}
else {
int rcount = 0;
int r_x = 0;
int r_y = -1;
int r_z = 0;
String[] r_dat = new String[] { argument };
boolean validRadius = false;
if (argument.contains("x")) {
r_dat = argument.split("x");
}
for (String value : r_dat) {
String i4 = value.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.length() == value.length() && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
double a1 = Double.parseDouble(i4);
if (rcount == 0) { // x
r_x = (int) a1;
r_z = (int) a1;
}
else if (rcount == 1) { // y
r_y = (int) a1;
}
else if (rcount == 2) { // z
r_z = (int) a1;
}
validRadius = true;
}
rcount++;
}
if (location != null) {
Integer xmin = location.getBlockX() - r_x;
Integer xmax = location.getBlockX() + r_x;
Integer ymin = null;
Integer ymax = null;
Integer zmin = location.getBlockZ() - r_z;
Integer zmax = location.getBlockZ() + r_z;
if (r_y > -1) {
ymin = location.getBlockY() - r_y;
ymax = location.getBlockY() + r_y;
}
int max = r_x;
if (r_y > max) {
max = r_y;
}
if (r_z > max) {
max = r_z;
}
if (validRadius) {
radius = new Integer[] { max, xmin, xmax, ymin, ymax, zmin, zmax, 0 };
}
else {
radius = new Integer[] { -1 };
}
}
}
next = 0;
}
else {
next = 0;
}
}
count++;
}
return radius;
}

Check notice on line 600 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L508-L600

Complex Method
protected static List<Object> parseRestricted(CommandSender player, String[] inputArguments, List<Integer> argAction) {
String[] argumentArray = inputArguments.clone();
List<Object> restricted = new ArrayList<>();
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("i:") || argument.equals("include:") || argument.equals("item:") || argument.equals("items:") || argument.equals("b:") || argument.equals("block:") || argument.equals("blocks:")) {
next = 4;
}
else if (next == 4 || argument.startsWith("i:") || argument.startsWith("include:") || argument.startsWith("item:") || argument.startsWith("items:") || argument.startsWith("b:") || argument.startsWith("block:") || argument.startsWith("blocks:")) {
argument = argument.replaceAll("include:", "");
argument = argument.replaceAll("i:", "");
argument = argument.replaceAll("items:", "");
argument = argument.replaceAll("item:", "");
argument = argument.replaceAll("blocks:", "");
argument = argument.replaceAll("block:", "");
argument = argument.replaceAll("b:", "");
if (argument.contains(",")) {
String[] i2 = argument.split(",");
for (String i3 : i2) {
if (i3.equals("#natural")) {
restricted.addAll(naturalBlocks);
}
else {
Material i3_material = Util.getType(i3);
if (i3_material != null && (i3_material.isBlock() || argAction.contains(4))) {
restricted.add(i3_material);
}
else {
EntityType i3_entity = Util.getEntityType(i3);
if (i3_entity != null) {
restricted.add(i3_entity);
}
else if (i3_material != null) {
restricted.add(i3_material);
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_INCLUDE, i3));
// Functions.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co help include"));
return null;
}
}
}
}
if (argument.endsWith(",")) {
next = 4;
}
else {
next = 0;
}
}
else {
if (argument.equals("#natural")) {
restricted.addAll(naturalBlocks);
}
else {
Material material = Util.getType(argument);
if (material != null && (material.isBlock() || argAction.contains(4))) {
restricted.add(material);
}
else {
EntityType entityType = Util.getEntityType(argument);
if (entityType != null) {
restricted.add(entityType);
}
else if (material != null) {
restricted.add(material);
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_INCLUDE, argument));
// Functions.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co help include"));
return null;
}
}
}
next = 0;
}
}
else {
next = 0;
}
}
count++;
}
return restricted;
}

Check notice on line 692 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L601-L692

Complex Method
protected static long[] parseTime(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
long timeStart = 0;
long timeEnd = 0;
int count = 0;
int next = 0;
boolean range = false;
double w = 0;
double d = 0;
double h = 0;
double m = 0;
double s = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("t:") || argument.equals("time:")) {
next = 1;
}
else if (next == 1 || argument.startsWith("t:") || argument.startsWith("time:")) {
// time arguments
argument = argument.replaceAll("time:", "");
argument = argument.replaceAll("t:", "");
argument = argument.replaceAll("y", "y:");
argument = argument.replaceAll("m", "m:");
argument = argument.replaceAll("w", "w:");
argument = argument.replaceAll("d", "d:");
argument = argument.replaceAll("h", "h:");
argument = argument.replaceAll("s", "s:");
range = argument.contains("-");

int argCount = 0;
String[] i2 = argument.split(":");
for (String i3 : i2) {
if (range && argCount > 0 && timeStart == 0 && i3.startsWith("-")) {
timeStart = (long) (((w * 7 * 24 * 60 * 60) + (d * 24 * 60 * 60) + (h * 60 * 60) + (m * 60) + s));
w = 0;
d = 0;
h = 0;
m = 0;
s = 0;
}

if (i3.endsWith("w") && w == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
w = Double.parseDouble(i4);
}
}
else if (i3.endsWith("d") && d == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
d = Double.parseDouble(i4);
}
}
else if (i3.endsWith("h") && h == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
h = Double.parseDouble(i4);
}
}
else if (i3.endsWith("m") && m == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
m = Double.parseDouble(i4);
}
}
else if (i3.endsWith("s") && s == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
s = Double.parseDouble(i4);
}
}

argCount++;
}
if (timeStart > 0) {
timeEnd = (long) (((w * 7 * 24 * 60 * 60) + (d * 24 * 60 * 60) + (h * 60 * 60) + (m * 60) + s));
}
else {
timeStart = (long) (((w * 7 * 24 * 60 * 60) + (d * 24 * 60 * 60) + (h * 60 * 60) + (m * 60) + s));
}
next = 0;
}
else {
next = 0;
}
}
count++;
}

if (timeEnd >= timeStart) {
return new long[] { timeEnd, timeStart };
}
else {
return new long[] { timeStart, timeEnd };
}
}

Check notice on line 793 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L693-L793

Complex Method
private static String timeString(BigDecimal input) {
return input.stripTrailingZeros().toPlainString();
}

protected static String parseTimeString(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
String time = "";
int count = 0;
int next = 0;
boolean range = false;
BigDecimal w = new BigDecimal(0);
BigDecimal d = new BigDecimal(0);
BigDecimal h = new BigDecimal(0);
BigDecimal m = new BigDecimal(0);
BigDecimal s = new BigDecimal(0);
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("t:") || argument.equals("time:")) {
next = 1;
}
else if (next == 1 || argument.startsWith("t:") || argument.startsWith("time:")) {
// time arguments
argument = argument.replaceAll("time:", "");
argument = argument.replaceAll("t:", "");
argument = argument.replaceAll("y", "y:");
argument = argument.replaceAll("m", "m:");
argument = argument.replaceAll("w", "w:");
argument = argument.replaceAll("d", "d:");
argument = argument.replaceAll("h", "h:");
argument = argument.replaceAll("s", "s:");
range = argument.contains("-");

int argCount = 0;
String[] i2 = argument.split(":");
for (String i3 : i2) {
if (range && argCount > 0 && !time.contains("-") && i3.startsWith("-")) {
w = new BigDecimal(0);
d = new BigDecimal(0);
h = new BigDecimal(0);
m = new BigDecimal(0);
s = new BigDecimal(0);
time = time + " -";
}

if (i3.endsWith("w") && w.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
w = new BigDecimal(i4);
if (range) {
time = time + " " + timeString(w) + "w";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_WEEKS, timeString(w), (w.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
else if (i3.endsWith("d") && d.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
d = new BigDecimal(i4);
if (range) {
time = time + " " + timeString(d) + "d";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_DAYS, timeString(d), (d.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
else if (i3.endsWith("h") && h.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
h = new BigDecimal(i4);
if (range) {
time = time + " " + timeString(h) + "h";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_HOURS, timeString(h), (h.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
else if (i3.endsWith("m") && m.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
m = new BigDecimal(i4);
if (range) {
time = time + " " + timeString(m) + "m";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_MINUTES, timeString(m), (m.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
else if (i3.endsWith("s") && s.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
s = new BigDecimal(i4);
if (range) {
time = time + " " + timeString(s) + "s";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_SECONDS, timeString(s), (s.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}

argCount++;
}
next = 0;
}
else {
next = 0;
}
}
count++;
}

if (time.startsWith(" ")) {
time = time.substring(1);
}

return time;
}

Check notice on line 920 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L798-L920

Complex Method
protected static int parseRows(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
int rows = 0;
Expand Down Expand Up @@ -974,104 +967,104 @@
}
}

protected static List<String> parseUsers(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
List<String> users = new ArrayList<>();
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (next == 2) {
if (argument.endsWith(",")) {
next = 2;
}
else {
next = 0;
}
}
else if (argument.equals("p:") || argument.equals("user:") || argument.equals("users:") || argument.equals("u:")) {
next = 1;
}
else if (next == 1 || argument.startsWith("p:") || argument.startsWith("user:") || argument.startsWith("users:") || argument.startsWith("u:")) {
argument = argument.replaceAll("user:", "");
argument = argument.replaceAll("users:", "");
argument = argument.replaceAll("p:", "");
argument = argument.replaceAll("u:", "");
if (argument.contains(",")) {
String[] i2 = argument.split(",");
for (String i3 : i2) {
parseUser(users, i3);
}
if (argument.endsWith(",")) {
next = 1;
}
else {
next = 0;
}
}
else {
parseUser(users, argument);
next = 0;
}
}
else if (argument.endsWith(",") || argument.endsWith(":")) {
next = 2;
}
else if (argument.contains(":")) {
next = 0;
}
else {
parseUser(users, argument);
next = 0;
}
}
count++;
}
return users;
}

Check notice on line 1029 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L970-L1029

Complex Method
protected static int parseWorld(String[] inputArguments, boolean processWorldEdit, boolean requireLoaded) {
String[] argumentArray = inputArguments.clone();
int world_id = 0;
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim();
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

String inputProcessed = argument.toLowerCase(Locale.ROOT);
if (inputProcessed.equals("r:") || inputProcessed.equals("radius:")) {
next = 2;
}
else if (next == 2 || inputProcessed.startsWith("r:") || inputProcessed.startsWith("radius:")) {
argument = argument.replaceAll("radius:", "").replaceAll("r:", "");
inputProcessed = argument.toLowerCase(Locale.ROOT);
if ((processWorldEdit && (inputProcessed.equals("#worldedit") || inputProcessed.equals("#we"))) || inputProcessed.equals("#global") || inputProcessed.equals("global") || inputProcessed.equals("off") || inputProcessed.equals("-1") || inputProcessed.equals("none") || inputProcessed.equals("false")) {
world_id = 0;
}
else if (inputProcessed.startsWith("#")) {
world_id = Util.matchWorld(inputProcessed);
if (world_id == -1 && !requireLoaded) {
world_id = ConfigHandler.worlds.getOrDefault(argument.replaceFirst("#", ""), -1);
}
}
next = 0;
}
else {
next = 0;
}
}
count++;
}
return world_id;
}

Check notice on line 1067 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L1030-L1067

Complex Method
protected static boolean parseWorldEdit(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
boolean result = false;
Expand Down Expand Up @@ -1103,40 +1096,40 @@
return result;
}

protected static String parseWorldName(String[] inputArguments, boolean processWorldEdit) {
String[] argumentArray = inputArguments.clone();
String worldName = "";
int count = 0;
int next = 0;
for (String argument : argumentArray) {
if (count > 0) {
argument = argument.trim().toLowerCase(Locale.ROOT);
argument = argument.replaceAll("\\\\", "");
argument = argument.replaceAll("'", "");

if (argument.equals("r:") || argument.equals("radius:")) {
next = 2;
}
else if (next == 2 || argument.startsWith("r:") || argument.startsWith("radius:")) {
argument = argument.replaceAll("radius:", "");
argument = argument.replaceAll("r:", "");
if ((processWorldEdit && (argument.equals("#worldedit") || argument.equals("#we"))) || argument.equals("#global") || argument.equals("global") || argument.equals("off") || argument.equals("-1") || argument.equals("none") || argument.equals("false")) {
worldName = "";
}
else if (argument.startsWith("#")) {
worldName = argument.replaceFirst("#", "");
}
next = 0;
}
else {
next = 0;
}
}
count++;
}
return worldName;
}

Check notice on line 1132 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L1099-L1132

Complex Method
private static void validUserCheck(List<String> users, String user) {
List<String> badUsers = Arrays.asList("n", "noisy", "v", "verbose", "#v", "#verbose", "#silent", "#preview", "#preview_cancel", "#count", "#sum");
String check = user.replaceAll("[\\s'\"]", "");
Expand All @@ -1150,112 +1143,112 @@
}
}

@Override
public boolean onCommand(CommandSender user, Command command, String commandLabel, String[] argumentArray) {
String commandName = command.getName().toLowerCase(Locale.ROOT);

if (commandName.equals("core") || commandName.equals("coreprotect") || commandName.equals("co")) {
int resultc = argumentArray.length;
if (resultc > -1) {
String corecommand = "help";
if (resultc > 0) {
corecommand = argumentArray[0].toLowerCase(Locale.ROOT);
}
boolean permission = false;
if (!permission) {
if (user.hasPermission("coreprotect.rollback") && (corecommand.equals("rollback") || corecommand.equals("rb") || corecommand.equals("ro") || corecommand.equals("apply") || corecommand.equals("cancel"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.restore") && (corecommand.equals("restore") || corecommand.equals("rs") || corecommand.equals("re") || corecommand.equals("undo") || corecommand.equals("apply") || corecommand.equals("cancel"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.inspect") && (corecommand.equals("i") || corecommand.equals("inspect") || corecommand.equals("inspector"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.help") && corecommand.equals("help")) {
permission = true;
}
else if (user.hasPermission("coreprotect.purge") && corecommand.equals("purge")) {
permission = true;
}
else if (user.hasPermission("coreprotect.lookup") && (corecommand.equals("l") || corecommand.equals("lookup") || corecommand.equals("page") || corecommand.equals("near"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.lookup.near") && corecommand.equals("near")) {
permission = true;
}
else if (user.hasPermission("coreprotect.teleport") && (corecommand.equals("tp") || corecommand.equals("teleport"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.reload") && corecommand.equals("reload")) {
permission = true;
}
else if (user.hasPermission("coreprotect.status") && (corecommand.equals("status") || corecommand.equals("stats") || corecommand.equals("version"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.consumer") && corecommand.equals("consumer")) {
permission = true;
}
else if (user.hasPermission("coreprotect.networking") && corecommand.equals("network-debug")) {
permission = true;
}
}

if (corecommand.equals("rollback") || corecommand.equals("restore") || corecommand.equals("rb") || corecommand.equals("rs") || corecommand.equals("ro") || corecommand.equals("re")) {
RollbackRestoreCommand.runCommand(user, command, permission, argumentArray, null, 0, 0);
}
else if (corecommand.equals("apply")) {
ApplyCommand.runCommand(user, command, permission, argumentArray);
}
else if (corecommand.equals("cancel")) {
CancelCommand.runCommand(user, command, permission, argumentArray);
}
else if (corecommand.equals("undo")) {
UndoCommand.runCommand(user, command, permission, argumentArray);
}
else if (corecommand.equals("help")) {
HelpCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("purge")) {
PurgeCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("inspect") || corecommand.equals("i")) {
InspectCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("lookup") || corecommand.equals("l") || corecommand.equals("page")) {
LookupCommand.runCommand(user, command, permission, argumentArray);
}
else if (corecommand.equals("near")) {
LookupCommand.runCommand(user, command, permission, new String[] { "near", "r:5x5" });
}
else if (corecommand.equals("teleport") || corecommand.equals("tp")) {
TeleportCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("status") || corecommand.equals("stats") || corecommand.equals("version")) {
StatusCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("reload")) {
ReloadCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("consumer")) {
ConsumerCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("network-debug")) {
NetworkDebugCommand.runCommand(user, permission, argumentArray);
}
else {
Chat.sendMessage(user, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.COMMAND_NOT_FOUND, Color.WHITE, "/co " + corecommand));
}
}
else {
Chat.sendMessage(user, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, Color.WHITE, "/co <parameters>"));
}

if (user.isOp() && versionAlert.get(user.getName()) == null) {
String latestVersion = NetworkHandler.latestVersion();
if (latestVersion != null) {
versionAlert.put(user.getName(), true);
class updateAlert implements Runnable {

Check warning on line 1251 in src/main/java/net/coreprotect/command/CommandHandler.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/CommandHandler.java#L1146-L1251

Very Complex Method
@Override
public void run() {
try {
Expand All @@ -1269,7 +1262,7 @@
}
}
}
(new Thread(new updateAlert())).start();
(Util.THREAD_FACTORY.newThread(new updateAlert())).start();
}
}

Expand Down
52 changes: 23 additions & 29 deletions src/main/java/net/coreprotect/command/LookupCommand.java
Original file line number Diff line number Diff line change
@@ -1,37 +1,12 @@
package net.coreprotect.command;

import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Statement;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;

import com.google.common.base.Strings;

import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.database.Database;
import net.coreprotect.database.Lookup;
import net.coreprotect.database.logger.ItemLogger;
import net.coreprotect.database.lookup.BlockLookup;
import net.coreprotect.database.lookup.ChestTransactionLookup;
import net.coreprotect.database.lookup.InteractionLookup;
import net.coreprotect.database.lookup.PlayerLookup;
import net.coreprotect.database.lookup.SignMessageLookup;
import net.coreprotect.database.lookup.*;
import net.coreprotect.database.statement.UserStatement;
import net.coreprotect.language.Phrase;
import net.coreprotect.language.Selector;
Expand All @@ -41,316 +16,335 @@
import net.coreprotect.utility.ChatMessage;
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;

import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Statement;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class LookupCommand {
protected static void runCommand(CommandSender player, Command command, boolean permission, String[] args) {
int resultc = args.length;
args = CommandHandler.parsePage(args);
Location lo = CommandHandler.parseLocation(player, args);
// List<String> arg_uuids = new ArrayList<String>();
List<String> argUsers = CommandHandler.parseUsers(args);
Integer[] argRadius = CommandHandler.parseRadius(args, player, lo);
int argNoisy = CommandHandler.parseNoisy(args);
List<Integer> argAction = CommandHandler.parseAction(args);
List<Object> argBlocks = CommandHandler.parseRestricted(player, args, argAction);
Map<Object, Boolean> argExclude = CommandHandler.parseExcluded(player, args, argAction);
List<String> argExcludeUsers = CommandHandler.parseExcludedUsers(player, args);
String ts = CommandHandler.parseTimeString(args);
long[] argTime = CommandHandler.parseTime(args);
long startTime = argTime[0];
long endTime = argTime[1];
int argWid = CommandHandler.parseWorld(args, true, true);
int parseRows = CommandHandler.parseRows(args);
boolean count = CommandHandler.parseCount(args);
boolean worldedit = CommandHandler.parseWorldEdit(args);
boolean forceglobal = CommandHandler.parseForceGlobal(args);
boolean pageLookup = false;

if (argBlocks == null || argExclude == null || argExcludeUsers == null) {
return;
}

if (args[0].toLowerCase(Locale.ROOT).equals("page") && (args.length != 2 || !args[1].equals(args[1].replaceAll("[^0-9]", "")))) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, Color.WHITE, "/co page <page>"));
return;
}

int argExcluded = argExclude.size();
int argRestricted = argBlocks.size();

/* check for invalid block/entity combinations (include) */
boolean hasBlock = false;
boolean hasEntity = false;
for (Object arg : argBlocks) {
if (arg instanceof Material) {
hasBlock = true;
}
else if (arg instanceof EntityType) {
hasEntity = true;
if (argAction.size() == 0) {
argAction.add(3);
}
else if (!argAction.contains(3)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_INCLUDE_COMBO));
return;
}
}
}

/* check for invalid block/entity combinations (exclude) */
for (Object arg : argExclude.keySet()) {
if (arg instanceof Material) {
hasBlock = true;
}
else if (arg instanceof EntityType) {
hasEntity = true;
if (argAction.size() == 0) {
argAction.add(3);
}
else if (!argAction.contains(3)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_INCLUDE_COMBO));
return;
}
}
}

if (hasBlock && hasEntity) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_INCLUDE_COMBO));
return;
}

if (argWid == -1) {
String worldName = CommandHandler.parseWorldName(args, true);
Chat.sendMessage(player, new ChatMessage(Phrase.build(Phrase.WORLD_NOT_FOUND, worldName)).build());
return;
}

int type = 0;
if (ConfigHandler.lookupType.get(player.getName()) != null) {
type = ConfigHandler.lookupType.get(player.getName());
}
if (type == 0 && resultc > 1) {
type = 4;
}
else if (resultc > 2) {
type = 4;
}
else if (resultc > 1) {
pageLookup = true;
String dat = args[1];
if (dat.contains(":")) {
String[] split = dat.split(":");
String check1 = split[0].replaceAll("[^a-zA-Z_]", "");
String check2 = "";
if (split.length > 1) {
check2 = split[1].replaceAll("[^a-zA-Z_]", "");
}
if (check1.length() > 0 || check2.length() > 0) {
type = 4;
pageLookup = false;
}
}
else {
String check1 = dat.replaceAll("[^a-zA-Z_]", "");
if (check1.length() > 0) {
type = 4;
pageLookup = false;
}
}
}
if (argAction.contains(6) || argAction.contains(7) || argAction.contains(8) || argAction.contains(9) || argAction.contains(10)) {
pageLookup = true;
}

if (!permission) {
if (!pageLookup || !player.hasPermission("coreprotect.inspect")) {
Chat.sendMessage(player, new ChatMessage(Phrase.build(Phrase.NO_PERMISSION)).build());
return;
}
}
if (ConfigHandler.converterRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.UPGRADE_IN_PROGRESS));
return;
}
if (ConfigHandler.purgeRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_IN_PROGRESS));
return;
}
if (resultc < 2) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co l <params>"));
return;
}
if (argAction.contains(-1)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_ACTION));
return;
}
if (worldedit && argRadius == null) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_SELECTION, "WorldEdit"));
return;
}
if (argRadius != null && argRadius[0] == -1) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_RADIUS));
return;
}
if (ConfigHandler.lookupThrottle.get(player.getName()) != null) {
Object[] lookupThrottle = ConfigHandler.lookupThrottle.get(player.getName());
if ((boolean) lookupThrottle[0] || ((System.currentTimeMillis() - (long) lookupThrottle[1])) < 50) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
return;
}
}
boolean allPermission = false;
if (args[0].equals("near") && player.hasPermission("coreprotect.lookup.near")) {
allPermission = true;
}
if (!allPermission) {
if (!pageLookup && (argAction.size() == 0 || (argAction.size() == 1 && (argAction.contains(0) || argAction.contains(1)))) && !player.hasPermission("coreprotect.lookup.block")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(2) && !player.hasPermission("coreprotect.lookup.click")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(3) && !player.hasPermission("coreprotect.lookup.kill")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(4) && !argAction.contains(11) && !player.hasPermission("coreprotect.lookup.container")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(6) && !player.hasPermission("coreprotect.lookup.chat")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(7) && !player.hasPermission("coreprotect.lookup.command")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(8) && !player.hasPermission("coreprotect.lookup.session")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(9) && !player.hasPermission("coreprotect.lookup.username")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(10) && !player.hasPermission("coreprotect.lookup.sign")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(11) && !argAction.contains(4) && !player.hasPermission("coreprotect.lookup.item")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(4) && argAction.contains(11) && !player.hasPermission("coreprotect.lookup.inventory")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
}
if (argAction.contains(6) || argAction.contains(7) || argAction.contains(8) || argAction.contains(9) || argAction.contains(10)) {
if (argAction.contains(9) && (argRadius != null || argWid > 0 || worldedit)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INCOMPATIBLE_ACTION, "r:"));
return;
}
if (argBlocks.size() > 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INCOMPATIBLE_ACTION, "i:"));
return;
}
if (argExclude.size() > 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INCOMPATIBLE_ACTION, "e:"));
return;
}
}

if (startTime <= 0 && !pageLookup && type == 4 && (argBlocks.size() > 0 || argUsers.size() > 0)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_LOOKUP_TIME, Selector.FIRST));
return;
}

if (argAction.contains(4) && argAction.contains(11)) { // a:inventory
if (argUsers.size() == 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_ACTION_USER));
return;
}

argExclude.put(Material.FIRE, false);
argExclude.put(Material.WATER, false);
argExclude.put(Material.FARMLAND, false);
argExcludeUsers.add("#hopper");
}

if (type == 1) {
boolean defaultRe = true;
int p = 0;
int re = 7;
if (parseRows > 0) {
re = parseRows;
}
if (resultc > 1) {
String pages = args[1];
if (pages.contains(":")) {
String[] data = pages.split(":");
pages = data[0];
String results = "";
if (data.length > 1) {
results = data[1];
}
results = results.replaceAll("[^0-9]", "");
if (results.length() > 0 && results.length() < 10) {
int r = Integer.parseInt(results);
if (r > 0) {
re = r;
defaultRe = false;
}
}
}
pages = pages.replaceAll("[^0-9]", "");
if (pages.length() > 0 && pages.length() < 10) {
int pa = Integer.parseInt(pages);
if (pa > 0) {
p = pa;
}
}
}

if (re > 1000) {
re = 1000;
}
if (re > 100 && !(player instanceof ConsoleCommandSender)) {
re = 100;
}

if (p <= 0) {
p = 1;
}
String lcommand = ConfigHandler.lookupCommand.get(player.getName());
String[] data = lcommand.split("\\.");
int x = Integer.parseInt(data[0]);
int y = Integer.parseInt(data[1]);
int z = Integer.parseInt(data[2]);
int wid = Integer.parseInt(data[3]);
int x2 = Integer.parseInt(data[4]);
int y2 = Integer.parseInt(data[5]);
int z2 = Integer.parseInt(data[6]);
if (defaultRe) {
re = Integer.parseInt(data[7]);
}

String bc = x + "." + y + "." + z + "." + wid + "." + x2 + "." + y2 + "." + z2 + "." + re;
ConfigHandler.lookupCommand.put(player.getName(), bc);

String world = Util.getWorldName(wid);
double dx = 0.5 * (x + x2);
double dy = 0.5 * (y + y2);
double dz = 0.5 * (z + z2);
final Location location = new Location(Bukkit.getServer().getWorld(world), dx, dy, dz);
final CommandSender player2 = player;
final int p2 = p;
final int finalLimit = re;

class BasicThread implements Runnable {

Check failure on line 347 in src/main/java/net/coreprotect/command/LookupCommand.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/LookupCommand.java#L40-L347

Very Complex Method
@Override
public void run() {
try (Connection connection = Database.getConnection(true)) {
Expand All @@ -375,7 +369,7 @@
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
}
else if (type == 2 || type == 3 || type == 7 || type == 8) {
Expand Down Expand Up @@ -495,7 +489,7 @@
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
}
else if (type == 4 || type == 5) {
Expand Down Expand Up @@ -716,410 +710,410 @@
final boolean finalCount = count;

class BasicThread2 implements Runnable {
@Override
public void run() {
try (Connection connection = Database.getConnection(true)) {
ConfigHandler.lookupThrottle.put(player2.getName(), new Object[] { true, System.currentTimeMillis() });

List<String> uuidList = new ArrayList<>();
Location location = finalLocation;
boolean exists = false;
String bc = finalX + "." + finalY + "." + finalZ + "." + finalWid + "." + finalTimeStart + "." + finalTimeEnd + "." + noisy + "." + excluded + "." + restricted + "." + finalArgWid + "." + displayResults;
ConfigHandler.lookupCommand.put(player2.getName(), bc);
ConfigHandler.lookupPage.put(player2.getName(), page);
ConfigHandler.lookupTime.put(player2.getName(), rtime);
ConfigHandler.lookupType.put(player2.getName(), 5);
ConfigHandler.lookupElist.put(player2.getName(), elist);
ConfigHandler.lookupEUserlist.put(player2.getName(), euserlist);
ConfigHandler.lookupBlist.put(player2.getName(), blist);
ConfigHandler.lookupUlist.put(player2.getName(), rollbackusers2);
ConfigHandler.lookupAlist.put(player2.getName(), finalArgAction);
ConfigHandler.lookupRadius.put(player2.getName(), radius);

if (connection != null) {
Statement statement = connection.createStatement();
String baduser = "";
for (String check : rollbackusers2) {
if ((!check.equals("#global") && !check.equals("#container")) || finalArgAction.contains(9)) {
exists = PlayerLookup.playerExists(connection, check);
if (!exists) {
baduser = check;
break;
}
else if (finalArgAction.contains(9)) {
if (ConfigHandler.uuidCache.get(check.toLowerCase(Locale.ROOT)) != null) {
String uuid = ConfigHandler.uuidCache.get(check.toLowerCase(Locale.ROOT));
uuidList.add(uuid);
}
}
}
else {
exists = true;
}
}
if (exists) {
for (String check : euserlist) {
if (!check.equals("#global") && !check.equals("#hopper")) {
exists = PlayerLookup.playerExists(connection, check);
if (!exists) {
baduser = check;
break;
}
}
else if (check.equals("#global")) {
baduser = "#global";
exists = false;
}
}
}

if (exists) {
List<String> userList = new ArrayList<>();
if (!finalArgAction.contains(9)) {
userList = rollbackusers2;
}

int unixtimestamp = (int) (System.currentTimeMillis() / 1000L);
boolean restrict_world = false;
if (radius != null) {
restrict_world = true;
}
if (location == null) {
restrict_world = false;
}
if (finalArgWid > 0) {
restrict_world = true;
location = new Location(Bukkit.getServer().getWorld(Util.getWorldName(finalArgWid)), finalX, finalY, finalZ);
}
else if (location != null) {
location = new Location(Bukkit.getServer().getWorld(Util.getWorldName(finalWid)), finalX, finalY, finalZ);
}

Long[] rowData = new Long[] { 0L, 0L, 0L, 0L };
long rowMax = (long) page * displayResults;
long pageStart = rowMax - displayResults;
long rows = 0L;
boolean checkRows = true;

if (typeLookup == 5 && page > 1) {
rowData = ConfigHandler.lookupRows.get(player2.getName());
rows = rowData[3];

if (pageStart < rows) {
checkRows = false;
}
}

if (checkRows) {
rows = Lookup.countLookupRows(statement, player2, uuidList, userList, blist, elist, euserlist, finalArgAction, location, radius, rowData, finalTimeStart, finalTimeEnd, restrict_world, true);
rowData[3] = rows;
ConfigHandler.lookupRows.put(player2.getName(), rowData);
}
if (finalCount) {
String row_format = NumberFormat.getInstance().format(rows);
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.LOOKUP_ROWS_FOUND, row_format, (rows == 1 ? Selector.FIRST : Selector.SECOND)));
}
else if (pageStart < rows) {
List<String[]> lookupList = Lookup.performPartialLookup(statement, player2, uuidList, userList, blist, elist, euserlist, finalArgAction, location, radius, rowData, finalTimeStart, finalTimeEnd, (int) pageStart, displayResults, restrict_world, true);

Chat.sendMessage(player2, Color.WHITE + "----- " + Color.DARK_AQUA + Phrase.build(Phrase.LOOKUP_HEADER, "CoreProtect" + Color.WHITE + " | " + Color.DARK_AQUA) + Color.WHITE + " -----");
if (finalArgAction.contains(6) || finalArgAction.contains(7)) { // Chat/command
for (String[] data : lookupList) {
String time = data[0];
String dplayer = data[1];
String message = data[2];
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
Chat.sendComponent(player2, timeago + " " + Color.WHITE + "- " + Color.DARK_AQUA + dplayer + ": " + Color.WHITE, message);
if (PluginChannelHandshakeListener.getInstance().isPluginChannelPlayer(player2)) {
int wid = Integer.parseInt(data[3]);
int x = Integer.parseInt(data[4]);
int y = Integer.parseInt(data[5]);
int z = Integer.parseInt(data[6]);
PluginChannelListener.getInstance().sendMessageData(player2, Integer.parseInt(time), dplayer, message, false, x, y, z, wid);
}
}
}
else if (finalArgAction.contains(8)) { // login/logouts
for (String[] data : lookupList) {
String time = data[0];
String dplayer = data[1];
int wid = Integer.parseInt(data[2]);
int x = Integer.parseInt(data[3]);
int y = Integer.parseInt(data[4]);
int z = Integer.parseInt(data[5]);
int action = Integer.parseInt(data[6]);
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
int timeLength = 50 + (Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 6);
String leftPadding = Color.BOLD + Strings.padStart("", 10, ' ');
if (timeLength % 4 == 0) {
leftPadding = Strings.padStart("", timeLength / 4, ' ');
}
else {
leftPadding = leftPadding + Color.WHITE + Strings.padStart("", (timeLength - 50) / 4, ' ');
}

String tag = (action != 0 ? Color.GREEN + "+" : Color.RED + "-");
Chat.sendComponent(player2, timeago + " " + tag + " " + Color.DARK_AQUA + Phrase.build(Phrase.LOOKUP_LOGIN, Color.DARK_AQUA + dplayer + Color.WHITE, (action != 0 ? Selector.FIRST : Selector.SECOND)));
Chat.sendComponent(player2, Color.WHITE + leftPadding + Color.GREY + "^ " + Util.getCoordinates(command.getName(), wid, x, y, z, true, true) + "");
PluginChannelListener.getInstance().sendInfoData(player2, Integer.parseInt(time), Phrase.LOOKUP_LOGIN, (action != 0 ? Selector.FIRST : Selector.SECOND), dplayer, -1, x, y, z, wid);
}
}
else if (finalArgAction.contains(9)) { // username-changes
for (String[] data : lookupList) {
String time = data[0];
String user = ConfigHandler.uuidCacheReversed.get(data[1]);
String username = data[2];
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
Chat.sendComponent(player2, timeago + " " + Color.WHITE + "- " + Phrase.build(Phrase.LOOKUP_USERNAME, Color.DARK_AQUA + user + Color.WHITE, Color.DARK_AQUA + username + Color.WHITE));
PluginChannelListener.getInstance().sendUsernameData(player2, Integer.parseInt(time), user, username);
}
}
else if (finalArgAction.contains(10)) { // sign messages
for (String[] data : lookupList) {
String time = data[0];
String dplayer = data[1];
int wid = Integer.parseInt(data[2]);
int x = Integer.parseInt(data[3]);
int y = Integer.parseInt(data[4]);
int z = Integer.parseInt(data[5]);
String message = data[6];
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
int timeLength = 50 + (Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 6);
String leftPadding = Color.BOLD + Strings.padStart("", 10, ' ');
if (timeLength % 4 == 0) {
leftPadding = Strings.padStart("", timeLength / 4, ' ');
}
else {
leftPadding = leftPadding + Color.WHITE + Strings.padStart("", (timeLength - 50) / 4, ' ');
}

Chat.sendComponent(player2, timeago + " " + Color.WHITE + "- " + Color.DARK_AQUA + dplayer + ": " + Color.WHITE, message);
Chat.sendComponent(player2, Color.WHITE + leftPadding + Color.GREY + "^ " + Util.getCoordinates(command.getName(), wid, x, y, z, true, true) + "");
PluginChannelListener.getInstance().sendMessageData(player2, Integer.parseInt(time), dplayer, message, true, x, y, z, wid);
}
}
else if (finalArgAction.contains(4) && finalArgAction.contains(11)) { // inventory transactions
for (String[] data : lookupList) {
String time = data[0];
String dplayer = data[1];
int dtype = Integer.parseInt(data[5]);
int ddata = Integer.parseInt(data[6]);
int daction = Integer.parseInt(data[7]);
int amount = Integer.parseInt(data[10]);
int wid = Integer.parseInt(data[9]);
int x = Integer.parseInt(data[2]);
int y = Integer.parseInt(data[3]);
int z = Integer.parseInt(data[4]);
String rbd = ((Integer.parseInt(data[8]) == 2 || Integer.parseInt(data[8]) == 3) ? Color.STRIKETHROUGH : "");
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
Material blockType = Util.itemFilter(Util.getType(dtype), (Integer.parseInt(data[13]) == 0));
String dname = Util.nameFilter(blockType.name().toLowerCase(Locale.ROOT), ddata);
byte[] metadata = data[11] == null ? null : data[11].getBytes(StandardCharsets.ISO_8859_1);
String tooltip = Util.getEnchantments(metadata, dtype, amount);

String selector = Selector.FIRST;
String tag = Color.WHITE + "-";
if (daction == 2 || daction == 3) { // LOOKUP_ITEM
selector = (daction != 2 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 2 ? Color.GREEN + "+" : Color.RED + "-");
}
else if (daction == 4 || daction == 5) { // LOOKUP_STORAGE
selector = (daction == 4 ? Selector.FIRST : Selector.SECOND);
tag = (daction == 4 ? Color.GREEN + "+" : Color.RED + "-");
}
else if (daction == 6 || daction == 7) { // LOOKUP_PROJECTILE
selector = Selector.SECOND;
tag = Color.RED + "-";
}
else if (daction == ItemLogger.ITEM_BREAK || daction == ItemLogger.ITEM_DESTROY || daction == ItemLogger.ITEM_CREATE) {
selector = (daction == ItemLogger.ITEM_CREATE ? Selector.FIRST : Selector.SECOND);
tag = (daction == ItemLogger.ITEM_CREATE ? Color.GREEN + "+" : Color.RED + "-");
}
else if (daction == ItemLogger.ITEM_SELL || daction == ItemLogger.ITEM_BUY) { // LOOKUP_TRADE
selector = (daction == ItemLogger.ITEM_BUY ? Selector.FIRST : Selector.SECOND);
tag = (daction == ItemLogger.ITEM_BUY ? Color.GREEN + "+" : Color.RED + "-");
}
else { // LOOKUP_CONTAINER
selector = (daction == 0 ? Selector.FIRST : Selector.SECOND);
tag = (daction == 0 ? Color.GREEN + "+" : Color.RED + "-");
}

Chat.sendComponent(player2, timeago + " " + tag + " " + Phrase.build(Phrase.LOOKUP_CONTAINER, Color.DARK_AQUA + rbd + dplayer + Color.WHITE + rbd, "x" + amount, Util.createTooltip(Color.DARK_AQUA + rbd + dname, tooltip) + Color.WHITE, selector));
PluginChannelListener.getInstance().sendData(player2, Integer.parseInt(time), Phrase.LOOKUP_CONTAINER, selector, dplayer, dname, amount, x, y, z, wid, rbd, true, tag.contains("+"));
}
}
else {
for (String[] data : lookupList) {
int drb = Integer.parseInt(data[8]);
String rbd = "";
if (drb == 1 || drb == 3) {
rbd = Color.STRIKETHROUGH;
}

String time = data[0];
String dplayer = data[1];
int x = Integer.parseInt(data[2]);
int y = Integer.parseInt(data[3]);
int z = Integer.parseInt(data[4]);
int dtype = Integer.parseInt(data[5]);
int ddata = Integer.parseInt(data[6]);
int daction = Integer.parseInt(data[7]);
int wid = Integer.parseInt(data[9]);
int amount = Integer.parseInt(data[10]);
String tag = Color.WHITE + "-";

String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
int timeLength = 50 + (Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 6);
String leftPadding = Color.BOLD + Strings.padStart("", 10, ' ');
if (timeLength % 4 == 0) {
leftPadding = Strings.padStart("", timeLength / 4, ' ');
}
else {
leftPadding = leftPadding + Color.WHITE + Strings.padStart("", (timeLength - 50) / 4, ' ');
}

String dname = "";
boolean isPlayer = false;
if (daction == 3 && !finalArgAction.contains(11) && amount == -1) {
if (dtype == 0) {
if (ConfigHandler.playerIdCacheReversed.get(ddata) == null) {
UserStatement.loadName(connection, ddata);
}
dname = ConfigHandler.playerIdCacheReversed.get(ddata);
isPlayer = true;
}
else {
dname = Util.getEntityType(dtype).name();
}
}
else {
dname = Util.getType(dtype).name().toLowerCase(Locale.ROOT);
dname = Util.nameFilter(dname, ddata);
}
if (dname.length() > 0 && !isPlayer) {
dname = "minecraft:" + dname.toLowerCase(Locale.ROOT) + "";
}

// Hide "minecraft:" for now.
if (dname.contains("minecraft:")) {
String[] blockNameSplit = dname.split(":");
dname = blockNameSplit[1];
}

// Functions.sendMessage(player2, timeago+" " + ChatColors.WHITE + "- " + ChatColors.DARK_AQUA+rbd+""+dplayer+" " + ChatColors.WHITE+rbd+""+a+" " + ChatColors.DARK_AQUA+rbd+"#"+dtype+ChatColors.WHITE + ". " + ChatColors.GREY + "(x"+x+"/y"+y+"/z"+z+")");

Phrase phrase = Phrase.LOOKUP_BLOCK;
String selector = Selector.FIRST;
String action = "a:block";
if (finalArgAction.contains(4) || finalArgAction.contains(5) || finalArgAction.contains(11) || amount > -1) {
byte[] metadata = data[11] == null ? null : data[11].getBytes(StandardCharsets.ISO_8859_1);
String tooltip = Util.getEnchantments(metadata, dtype, amount);

if (daction == 2 || daction == 3) {
phrase = Phrase.LOOKUP_ITEM; // {picked up|dropped}
selector = (daction != 2 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 2 ? Color.GREEN + "+" : Color.RED + "-");
action = "a:item";
}
else if (daction == 4 || daction == 5) {
phrase = Phrase.LOOKUP_STORAGE; // {deposited|withdrew}
selector = (daction != 4 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 4 ? Color.RED + "-" : Color.GREEN + "+");
action = "a:item";
}
else if (daction == 6 || daction == 7) {
phrase = Phrase.LOOKUP_PROJECTILE; // {threw|shot}
selector = (daction != 7 ? Selector.FIRST : Selector.SECOND);
tag = Color.RED + "-";
action = "a:item";
}
else {
phrase = Phrase.LOOKUP_CONTAINER; // {added|removed}
selector = (daction != 0 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 0 ? Color.GREEN + "+" : Color.RED + "-");
action = "a:container";
}

Chat.sendComponent(player2, timeago + " " + tag + " " + Phrase.build(phrase, Color.DARK_AQUA + rbd + dplayer + Color.WHITE + rbd, "x" + amount, Util.createTooltip(Color.DARK_AQUA + rbd + dname, tooltip) + Color.WHITE, selector));
PluginChannelListener.getInstance().sendData(player2, Integer.parseInt(time), phrase, selector, dplayer, dname, (tag.contains("+") ? 1 : -1), x, y, z, wid, rbd, action.contains("container"), tag.contains("+"));
}
else {
if (daction == 2 || daction == 3) {
phrase = Phrase.LOOKUP_INTERACTION; // {clicked|killed}
selector = (daction != 3 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 3 ? Color.WHITE + "-" : Color.RED + "-");
action = (daction == 2 ? "a:click" : "a:kill");
}
else {
phrase = Phrase.LOOKUP_BLOCK; // {placed|broke}
selector = (daction != 0 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 0 ? Color.GREEN + "+" : Color.RED + "-");
}

Chat.sendComponent(player2, timeago + " " + tag + " " + Phrase.build(phrase, Color.DARK_AQUA + rbd + dplayer + Color.WHITE + rbd, Color.DARK_AQUA + rbd + dname + Color.WHITE, selector));
PluginChannelListener.getInstance().sendData(player2, Integer.parseInt(time), phrase, selector, dplayer, dname, (tag.contains("+") ? 1 : -1), x, y, z, wid, rbd, false, tag.contains("+"));
}

action = (finalArgAction.size() == 0 ? " (" + action + ")" : "");
Chat.sendComponent(player2, Color.WHITE + leftPadding + Color.GREY + "^ " + Util.getCoordinates(command.getName(), wid, x, y, z, true, true) + Color.GREY + Color.ITALIC + action);
}
}
if (rows > displayResults) {
int total_pages = (int) Math.ceil(rows / (displayResults + 0.0));
if (finalArgAction.contains(6) || finalArgAction.contains(7) || finalArgAction.contains(9) || (finalArgAction.contains(4) && finalArgAction.contains(11))) {
Chat.sendMessage(player2, "-----");
}
Chat.sendComponent(player2, Util.getPageNavigation(command.getName(), page, total_pages));
}
}
else if (rows > 0) {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_RESULTS_PAGE, Selector.FIRST));
}
else {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_RESULTS));
}
}
else {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.USER_NOT_FOUND, baduser));
}
statement.close();
}
else {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
}
}
catch (Exception e) {
e.printStackTrace();
}

ConfigHandler.lookupThrottle.put(player2.getName(), new Object[] { false, System.currentTimeMillis() });
}
}
Runnable runnable = new BasicThread2();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
else {
// Functions.sendMessage(player, ChatColors.RED + "You did not specify a lookup radius.");
if (argUsers.size() == 0 && argBlocks.size() == 0 && (argWid > 0 || forceglobal)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_LOOKUP_USER, Selector.FIRST));
return;
}
else if (argUsers.size() == 0 && argBlocks.size() == 0 && argRadius == null) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_LOOKUP_USER, Selector.SECOND));
return;
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co l <params>"));
}
}
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co l <params>"));
}
}

Check warning on line 1118 in src/main/java/net/coreprotect/command/LookupCommand.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/LookupCommand.java#L713-L1118

Very Complex Method
}
27 changes: 13 additions & 14 deletions src/main/java/net/coreprotect/command/PurgeCommand.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
package net.coreprotect.command;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;

import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.Consumer;
Expand All @@ -24,369 +11,381 @@
import net.coreprotect.utility.ChatMessage;
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;

public class PurgeCommand extends Consumer {

protected static void runCommand(final CommandSender player, boolean permission, String[] args) {
int resultc = args.length;
Location location = CommandHandler.parseLocation(player, args);
final Integer[] argRadius = CommandHandler.parseRadius(args, player, location);
final long[] argTime = CommandHandler.parseTime(args);
final int argWid = CommandHandler.parseWorld(args, false, false);
final List<Integer> argAction = CommandHandler.parseAction(args);
final List<Integer> supportedActions = Arrays.asList();
long startTime = argTime[1] > 0 ? argTime[0] : 0;
long endTime = argTime[1] > 0 ? argTime[1] : argTime[0];

if (ConfigHandler.converterRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.UPGRADE_IN_PROGRESS));
return;
}
if (ConfigHandler.purgeRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_IN_PROGRESS));
return;
}
if (!permission) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (resultc <= 1) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co purge t:<time>"));
return;
}
if (endTime <= 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co purge t:<time>"));
return;
}
if (argRadius != null) {
Chat.sendMessage(player, new ChatMessage(Phrase.build(Phrase.INVALID_WORLD)).build());
return;
}
if (argWid == -1) {
String worldName = CommandHandler.parseWorldName(args, false);
Chat.sendMessage(player, new ChatMessage(Phrase.build(Phrase.WORLD_NOT_FOUND, worldName)).build());
return;
}
for (int action : argAction) {
if (!supportedActions.contains(action)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.ACTION_NOT_SUPPORTED));
// Functions.sendMessage(player, new ChatMessage("Please specify a valid purge action.").build());
return;
}
}
if (player instanceof Player && endTime < 2592000) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_MINIMUM_TIME, "30", Selector.FIRST)); // 30 days
return;
}
else if (endTime < 86400) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_MINIMUM_TIME, "24", Selector.SECOND)); // 24 hours
return;
}

boolean optimizeCheck = false;
for (String arg : args) {
if (arg.trim().equalsIgnoreCase("#optimize")) {
optimizeCheck = true;
break;
}
}
final boolean optimize = optimizeCheck;

class BasicThread implements Runnable {

Check notice on line 95 in src/main/java/net/coreprotect/command/PurgeCommand.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/PurgeCommand.java#L29-L95

Complex Method
@Override
public void run() {
try {
long timestamp = (System.currentTimeMillis() / 1000L);
long timeStart = startTime > 0 ? (timestamp - startTime) : 0;
long timeEnd = timestamp - endTime;
long removed = 0;

Connection connection = null;
for (int i = 0; i <= 5; i++) {
connection = Database.getConnection(false, 500);
if (connection != null) {
break;
}
Thread.sleep(1000);
}

if (connection == null) {
Chat.sendGlobalMessage(player, Phrase.build(Phrase.DATABASE_BUSY));
return;
}

if (argWid > 0) {
String worldName = CommandHandler.parseWorldName(args, false);
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_STARTED, worldName));
}
else {
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_STARTED, "#global"));
}
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_NOTICE_1));
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_NOTICE_2));

ConfigHandler.purgeRunning = true;
while (!Consumer.pausedSuccess) {
Thread.sleep(1);
}
Consumer.isPaused = true;

String query = "";
PreparedStatement preparedStmt = null;
boolean abort = false;
String purgePrefix = "tmp_" + ConfigHandler.prefix;

if (!Config.getGlobal().MYSQL) {
query = "ATTACH DATABASE '" + ConfigHandler.path + ConfigHandler.sqlite + ".tmp' AS tmp_db";
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
purgePrefix = "tmp_db." + ConfigHandler.prefix;
}

Integer[] lastVersion = Patch.getDatabaseVersion(connection, true);
boolean newVersion = Util.newVersion(lastVersion, Util.getInternalPluginVersion());
if (newVersion && !ConfigHandler.EDITION_BRANCH.contains("-dev")) {
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_FAILED));
Consumer.isPaused = false;
ConfigHandler.purgeRunning = false;
return;
}

if (!Config.getGlobal().MYSQL) {
for (String table : ConfigHandler.databaseTables) {
try {
query = "DROP TABLE IF EXISTS " + purgePrefix + table + "";
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
}

Database.createDatabaseTables(purgePrefix, true);
}

List<String> purgeTables = Arrays.asList("sign", "container", "item", "skull", "session", "chat", "command", "entity", "block");
List<String> worldTables = Arrays.asList("sign", "container", "item", "session", "chat", "command", "block");
List<String> excludeTables = Arrays.asList("database_lock"); // don't insert data into these tables
for (String table : ConfigHandler.databaseTables) {
String tableName = table.replaceAll("_", " ");
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_PROCESSING, tableName));

if (!Config.getGlobal().MYSQL) {
String columns = "";
ResultSet rs = connection.createStatement().executeQuery("SELECT * FROM " + purgePrefix + table);
ResultSetMetaData resultSetMetaData = rs.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String name = resultSetMetaData.getColumnName(i);
if (columns.length() == 0) {
columns = name;
}
else {
columns = columns + "," + name;
}
}
rs.close();

boolean error = false;
if (!excludeTables.contains(table)) {
try {
String timeLimit = "";
if (purgeTables.contains(table)) {
if (argWid > 0 && worldTables.contains(table)) {
timeLimit = " WHERE (wid = '" + argWid + "' AND (time >= '" + timeEnd + "' OR time < '" + timeStart + "')) OR wid != '" + argWid + "'";
}
else if (argWid == 0) {
timeLimit = " WHERE (time >= '" + timeEnd + "' OR time < '" + timeStart + "')";
}
}
query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + ConfigHandler.prefix + table + timeLimit;
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
}
catch (Exception e) {
error = true;
e.printStackTrace();
}
}

if (error) {
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_ERROR, tableName));
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_REPAIRING));

try {
query = "DELETE FROM " + purgePrefix + table;
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
}
catch (Exception e) {
e.printStackTrace();
}

try {
query = "REINDEX " + ConfigHandler.prefix + table;
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
}
catch (Exception e) {
e.printStackTrace();
}

try {
String index = " NOT INDEXED";
query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + ConfigHandler.prefix + table + index;
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
}
catch (Exception e) {
e.printStackTrace();
abort = true;
break;
}

try {
boolean purge = purgeTables.contains(table);

String worldRestriction = "";
if (argWid > 0 && worldTables.contains(table)) {
worldRestriction = " AND wid = '" + argWid + "'";
}
else if (argWid > 0) {
purge = false;
}

if (purge) {
query = "DELETE FROM " + purgePrefix + table + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction;
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}

if (purgeTables.contains(table)) {
int oldCount = 0;
try {
query = "SELECT COUNT(*) as count FROM " + ConfigHandler.prefix + table + " LIMIT 0, 1";
preparedStmt = connection.prepareStatement(query);
ResultSet resultSet = preparedStmt.executeQuery();
while (resultSet.next()) {
oldCount = resultSet.getInt("count");
}
resultSet.close();
preparedStmt.close();
}
catch (Exception e) {
e.printStackTrace();
}

int new_count = 0;
try {
query = "SELECT COUNT(*) as count FROM " + purgePrefix + table + " LIMIT 0, 1";
preparedStmt = connection.prepareStatement(query);
ResultSet resultSet = preparedStmt.executeQuery();
while (resultSet.next()) {
new_count = resultSet.getInt("count");
}
resultSet.close();
preparedStmt.close();
}
catch (Exception e) {
e.printStackTrace();
}

removed = removed + (oldCount - new_count);
}
}

if (Config.getGlobal().MYSQL) {
try {
boolean purge = purgeTables.contains(table);

String worldRestriction = "";
if (argWid > 0 && worldTables.contains(table)) {
worldRestriction = " AND wid = '" + argWid + "'";
}
else if (argWid > 0) {
purge = false;
}

if (purge) {
query = "DELETE FROM " + ConfigHandler.prefix + table + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction;
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
removed = removed + preparedStmt.getUpdateCount();
preparedStmt.close();
}
}
catch (Exception e) {
if (!ConfigHandler.serverRunning) {
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_FAILED));
return;
}

e.printStackTrace();
}
}
}

if (Config.getGlobal().MYSQL && optimize) {
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_OPTIMIZING));
for (String table : ConfigHandler.databaseTables) {
query = "OPTIMIZE LOCAL TABLE " + ConfigHandler.prefix + table + "";
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
}
}

connection.close();

if (abort) {
if (!Config.getGlobal().MYSQL) {
(new File(ConfigHandler.path + ConfigHandler.sqlite + ".tmp")).delete();
}
ConfigHandler.loadDatabase();
Chat.sendGlobalMessage(player, Color.RED + Phrase.build(Phrase.PURGE_ABORTED));
Consumer.isPaused = false;
ConfigHandler.purgeRunning = false;
return;
}

if (!Config.getGlobal().MYSQL) {
(new File(ConfigHandler.path + ConfigHandler.sqlite)).delete();
(new File(ConfigHandler.path + ConfigHandler.sqlite + ".tmp")).renameTo(new File(ConfigHandler.path + ConfigHandler.sqlite));
}

ConfigHandler.loadDatabase();

Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_SUCCESS));
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_ROWS, NumberFormat.getInstance().format(removed), (removed == 1 ? Selector.FIRST : Selector.SECOND)));
}
catch (Exception e) {
Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_FAILED));
e.printStackTrace();
}

Consumer.isPaused = false;
ConfigHandler.purgeRunning = false;
}
}

Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
}

Check notice on line 390 in src/main/java/net/coreprotect/command/PurgeCommand.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/PurgeCommand.java#L96-L390

Complex Method
}
8 changes: 4 additions & 4 deletions src/main/java/net/coreprotect/command/ReloadCommand.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package net.coreprotect.command;

import org.bukkit.command.CommandSender;

import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.Consumer;
import net.coreprotect.language.Phrase;
import net.coreprotect.thread.NetworkHandler;
import net.coreprotect.utility.Chat;
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
import org.bukkit.command.CommandSender;

public class ReloadCommand {
protected static void runCommand(final CommandSender player, boolean permission, String[] args) {
Expand Down Expand Up @@ -44,7 +44,7 @@ public void run() {
ConfigHandler.performInitialization(false);
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.RELOAD_SUCCESS));

Thread networkHandler = new Thread(new NetworkHandler(false, false));
Thread networkHandler = Util.THREAD_FACTORY.newThread(new NetworkHandler(false, false));
networkHandler.start();
}
catch (Exception e) {
Expand All @@ -56,7 +56,7 @@ public void run() {
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
}
else {
Expand Down
37 changes: 18 additions & 19 deletions src/main/java/net/coreprotect/command/RollbackRestoreCommand.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package net.coreprotect.command;

import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.database.ContainerRollback;
import net.coreprotect.database.Database;
import net.coreprotect.database.Rollback;
import net.coreprotect.database.lookup.PlayerLookup;
import net.coreprotect.language.Phrase;
import net.coreprotect.language.Selector;
import net.coreprotect.utility.Chat;
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
Expand All @@ -19,472 +23,467 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;

import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.database.ContainerRollback;
import net.coreprotect.database.Database;
import net.coreprotect.database.Rollback;
import net.coreprotect.database.lookup.PlayerLookup;
import net.coreprotect.language.Phrase;
import net.coreprotect.language.Selector;
import net.coreprotect.utility.Chat;
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class RollbackRestoreCommand {
protected static void runCommand(CommandSender player, Command command, boolean permission, String[] args, Location argLocation, long forceStart, long forceEnd) {
Location lo = (argLocation != null ? argLocation : CommandHandler.parseLocation(player, args));
List<String> argUuids = new ArrayList<>();
List<String> argUsers = CommandHandler.parseUsers(args);
Integer[] argRadius = CommandHandler.parseRadius(args, player, lo);
int argNoisy = CommandHandler.parseNoisy(args);
List<Integer> argAction = CommandHandler.parseAction(args);
List<Object> argBlocks = CommandHandler.parseRestricted(player, args, argAction);
Map<Object, Boolean> argExclude = CommandHandler.parseExcluded(player, args, argAction);
List<String> argExcludeUsers = CommandHandler.parseExcludedUsers(player, args);
String ts = CommandHandler.parseTimeString(args);
long[] argTime = CommandHandler.parseTime(args);
long startTime = argTime[0];
long endTime = argTime[1];
int argWid = CommandHandler.parseWorld(args, true, true);
boolean count = CommandHandler.parseCount(args);
boolean worldedit = CommandHandler.parseWorldEdit(args);
boolean forceglobal = CommandHandler.parseForceGlobal(args);
int preview = CommandHandler.parsePreview(args);
String corecommand = args[0].toLowerCase(Locale.ROOT);

if (argBlocks == null || argExclude == null || argExcludeUsers == null) {
return;
}

/* check for invalid block/entity combinations (include) */
boolean hasBlock = false;
boolean hasEntity = false;
for (Object arg : argBlocks) {
if (arg instanceof Material) {
hasBlock = true;
}
else if (arg instanceof EntityType) {
hasEntity = true;
if (argAction.size() == 0) {
argAction.add(3);
}
else if (!argAction.contains(3)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_INCLUDE_COMBO));
return;
}
}
}

/* check for invalid block/entity combinations (exclude) */
for (Object arg : argExclude.keySet()) {
if (arg instanceof Material) {
hasBlock = true;
}
else if (arg instanceof EntityType) {
hasEntity = true;
if (argAction.size() == 0) {
argAction.add(3);
}
else if (!argAction.contains(3)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_INCLUDE_COMBO));
return;
}
}
}

if (hasBlock && hasEntity) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_INCLUDE_COMBO));
return;
}

if (count) {
LookupCommand.runCommand(player, command, permission, args);
return;
}
if (ConfigHandler.converterRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.UPGRADE_IN_PROGRESS));
return;
}
if (ConfigHandler.purgeRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_IN_PROGRESS));
return;
}
if (argWid == -1) {
String worldName = CommandHandler.parseWorldName(args, true);
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.WORLD_NOT_FOUND, worldName));
return;
}
if (preview > 0 && (!(player instanceof Player))) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PREVIEW_IN_GAME));
return;
}
if (argAction.contains(-1)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_ACTION));
return;
}
if (worldedit && argRadius == null) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_SELECTION, "WorldEdit"));
return;
}
if (argRadius != null && argRadius[0] == -1) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_RADIUS));
return;
}
if (ConfigHandler.activeRollbacks.get(player.getName()) != null) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.ROLLBACK_IN_PROGRESS));
return;
}
if (ConfigHandler.lookupThrottle.get(player.getName()) != null) {
Object[] lookupThrottle = ConfigHandler.lookupThrottle.get(player.getName());
if ((boolean) lookupThrottle[0] || ((System.currentTimeMillis() - (long) lookupThrottle[1])) < 100) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
return;
}
}
if (preview > 1 && forceStart <= 0) {
preview = 1;
}

if (permission) {
int a = 0;
if (corecommand.equals("restore") || corecommand.equals("rs") || corecommand.equals("re")) {
a = 1;
}
final int finalAction = a;

int DEFAULT_RADIUS = Config.getGlobal().DEFAULT_RADIUS;
if ((player instanceof Player || player instanceof BlockCommandSender) && argRadius == null && DEFAULT_RADIUS > 0 && !forceglobal && !argAction.contains(11)) {
Location location = lo;
int xmin = location.getBlockX() - DEFAULT_RADIUS;
int xmax = location.getBlockX() + DEFAULT_RADIUS;
int zmin = location.getBlockZ() - DEFAULT_RADIUS;
int zmax = location.getBlockZ() + DEFAULT_RADIUS;
argRadius = new Integer[] { DEFAULT_RADIUS, xmin, xmax, null, null, zmin, zmax, 0 };
}
// if (arg_radius==-2)arg_radius = -1;

int g = 1;
if (argUsers.contains("#global")) {
if (argRadius == null) {
g = 0;
}
}

if (argUsers.size() == 0 && (argWid > 0 || forceglobal) && argRadius == null) {
if (finalAction == 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_ROLLBACK_USER, Selector.FIRST));
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_ROLLBACK_USER, Selector.SECOND));
}
return;
}

if (argAction.contains(4) && argAction.contains(11)) { // a:inventory
if (argUsers.size() == 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_ACTION_USER));
return;
}

argExclude.put(Material.FIRE, false);
argExclude.put(Material.WATER, false);
argExclude.put(Material.FARMLAND, false);
argExcludeUsers.add("#hopper");
}
else if (!argAction.contains(4) && Config.getGlobal().EXCLUDE_TNT && !argExclude.containsKey(Material.TNT) && !argBlocks.contains(Material.TNT)) {
argExclude.put(Material.TNT, true);
}

if (g == 1 && (argUsers.size() > 0 || (argUsers.size() == 0 && argRadius != null))) {
Integer MAX_RADIUS = Config.getGlobal().MAX_RADIUS;
if (argRadius != null) {
int radiusValue = argRadius[0];
if (radiusValue > MAX_RADIUS && MAX_RADIUS > 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MAXIMUM_RADIUS, MAX_RADIUS.toString(), (finalAction == 0 ? Selector.SECOND : Selector.THIRD)));
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.GLOBAL_ROLLBACK, "r:#global", (finalAction == 0 ? Selector.FIRST : Selector.SECOND)));
return;
}
}
if (argAction.size() > 0) {
if (argAction.contains(4)) {
if (argUsers.contains("#global") || (argUsers.size() == 0 && argRadius == null)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_ACTION_USER));
return;
}
else if (preview > 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PREVIEW_TRANSACTION, !argAction.contains(11) ? Selector.FIRST : Selector.SECOND));
return;
}
}
if (argAction.contains(8) || (argAction.contains(11) && !argAction.contains(4)) || (!argAction.contains(0) && !argAction.contains(1) && !argAction.contains(3) && !argAction.contains(4))) {
if (finalAction == 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.ACTION_NOT_SUPPORTED));
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.ACTION_NOT_SUPPORTED));
}
return;
}
}

if (argUsers.size() == 0) {
argUsers.add("#global");
}

List<String> rollbackusers = argUsers;
int c = 0;
for (String ruser : rollbackusers) {
List<Player> players = Bukkit.getServer().matchPlayer(ruser); // here
for (Player p : players) {
if (p.getName().equalsIgnoreCase(ruser)) {
ruser = p.getName();
rollbackusers.set(c, ruser);
}
}
c++;

if (argAction.contains(4) && argAction.contains(11)) {
Player onlineUser = Bukkit.getServer().getPlayer(ruser);
if (onlineUser == null || !onlineUser.isOnline()) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.USER_OFFLINE, ruser));
return;
}
}
}

int wid = 0;
int x = 0;
int y = 0;
int z = 0;
if (rollbackusers.contains("#container")) {
if (argAction.contains(11)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_USERNAME, "#container"));
return;
}

boolean valid = false;
if (ConfigHandler.lookupType.get(player.getName()) != null) {
int lookupType = ConfigHandler.lookupType.get(player.getName());
if (lookupType == 1) {
valid = true;
}
else if (lookupType == 5) {
if (ConfigHandler.lookupUlist.get(player.getName()).contains("#container")) {
valid = true;
}
}
}
if (valid) {
if (preview > 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PREVIEW_TRANSACTION, Selector.FIRST));
return;
}
else {
String lcommand = ConfigHandler.lookupCommand.get(player.getName());
String[] data = lcommand.split("\\.");
x = Integer.parseInt(data[0]);
y = Integer.parseInt(data[1]);
z = Integer.parseInt(data[2]);
wid = Integer.parseInt(data[3]);
argAction.add(5);
argRadius = null;
argWid = 0;
lo = new Location(Bukkit.getServer().getWorld(Util.getWorldName(wid)), x, y, z);
Block block = lo.getBlock();
if (block.getState() instanceof Chest) {
BlockFace[] blockFaces = new BlockFace[] { BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST };
for (BlockFace face : blockFaces) {
if (block.getRelative(face, 1).getState() instanceof Chest) {
Block relative = block.getRelative(face, 1);
int x2 = relative.getX();
int z2 = relative.getZ();
double newX = (x + x2) / 2.0;
double newZ = (z + z2) / 2.0;
lo.setX(newX);
lo.setZ(newZ);
break;
}
}
}
}
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_CONTAINER));
return;
}
}

final List<String> rollbackusers2 = rollbackusers;
if (startTime > 0) {
long unixtimestamp = (System.currentTimeMillis() / 1000L);
long timeStart = unixtimestamp - startTime;
long timeEnd = endTime > 0 ? (unixtimestamp - endTime) : 0;
if (forceStart > 0) {
timeStart = forceStart;
timeEnd = forceEnd;
}
final long finalTimeStart = timeStart;
final long finalTimeEnd = timeEnd;
final Integer[] radius = argRadius;
try {
final CommandSender player2 = player;
final int noisy = argNoisy;
final String rtime = ts;
final List<String> uuidList = argUuids;
final List<Object> blist = argBlocks;
final Map<Object, Boolean> elist = argExclude;
final List<String> euserlist = argExcludeUsers;
final Location locationFinal = lo;
final int finalArgWid = argWid;
final List<Integer> finalArgAction = argAction;
final String[] finalArgs = args;
final int finalPreview = preview;

ConfigHandler.activeRollbacks.put(player.getName(), true);

class BasicThread2 implements Runnable {

Check warning on line 345 in src/main/java/net/coreprotect/command/RollbackRestoreCommand.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/RollbackRestoreCommand.java#L34-L345

Very Complex Method
@Override
public void run() {
try (Connection connection = Database.getConnection(false, 1000)) {
ConfigHandler.lookupThrottle.put(player.getName(), new Object[] { true, System.currentTimeMillis() });
int action = finalAction;
Location location = locationFinal;
if (connection != null) {
Statement statement = connection.createStatement();
String baduser = "";
boolean exists = false;
for (String check : rollbackusers2) {
if (!check.equals("#global") && !check.equals("#container")) {
exists = PlayerLookup.playerExists(connection, check);
if (!exists) {
baduser = check;
break;
}
}
else {
exists = true;
}
}
if (exists) {
for (String check : euserlist) {
if (!check.equals("#global") && !check.equals("#hopper")) {
exists = PlayerLookup.playerExists(connection, check);
if (!exists) {
baduser = check;
break;
}
}
else if (check.equals("#global")) {
baduser = "#global";
exists = false;
}
}
}
if (exists) {
boolean restrictWorld = false;
if (radius != null) {
restrictWorld = true;
}
if (location == null) {
restrictWorld = false;
}
if (finalArgWid > 0) {
restrictWorld = true;
location = new Location(Bukkit.getServer().getWorld(Util.getWorldName(finalArgWid)), 0, 0, 0);
}
boolean verbose = false;
if (noisy == 1) {
verbose = true;
}

String users = "";
for (String value : rollbackusers2) {
if (users.length() == 0) {
users = "" + value + "";
}
else {
users = users + ", " + value;
}
}
if (users.equals("#global") && restrictWorld) {
// chat output only, don't pass into any functions
users = "#" + location.getWorld().getName();
}
if (finalPreview == 2) {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PREVIEW_CANCELLING));
}
else if (finalPreview == 1) {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.ROLLBACK_STARTED, users, Selector.THIRD));
}
else if (action == 0) {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.ROLLBACK_STARTED, users, Selector.FIRST));
}
else {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.ROLLBACK_STARTED, users, Selector.SECOND));
}

if (finalArgAction.contains(5)) {
ContainerRollback.performContainerRollbackRestore(statement, player2, uuidList, rollbackusers2, rtime, blist, elist, euserlist, finalArgAction, location, radius, finalTimeStart, finalTimeEnd, restrictWorld, false, verbose, action);
}
else {
Rollback.performRollbackRestore(statement, player2, uuidList, rollbackusers2, rtime, blist, elist, euserlist, finalArgAction, location, radius, finalTimeStart, finalTimeEnd, restrictWorld, false, verbose, action, finalPreview);
}
if (finalPreview < 2) {
List<Object> list = new ArrayList<>();
list.add(finalTimeStart);
list.add(finalTimeEnd);
list.add(finalArgs);
list.add(locationFinal);
ConfigHandler.lastRollback.put(player2.getName(), list);
}
}
else {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.USER_NOT_FOUND, baduser));
}
statement.close();
}
else {
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
}
}
catch (Exception e) {
e.printStackTrace();
}
if (ConfigHandler.activeRollbacks.get(player2.getName()) != null) {
ConfigHandler.activeRollbacks.remove(player2.getName());
}
ConfigHandler.lookupThrottle.put(player2.getName(), new Object[] { false, System.currentTimeMillis() });
}
}
Runnable runnable = new BasicThread2();
Thread thread = new Thread(runnable);
Thread thread = Util.THREAD_FACTORY.newThread(runnable);
thread.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
else {
if (finalAction == 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_LOOKUP_TIME, Selector.SECOND));
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_LOOKUP_TIME, Selector.THIRD));
}
}
}
else {
if (finalAction == 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_ROLLBACK_RADIUS, Selector.FIRST)); // rollback
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_ROLLBACK_RADIUS, Selector.SECOND)); // restore
}
}
}
else {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
}
}

Check notice on line 488 in src/main/java/net/coreprotect/command/RollbackRestoreCommand.java

View check run for this annotation

codefactor.io / CodeFactor

src/main/java/net/coreprotect/command/RollbackRestoreCommand.java#L346-L488

Complex Method
}
Loading
Loading