1
mirror of https://github.com/StarWishsama/Slimefun4.git synced 2024-09-20 03:35:51 +00:00

Merge branch 'master' into EnergyConnector

This commit is contained in:
LinoxGH 2020-10-08 15:53:08 +03:00 committed by GitHub
commit 4bf08db1d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
208 changed files with 910 additions and 1364 deletions

View File

@ -36,11 +36,13 @@
* (API) Added "NotConfigurable" attribute to disable configurability * (API) Added "NotConfigurable" attribute to disable configurability
* Added Elytra Cap * Added Elytra Cap
* Added Planks to Sticks recipe to the Table Saw * Added Planks to Sticks recipe to the Table Saw
* Added "slimefun.gps.bypass" permission to open GPS devices anywhere
#### Changes #### Changes
* Improved Auto-Updater (Multi-Threading and more) * Improved Auto-Updater (Multi-Threading and more)
* General performance improvements * General performance improvements
* /sf cheat now shows seasonal categories all year through * /sf cheat now shows seasonal categories all year through
* GPS devices now require chest-access in that area to be used
#### Fixes #### Fixes
* Fixed #2300 * Fixed #2300
@ -65,6 +67,7 @@
* Fixed radioactive items still being radioactive when disabled * Fixed radioactive items still being radioactive when disabled
* Fixed #2391 * Fixed #2391
* Fixed #2403 * Fixed #2403
* Fixed #2405
## Release Candidate 16 (07 Sep 2020) ## Release Candidate 16 (07 Sep 2020)
https://thebusybiscuit.github.io/builds/TheBusyBiscuit/Slimefun4/stable/#16 https://thebusybiscuit.github.io/builds/TheBusyBiscuit/Slimefun4/stable/#16

View File

@ -94,3 +94,93 @@ Then you should be able build it via Maven using the goals `clean package`.
If you have any further questions, then please join our [Discord Support Server](https://discord.gg/slimefun) and ask your questions in the `#programming-help` channel.<br> If you have any further questions, then please join our [Discord Support Server](https://discord.gg/slimefun) and ask your questions in the `#programming-help` channel.<br>
**Note that we will not accept any bug reports from custom-compiled versions of Slimefun**. **Note that we will not accept any bug reports from custom-compiled versions of Slimefun**.
## :black_nib: Code Style guidelines
The general gist when it comes to code style: **Try to be consistent!**.<br>
Try to stay inline with the code that surrounds you, having an entire package or even a single file that's filled with plenty of different and inconsistent code styles is just hard to read or maintain. That's why we wanna make sure everyone follows these principles.
*Note that these are just guidelines, we may request changes on your pull request if we think there are changes necessary.
But we won't reject your Pull Request completely due to a few styling inconsistencies, we can always refactor code later.
But do try to follow our code style as best as you can.*
#### 1. Imports
* Don't use wildcard (`*`) imports!
* Don't import unused classes!
* Don't use static imports!
* Always use imports, even in javadocs, don't write out the full location of a class.
#### 2. Annotations
* Methods and parameters should be annotated with `@Nullable` (`javax.annotation.Nullable`) or `@Nonnull`(`javax.annotation.Nonnull`)!
* Methods that override a method must be annotated with `@Override`!
* Interfaces with only one method should be annotated using `@FunctionalInterface`!
* If you deprecate a method, add an `@deprecated` section to the javadocs explaining why you did it.
#### 3. Documentation
* Every class and every public method should have a Javadocs section assigned to it.
* New packages should have a `package-info.java` file with documentation about the package.
* Classes should have an `@author` tag.
* If there are any other relevant classes related to yours, add them using the `@see` tag.
#### 4. Unit Tests
* Try to write Unit Tests where possible.
* Unit Test classes and methods should have no access modifier, not `public`, `protected` nor `private`.
* Each Test should have a plain text `@DisplayName` annotation!
#### 5. General best-practices
* Do not use `Collection#forEach(x -> ...)`, use a proper `for (...)` loop!
* Do not create new `Random` objects, use `ThreadLocalRandom.current()` instead!
* Always declare Maps or Collections using their base type! (e.g. `List<String> list = new ArrayList<>();`)
* When doing String operations like `String#toUppercase()`, always specify `Locale.ROOT` as an argument!
* When reading or writing files, always specify the encoding using `StandardCharsets.UTF_8`!
* Do not declare multiple fields/variables on the same line! (e.g. Don't do this: `int x, y, z;`)
* Use a Logger, try to avoid `System.out.println(...)` and `Throwable#printStacktrace()`, use `Logger#log` instead!
* Do not use Exceptions to validate data, empty catch blocks are a very bad practice, use other means like a regular expression to validate data.
* If a parameter is annotated with `@Nonnull`, you should enforce this behaviour by doing `Validate.notNull(variable, "...");` and give a meaningful message about what went wrong
* Any `switch/case` should always have a `default:` case at the end.
* If you are working with a resource that must be closed, use a `try/with-resource`, this will automatically close the resource at the end. (e.g. `try (InputStream stream = ...) {`)
* Array designators should be placed behind the type, not the variable name. (e.g. `int[] myArray`)
* Enums must be compared using `==`, not with `.equals()`!
* Avoid direct string concatenation, use a `StringBuilder` instead!
* If you need both the key and the value from a Map, use `Map#entrySet()`!
#### 6. Naming conventions
* Classes should be in *PascalCase* (e.g. `MyAwesomeClass`)
* Enum constants should be in *SCREAMING_SNAKE_CASE* (e.g. `MY_ENUM_CONSTANT`)
* Constants (`static final` fields) should be in *SCREAMING_SNAKE_CASE* (e.g. `MY_CONSTANT_FIELD`)
* Variables, parameters and fields should be in *camelCase* (e.g. `myVariableOrField`)
* All methods should be in *camelCase* (e.g. `myMethod`)
* Packages must be all lowercase, consecutive words should generally be avoided. (e.g. `io.github.thebusybiscuit.slimefun4.core.something`)
#### 7. Style preferences
* Use **Spaces**, not Tabs!
* One class per file! Please don't put multiple classes into one file, this also applies to enums, make a seperate file for new classes or enums.
* Try to keep ternary operators to a minimum, only in return statements. (e.g. avoid doing this: `int y = x == null ? 1: 2`)
* Try to keep so-called "guard blocks" to a minimum. One guard block is fine but having multiple guard blocks before getting to the actual code... Well, you might wanna refactor your code there. Example:
```java
// guard block
if (something) {
return;
}
// Actual code...
```
* if/else statements should always include a bracket, please avoid one-line statements. (e.g. Avoid doing: `if (x == 0) return;`)
* We do not enforce any particular width or column limit, but try to prevent your lines from becoming too long.
* Annotations for methods or fields should never go on the same line, place them on the line above.
* Comments should never go on the same line as code! Always above or below.
* Make sure that empty lines are truly empty, they should not contain any whitespace characters.
* Empty blocks like constructors should not occupy more than one line. (e.g. `private MyClass() {}`)
* Modifiers for classes and fields must follow this order:<br>
`(public/protected/private) (abstract) (static) (final)`
* We recommend using horizontal whitespaces like this:
* In variable assignments: `int x = 123;`
* In a for-loop: `for (int i = 0; i < 10; i++) {`
* Before and after statement parenthesis: `if (x != null) {`
* Inbetween array initializers: `int[] array = { 1, 2, 3 };`
* After the double slash of a comment: `// This is a comment`
* Slimefun follows the **1TBS / OTBS** Bracket-Style standard (One true brace style):
```java
private void example(int x) {
if (x < 0) {
// x < 0
} else if (x > 0) {
// x > 0
} else {
// x == 0
}
}
```

View File

@ -182,8 +182,7 @@ public class ErrorReport<T extends Throwable> {
} }
addon.getLogger().log(Level.WARNING, ""); addon.getLogger().log(Level.WARNING, "");
} } catch (Exception x) {
catch (Exception x) {
addon.getLogger().log(Level.SEVERE, x, () -> "An Error occurred while saving an Error-Report for Slimefun " + SlimefunPlugin.getVersion()); addon.getLogger().log(Level.SEVERE, x, () -> "An Error occurred while saving an Error-Report for Slimefun " + SlimefunPlugin.getVersion());
} }
} }
@ -198,8 +197,7 @@ public class ErrorReport<T extends Throwable> {
if (plugin.getDescription().getDepend().contains(dependency) || plugin.getDescription().getSoftDepend().contains(dependency)) { if (plugin.getDescription().getDepend().contains(dependency) || plugin.getDescription().getSoftDepend().contains(dependency)) {
addons.add(" + " + plugin.getName() + ' ' + plugin.getDescription().getVersion()); addons.add(" + " + plugin.getName() + ' ' + plugin.getDescription().getVersion());
} }
} } else {
else {
plugins.add(" - " + plugin.getName() + ' ' + plugin.getDescription().getVersion()); plugins.add(" - " + plugin.getName() + ' ' + plugin.getDescription().getVersion());
if (plugin.getDescription().getDepend().contains(dependency) || plugin.getDescription().getSoftDepend().contains(dependency)) { if (plugin.getDescription().getDepend().contains(dependency) || plugin.getDescription().getSoftDepend().contains(dependency)) {
@ -227,8 +225,7 @@ public class ErrorReport<T extends Throwable> {
public static void tryCatch(@Nonnull Function<Exception, ErrorReport<Exception>> function, @Nonnull Runnable runnable) { public static void tryCatch(@Nonnull Function<Exception, ErrorReport<Exception>> function, @Nonnull Runnable runnable) {
try { try {
runnable.run(); runnable.run();
} } catch (Exception x) {
catch (Exception x) {
function.apply(x); function.apply(x);
} }
} }

View File

@ -79,8 +79,7 @@ public class BlockPlacerPlaceEvent extends BlockEvent implements Cancellable {
if (!locked) { if (!locked) {
this.placedItem = item; this.placedItem = item;
} } else {
else {
SlimefunItem.getByItem(placedItem).warn("A BlockPlacerPlaceEvent cannot be modified from within a BlockPlaceHandler!"); SlimefunItem.getByItem(placedItem).warn("A BlockPlacerPlaceEvent cannot be modified from within a BlockPlaceHandler!");
} }
} }
@ -94,8 +93,7 @@ public class BlockPlacerPlaceEvent extends BlockEvent implements Cancellable {
public void setCancelled(boolean cancel) { public void setCancelled(boolean cancel) {
if (!locked) { if (!locked) {
cancelled = cancel; cancelled = cancel;
} } else {
else {
SlimefunItem.getByItem(placedItem).warn("A BlockPlacerPlaceEvent cannot be modified from within a BlockPlaceHandler!"); SlimefunItem.getByItem(placedItem).warn("A BlockPlacerPlaceEvent cannot be modified from within a BlockPlaceHandler!");
} }
} }

View File

@ -47,8 +47,7 @@ public class PlayerRightClickEvent extends Event {
if (e.getItem() == null || e.getItem().getType() == Material.AIR || e.getItem().getAmount() == 0) { if (e.getItem() == null || e.getItem().getType() == Material.AIR || e.getItem().getAmount() == 0) {
itemStack = Optional.empty(); itemStack = Optional.empty();
} } else {
else {
itemStack = Optional.of(e.getItem()); itemStack = Optional.of(e.getItem());
} }
} }
@ -101,8 +100,7 @@ public class PlayerRightClickEvent extends Event {
if (!slimefunItem.isComputed()) { if (!slimefunItem.isComputed()) {
if (itemStack.isPresent()) { if (itemStack.isPresent()) {
slimefunItem.compute(SlimefunItem.getByItem(itemStack.get())); slimefunItem.compute(SlimefunItem.getByItem(itemStack.get()));
} } else {
else {
slimefunItem = ComputedOptional.empty(); slimefunItem = ComputedOptional.empty();
} }
} }
@ -115,8 +113,7 @@ public class PlayerRightClickEvent extends Event {
if (!slimefunBlock.isComputed()) { if (!slimefunBlock.isComputed()) {
if (clickedBlock.isPresent()) { if (clickedBlock.isPresent()) {
slimefunBlock.compute(BlockStorage.check(clickedBlock.get())); slimefunBlock.compute(BlockStorage.check(clickedBlock.get()));
} } else {
else {
slimefunBlock = ComputedOptional.empty(); slimefunBlock = ComputedOptional.empty();
} }
} }

View File

@ -12,7 +12,7 @@ import org.bukkit.inventory.ItemStack;
import io.github.thebusybiscuit.slimefun4.core.guide.SlimefunGuideLayout; import io.github.thebusybiscuit.slimefun4.core.guide.SlimefunGuideLayout;
/** /**
* This {@link Event} is called whenever a {@link Player} tries to open the Slimefun Guide book. * This {@link Event} is called whenever a {@link Player} tries to open the Slimefun Guide book.
* *
* @author Linox * @author Linox
* *
@ -37,7 +37,7 @@ public class SlimefunGuideOpenEvent extends Event implements Cancellable {
} }
/** /**
* This returns the {@link Player} that tries to open * This returns the {@link Player} that tries to open
* the Slimefun Guide. * the Slimefun Guide.
* *
* @return The {@link Player} * @return The {@link Player}
@ -48,7 +48,7 @@ public class SlimefunGuideOpenEvent extends Event implements Cancellable {
} }
/** /**
* This returns the {@link ItemStack} that {@link Player} * This returns the {@link ItemStack} that {@link Player}
* tries to open the Slimefun Guide with. * tries to open the Slimefun Guide with.
* *
* @return The {@link ItemStack} * @return The {@link ItemStack}
@ -57,7 +57,7 @@ public class SlimefunGuideOpenEvent extends Event implements Cancellable {
public ItemStack getGuide() { public ItemStack getGuide() {
return guide; return guide;
} }
/** /**
* This returns the {@link SlimefunGuideLayout} of the Slimefun Guide * This returns the {@link SlimefunGuideLayout} of the Slimefun Guide
* that {@link Player} tries to open. * that {@link Player} tries to open.
@ -68,12 +68,12 @@ public class SlimefunGuideOpenEvent extends Event implements Cancellable {
public SlimefunGuideLayout getGuideLayout() { public SlimefunGuideLayout getGuideLayout() {
return layout; return layout;
} }
/** /**
* Changes the {@link SlimefunGuideLayout} that was tried to be opened with. * Changes the {@link SlimefunGuideLayout} that was tried to be opened with.
* *
* @param layout * @param layout
* The new {@link SlimefunGuideLayout} * The new {@link SlimefunGuideLayout}
*/ */
public void setGuideLayout(@Nonnull SlimefunGuideLayout layout) { public void setGuideLayout(@Nonnull SlimefunGuideLayout layout) {
Validate.notNull(layout, "You must specify a layout that is not-null!"); Validate.notNull(layout, "You must specify a layout that is not-null!");

View File

@ -104,8 +104,7 @@ public class ResourceManager {
if (value != null) { if (value != null) {
return OptionalInt.of(Integer.parseInt(value)); return OptionalInt.of(Integer.parseInt(value));
} } else {
else {
return OptionalInt.empty(); return OptionalInt.empty();
} }
} }
@ -202,13 +201,15 @@ public class ResourceManager {
menu.addItem(47, ChestMenuUtils.getPreviousButton(p, page + 1, pages)); menu.addItem(47, ChestMenuUtils.getPreviousButton(p, page + 1, pages));
menu.addMenuClickHandler(47, (pl, slot, item, action) -> { menu.addMenuClickHandler(47, (pl, slot, item, action) -> {
if (page > 0) scan(pl, block, page - 1); if (page > 0)
scan(pl, block, page - 1);
return false; return false;
}); });
menu.addItem(51, ChestMenuUtils.getNextButton(p, page + 1, pages)); menu.addItem(51, ChestMenuUtils.getNextButton(p, page + 1, pages));
menu.addMenuClickHandler(51, (pl, slot, item, action) -> { menu.addMenuClickHandler(51, (pl, slot, item, action) -> {
if (page + 1 < pages) scan(pl, block, page + 1); if (page + 1 < pages)
scan(pl, block, page + 1);
return false; return false;
}); });

View File

@ -73,8 +73,7 @@ public class GPSNetwork {
if (online) { if (online) {
set.add(l); set.add(l);
} } else {
else {
set.remove(l); set.remove(l);
} }
} }
@ -118,8 +117,7 @@ public class GPSNetwork {
public int countTransmitters(@Nonnull UUID uuid) { public int countTransmitters(@Nonnull UUID uuid) {
if (!transmitters.containsKey(uuid)) { if (!transmitters.containsKey(uuid)) {
return 0; return 0;
} } else {
else {
return transmitters.get(uuid).size(); return transmitters.get(uuid).size();
} }
} }
@ -150,7 +148,8 @@ public class GPSNetwork {
int index = 0; int index = 0;
for (Location l : getTransmitters(p.getUniqueId())) { for (Location l : getTransmitters(p.getUniqueId())) {
if (index >= inventory.length) break; if (index >= inventory.length)
break;
SlimefunItem sfi = BlockStorage.check(l); SlimefunItem sfi = BlockStorage.check(l);
if (sfi instanceof GPSTransmitter) { if (sfi instanceof GPSTransmitter) {
@ -185,14 +184,11 @@ public class GPSNetwork {
public ItemStack getIcon(@Nonnull String name, @Nonnull Environment environment) { public ItemStack getIcon(@Nonnull String name, @Nonnull Environment environment) {
if (name.startsWith("player:death ")) { if (name.startsWith("player:death ")) {
return HeadTexture.DEATHPOINT.getAsItemStack(); return HeadTexture.DEATHPOINT.getAsItemStack();
} } else if (environment == Environment.NETHER) {
else if (environment == Environment.NETHER) {
return HeadTexture.GLOBE_NETHER.getAsItemStack(); return HeadTexture.GLOBE_NETHER.getAsItemStack();
} } else if (environment == Environment.THE_END) {
else if (environment == Environment.THE_END) {
return HeadTexture.GLOBE_THE_END.getAsItemStack(); return HeadTexture.GLOBE_THE_END.getAsItemStack();
} } else {
else {
return HeadTexture.GLOBE_OVERWORLD.getAsItemStack(); return HeadTexture.GLOBE_OVERWORLD.getAsItemStack();
} }
} }
@ -220,7 +216,8 @@ public class GPSNetwork {
int index = 0; int index = 0;
for (Waypoint waypoint : profile.getWaypoints()) { for (Waypoint waypoint : profile.getWaypoints()) {
if (index >= inventory.length) break; if (index >= inventory.length)
break;
int slot = inventory[index]; int slot = inventory[index];
Location l = waypoint.getLocation(); Location l = waypoint.getLocation();

View File

@ -92,7 +92,8 @@ public final class TeleportationManager {
@ParametersAreNonnullByDefault @ParametersAreNonnullByDefault
public int getTeleportationTime(int complexity, Location source, Location destination) { public int getTeleportationTime(int complexity, Location source, Location destination) {
if (complexity < 100) return 100; if (complexity < 100)
return 100;
int speed = 50_000 + complexity * complexity; int speed = 50_000 + complexity * complexity;
return 1 + Math.min(4 * distanceSquared(source, destination) / speed, 40); return 1 + Math.min(4 * distanceSquared(source, destination) / speed, 40);
@ -103,8 +104,7 @@ public final class TeleportationManager {
if (source.getWorld().getUID().equals(destination.getWorld().getUID())) { if (source.getWorld().getUID().equals(destination.getWorld().getUID())) {
int distance = (int) source.distanceSquared(destination); int distance = (int) source.distanceSquared(destination);
return Math.min(distance, 100_000_000); return Math.min(distance, 100_000_000);
} } else {
else {
return 150_000_000; return 150_000_000;
} }
} }
@ -129,8 +129,7 @@ public final class TeleportationManager {
if (progress > 99) { if (progress > 99) {
p.sendTitle(ChatColors.color(SlimefunPlugin.getLocalization().getMessage(p, "machines.TELEPORTER.teleported")), ChatColors.color("&b100%"), 20, 60, 20); p.sendTitle(ChatColors.color(SlimefunPlugin.getLocalization().getMessage(p, "machines.TELEPORTER.teleported")), ChatColors.color("&b100%"), 20, 60, 20);
PaperLib.teleportAsync(p, destination).thenAccept(success -> onTeleport(p, destination, success, resistance)); PaperLib.teleportAsync(p, destination).thenAccept(success -> onTeleport(p, destination, success, resistance));
} } else {
else {
p.sendTitle(ChatColors.color(SlimefunPlugin.getLocalization().getMessage(p, "machines.TELEPORTER.teleporting")), ChatColors.color("&b" + progress + "%"), 0, 60, 0); p.sendTitle(ChatColors.color(SlimefunPlugin.getLocalization().getMessage(p, "machines.TELEPORTER.teleporting")), ChatColors.color("&b" + progress + "%"), 0, 60, 0);
source.getWorld().spawnParticle(Particle.PORTAL, source, progress * 2, 0.2F, 0.8F, 0.2F); source.getWorld().spawnParticle(Particle.PORTAL, source, progress * 2, 0.2F, 0.8F, 0.2F);
@ -138,8 +137,7 @@ public final class TeleportationManager {
SlimefunPlugin.runSync(() -> updateProgress(uuid, speed, progress + speed, source, destination, resistance), 10L); SlimefunPlugin.runSync(() -> updateProgress(uuid, speed, progress + speed, source, destination, resistance), 10L);
} }
} } else {
else {
cancel(uuid, p); cancel(uuid, p);
} }
} }
@ -161,8 +159,7 @@ public final class TeleportationManager {
destination.getWorld().spawnParticle(Particle.PORTAL, loc, 200, 0.2F, 0.8F, 0.2F); destination.getWorld().spawnParticle(Particle.PORTAL, loc, 200, 0.2F, 0.8F, 0.2F);
destination.getWorld().playSound(destination, Sound.BLOCK_BEACON_ACTIVATE, 1F, 1F); destination.getWorld().playSound(destination, Sound.BLOCK_BEACON_ACTIVATE, 1F, 1F);
teleporterUsers.remove(p.getUniqueId()); teleporterUsers.remove(p.getUniqueId());
} } else {
else {
// Make sure the Player is removed from the actively teleporting users // Make sure the Player is removed from the actively teleporting users
// and notified about the failed teleportation // and notified about the failed teleportation
cancel(p.getUniqueId(), p); cancel(p.getUniqueId(), p);

View File

@ -54,8 +54,7 @@ public final class HashedArmorpiece {
public void update(@Nullable ItemStack stack, @Nullable SlimefunItem item) { public void update(@Nullable ItemStack stack, @Nullable SlimefunItem item) {
if (stack == null || stack.getType() == Material.AIR) { if (stack == null || stack.getType() == Material.AIR) {
this.hash = 0; this.hash = 0;
} } else {
else {
ItemStack copy = stack.clone(); ItemStack copy = stack.clone();
ItemMeta meta = copy.getItemMeta(); ItemMeta meta = copy.getItemMeta();
((Damageable) meta).setDamage(0); ((Damageable) meta).setDamage(0);
@ -65,8 +64,7 @@ public final class HashedArmorpiece {
if (item instanceof SlimefunArmorPiece) { if (item instanceof SlimefunArmorPiece) {
this.item = Optional.of((SlimefunArmorPiece) item); this.item = Optional.of((SlimefunArmorPiece) item);
} } else {
else {
this.item = Optional.empty(); this.item = Optional.empty();
} }
} }
@ -82,8 +80,7 @@ public final class HashedArmorpiece {
public boolean hasDiverged(@Nullable ItemStack stack) { public boolean hasDiverged(@Nullable ItemStack stack) {
if (stack == null || stack.getType() == Material.AIR) { if (stack == null || stack.getType() == Material.AIR) {
return hash != 0; return hash != 0;
} } else {
else {
ItemStack copy = stack.clone(); ItemStack copy = stack.clone();
ItemMeta meta = copy.getItemMeta(); ItemMeta meta = copy.getItemMeta();
((Damageable) meta).setDamage(0); ((Damageable) meta).setDamage(0);

View File

@ -69,8 +69,7 @@ public class ItemSetting<T> {
public void update(@Nonnull T newValue) { public void update(@Nonnull T newValue) {
if (validateInput(newValue)) { if (validateInput(newValue)) {
this.value = newValue; this.value = newValue;
} } else {
else {
throw new IllegalArgumentException("The passed value was not valid. (Maybe null?)"); throw new IllegalArgumentException("The passed value was not valid. (Maybe null?)");
} }
@ -134,8 +133,7 @@ public class ItemSetting<T> {
if (defaultValue.getClass().isInstance(configuredValue)) { if (defaultValue.getClass().isInstance(configuredValue)) {
this.value = (T) configuredValue; this.value = (T) configuredValue;
} } else {
else {
this.value = defaultValue; this.value = defaultValue;
String found = configuredValue == null ? "null" : configuredValue.getClass().getSimpleName(); String found = configuredValue == null ? "null" : configuredValue.getClass().getSimpleName();

View File

@ -122,8 +122,7 @@ public abstract class Network {
public void markDirty(@Nonnull Location l) { public void markDirty(@Nonnull Location l) {
if (regulator.equals(l)) { if (regulator.equals(l)) {
manager.unregisterNetwork(this); manager.unregisterNetwork(this);
} } else {
else {
nodeQueue.add(l.clone()); nodeQueue.add(l.clone());
} }
} }
@ -143,11 +142,9 @@ public abstract class Network {
private NetworkComponent getCurrentClassification(@Nonnull Location l) { private NetworkComponent getCurrentClassification(@Nonnull Location l) {
if (regulatorNodes.contains(l)) { if (regulatorNodes.contains(l)) {
return NetworkComponent.REGULATOR; return NetworkComponent.REGULATOR;
} } else if (connectorNodes.contains(l)) {
else if (connectorNodes.contains(l)) {
return NetworkComponent.CONNECTOR; return NetworkComponent.CONNECTOR;
} } else if (terminusNodes.contains(l)) {
else if (terminusNodes.contains(l)) {
return NetworkComponent.TERMINUS; return NetworkComponent.TERMINUS;
} }
@ -168,20 +165,17 @@ public abstract class Network {
// Requires a complete rebuild of the network, so we just throw the current one away. // Requires a complete rebuild of the network, so we just throw the current one away.
manager.unregisterNetwork(this); manager.unregisterNetwork(this);
return; return;
} } else if (currentAssignment == NetworkComponent.TERMINUS) {
else if (currentAssignment == NetworkComponent.TERMINUS) {
terminusNodes.remove(l); terminusNodes.remove(l);
} }
if (classification == NetworkComponent.REGULATOR) { if (classification == NetworkComponent.REGULATOR) {
regulatorNodes.add(l); regulatorNodes.add(l);
discoverNeighbors(l); discoverNeighbors(l);
} } else if (classification == NetworkComponent.CONNECTOR) {
else if (classification == NetworkComponent.CONNECTOR) {
connectorNodes.add(l); connectorNodes.add(l);
discoverNeighbors(l); discoverNeighbors(l);
} } else if (classification == NetworkComponent.TERMINUS) {
else if (classification == NetworkComponent.TERMINUS) {
terminusNodes.add(l); terminusNodes.add(l);
} }

View File

@ -95,8 +95,7 @@ public final class PlayerProfile {
Location loc = waypointsFile.getLocation(key); Location loc = waypointsFile.getLocation(key);
waypoints.add(new Waypoint(this, key, loc, waypointName)); waypoints.add(new Waypoint(this, key, loc, waypointName));
} }
} } catch (Exception x) {
catch (Exception x) {
Slimefun.getLogger().log(Level.WARNING, x, () -> "Could not load Waypoint \"" + key + "\" for Player \"" + p.getName() + '"'); Slimefun.getLogger().log(Level.WARNING, x, () -> "Could not load Waypoint \"" + key + "\" for Player \"" + p.getName() + '"');
} }
} }
@ -182,8 +181,7 @@ public final class PlayerProfile {
if (unlock) { if (unlock) {
configFile.setValue("researches." + research.getID(), true); configFile.setValue("researches." + research.getID(), true);
researches.add(research); researches.add(research);
} } else {
else {
configFile.setValue("researches." + research.getID(), null); configFile.setValue("researches." + research.getID(), null);
researches.remove(research); researches.remove(research);
} }
@ -303,8 +301,7 @@ public final class PlayerProfile {
if (backpack != null) { if (backpack != null) {
return Optional.of(backpack); return Optional.of(backpack);
} } else if (configFile.contains("backpacks." + id + ".size")) {
else if (configFile.contains("backpacks." + id + ".size")) {
backpack = new PlayerBackpack(this, id); backpack = new PlayerBackpack(this, id);
backpacks.put(id, backpack); backpacks.put(id, backpack);
return Optional.of(backpack); return Optional.of(backpack);
@ -477,8 +474,7 @@ public final class PlayerProfile {
if (!armorPiece.isPresent()) { if (!armorPiece.isPresent()) {
setId = null; setId = null;
} } else if (armorPiece.get() instanceof ProtectiveArmor) {
else if (armorPiece.get() instanceof ProtectiveArmor) {
ProtectiveArmor protectedArmor = (ProtectiveArmor) armorPiece.get(); ProtectiveArmor protectedArmor = (ProtectiveArmor) armorPiece.get();
if (setId == null && protectedArmor.isFullSetRequired()) { if (setId == null && protectedArmor.isFullSetRequired()) {
@ -489,8 +485,7 @@ public final class PlayerProfile {
if (protectionType == type) { if (protectionType == type) {
if (setId == null) { if (setId == null) {
return true; return true;
} } else if (setId.equals(protectedArmor.getArmorSetId())) {
else if (setId.equals(protectedArmor.getArmorSetId())) {
armorCount++; armorCount++;
} }
} }

View File

@ -100,13 +100,12 @@ public class StatusEffect implements Keyed {
if (timestamp == 0 || timestamp >= System.currentTimeMillis()) { if (timestamp == 0 || timestamp >= System.currentTimeMillis()) {
return true; return true;
} } else {
else {
clear(p); clear(p);
return false; return false;
} }
} } else
else return false; return false;
} }
/** /**
@ -124,8 +123,8 @@ public class StatusEffect implements Keyed {
String[] data = PatternUtils.SEMICOLON.split(optional.get()); String[] data = PatternUtils.SEMICOLON.split(optional.get());
return OptionalInt.of(Integer.parseInt(data[0])); return OptionalInt.of(Integer.parseInt(data[0]));
} } else
else return OptionalInt.empty(); return OptionalInt.empty();
} }
/** /**

View File

@ -59,8 +59,7 @@ public interface DamageableItem extends ItemAttribute {
if (damageable.getDamage() >= item.getType().getMaxDurability()) { if (damageable.getDamage() >= item.getType().getMaxDurability()) {
p.playSound(p.getEyeLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1); p.playSound(p.getEyeLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1);
item.setAmount(0); item.setAmount(0);
} } else {
else {
damageable.setDamage(damageable.getDamage() + 1); damageable.setDamage(damageable.getDamage() + 1);
item.setItemMeta(meta); item.setItemMeta(meta);
} }

View File

@ -72,8 +72,7 @@ public interface EnergyNetComponent extends ItemAttribute {
if (charge != null) { if (charge != null) {
return Integer.parseInt(charge); return Integer.parseInt(charge);
} } else {
else {
return 0; return 0;
} }
} }

View File

@ -4,8 +4,8 @@ import javax.annotation.Nonnull;
public enum MachineType { public enum MachineType {
CAPACITOR("Capacitor"), CAPACITOR("Capacitor"),
GENERATOR("Generator"), GENERATOR("Generator"),
MACHINE("Machine"); MACHINE("Machine");
private final String suffix; private final String suffix;

View File

@ -33,12 +33,10 @@ class SlimefunTabCompleter implements TabCompleter {
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) { public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length == 1) { if (args.length == 1) {
return createReturnList(command.getSubCommandNames(), args[0]); return createReturnList(command.getSubCommandNames(), args[0]);
} } else if (args.length == 3) {
else if (args.length == 3) {
if (args[0].equalsIgnoreCase("give")) { if (args[0].equalsIgnoreCase("give")) {
return createReturnList(getSlimefunItems(), args[2]); return createReturnList(getSlimefunItems(), args[2]);
} } else if (args[0].equalsIgnoreCase("research")) {
else if (args[0].equalsIgnoreCase("research")) {
List<Research> researches = SlimefunPlugin.getRegistry().getResearches(); List<Research> researches = SlimefunPlugin.getRegistry().getResearches();
List<String> suggestions = new LinkedList<>(); List<String> suggestions = new LinkedList<>();
@ -50,16 +48,13 @@ class SlimefunTabCompleter implements TabCompleter {
} }
return createReturnList(suggestions, args[2]); return createReturnList(suggestions, args[2]);
} } else {
else {
// Returning null will make it fallback to the default arguments (all online players) // Returning null will make it fallback to the default arguments (all online players)
return null; return null;
} }
} } else if (args.length == 4 && args[0].equalsIgnoreCase("give")) {
else if (args.length == 4 && args[0].equalsIgnoreCase("give")) {
return createReturnList(Arrays.asList("1", "2", "4", "8", "16", "32", "64"), args[3]); return createReturnList(Arrays.asList("1", "2", "4", "8", "16", "32", "64"), args[3]);
} } else {
else {
// Returning null will make it fallback to the default arguments (all online players) // Returning null will make it fallback to the default arguments (all online players)
return null; return null;
} }
@ -90,8 +85,7 @@ class SlimefunTabCompleter implements TabCompleter {
if (returnList.size() >= MAX_SUGGESTIONS) { if (returnList.size() >= MAX_SUGGESTIONS) {
break; break;
} }
} } else if (item.equalsIgnoreCase(input)) {
else if (item.equalsIgnoreCase(input)) {
return Collections.emptyList(); return Collections.emptyList();
} }
} }

View File

@ -83,8 +83,7 @@ public abstract class SubCommand {
public String getDescription(@Nonnull CommandSender sender) { public String getDescription(@Nonnull CommandSender sender) {
if (sender instanceof Player) { if (sender instanceof Player) {
return SlimefunPlugin.getLocalization().getMessage((Player) sender, getDescription()); return SlimefunPlugin.getLocalization().getMessage((Player) sender, getDescription());
} } else {
else {
return SlimefunPlugin.getLocalization().getMessage(getDescription()); return SlimefunPlugin.getLocalization().getMessage(getDescription());
} }
} }

View File

@ -61,12 +61,10 @@ class BackpackCommand extends SubCommand {
SlimefunPlugin.getLocalization().sendMessage(sender, "commands.backpack.restored-backpack-given"); SlimefunPlugin.getLocalization().sendMessage(sender, "commands.backpack.restored-backpack-given");
}); });
}); });
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true);
} }
} }

View File

@ -39,16 +39,13 @@ class ChargeCommand extends SubCommand {
Rechargeable rechargeableItem = (Rechargeable) slimefunItem; Rechargeable rechargeableItem = (Rechargeable) slimefunItem;
rechargeableItem.setItemCharge(item, rechargeableItem.getMaxItemCharge(item)); rechargeableItem.setItemCharge(item, rechargeableItem.getMaxItemCharge(item));
SlimefunPlugin.getLocalization().sendMessage(sender, "commands.charge.charge-success", true); SlimefunPlugin.getLocalization().sendMessage(sender, "commands.charge.charge-success", true);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "commands.charge.not-rechargeable", true); SlimefunPlugin.getLocalization().sendMessage(sender, "commands.charge.not-rechargeable", true);
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true);
} }
} }

View File

@ -19,12 +19,10 @@ class CheatCommand extends SubCommand {
if (sender instanceof Player) { if (sender instanceof Player) {
if (sender.hasPermission("slimefun.cheat.items")) { if (sender.hasPermission("slimefun.cheat.items")) {
SlimefunGuide.openCheatMenu((Player) sender); SlimefunGuide.openCheatMenu((Player) sender);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true);
} }
} }

View File

@ -18,8 +18,7 @@ class DebugFishCommand extends SubCommand {
public void onExecute(CommandSender sender, String[] args) { public void onExecute(CommandSender sender, String[] args) {
if (sender instanceof Player && sender.hasPermission("slimefun.debugging")) { if (sender instanceof Player && sender.hasPermission("slimefun.debugging")) {
((Player) sender).getInventory().addItem(SlimefunItems.DEBUG_FISH.clone()); ((Player) sender).getInventory().addItem(SlimefunItems.DEBUG_FISH.clone());
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} }

View File

@ -39,20 +39,16 @@ class GiveCommand extends SubCommand {
if (sfItem != null) { if (sfItem != null) {
giveItem(sender, p, sfItem, args); giveItem(sender, p, sfItem, args);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-valid-item", true, msg -> msg.replace(PLACEHOLDER_ITEM, args[2])); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-valid-item", true, msg -> msg.replace(PLACEHOLDER_ITEM, args[2]));
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-online", true, msg -> msg.replace(PLACEHOLDER_PLAYER, args[1])); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-online", true, msg -> msg.replace(PLACEHOLDER_PLAYER, args[1]));
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.usage", true, msg -> msg.replace("%usage%", "/sf give <Player> <Slimefun Item> [Amount]")); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.usage", true, msg -> msg.replace("%usage%", "/sf give <Player> <Slimefun Item> [Amount]"));
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} }
@ -60,13 +56,12 @@ class GiveCommand extends SubCommand {
private void giveItem(CommandSender sender, Player p, SlimefunItem sfItem, String[] args) { private void giveItem(CommandSender sender, Player p, SlimefunItem sfItem, String[] args) {
if (sfItem instanceof MultiBlockMachine) { if (sfItem instanceof MultiBlockMachine) {
SlimefunPlugin.getLocalization().sendMessage(sender, "guide.cheat.no-multiblocks"); SlimefunPlugin.getLocalization().sendMessage(sender, "guide.cheat.no-multiblocks");
} } else {
else {
int amount = parseAmount(args); int amount = parseAmount(args);
if (amount > 0) { if (amount > 0) {
SlimefunPlugin.getLocalization().sendMessage(p, "messages.given-item", true, msg -> msg.replace(PLACEHOLDER_ITEM, sfItem.getItemName()).replace(PLACEHOLDER_AMOUNT, String.valueOf(amount))); SlimefunPlugin.getLocalization().sendMessage(p, "messages.given-item", true, msg -> msg.replace(PLACEHOLDER_ITEM, sfItem.getItemName()).replace(PLACEHOLDER_AMOUNT, String.valueOf(amount)));
Map<Integer,ItemStack> excess = p.getInventory().addItem(new CustomItem(sfItem.getItem(), amount)); Map<Integer, ItemStack> excess = p.getInventory().addItem(new CustomItem(sfItem.getItem(), amount));
if (SlimefunPlugin.getCfg().getBoolean("options.drop-excess-sf-give-items") && !excess.isEmpty()) { if (SlimefunPlugin.getCfg().getBoolean("options.drop-excess-sf-give-items") && !excess.isEmpty()) {
for (ItemStack is : excess.values()) { for (ItemStack is : excess.values()) {
p.getWorld().dropItem(p.getLocation(), is); p.getWorld().dropItem(p.getLocation(), is);
@ -74,8 +69,7 @@ class GiveCommand extends SubCommand {
} }
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.give-item", true, msg -> msg.replace(PLACEHOLDER_PLAYER, args[1]).replace(PLACEHOLDER_ITEM, sfItem.getItemName()).replace(PLACEHOLDER_AMOUNT, String.valueOf(amount))); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.give-item", true, msg -> msg.replace(PLACEHOLDER_PLAYER, args[1]).replace(PLACEHOLDER_ITEM, sfItem.getItemName()).replace(PLACEHOLDER_AMOUNT, String.valueOf(amount)));
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-valid-amount", true, msg -> msg.replace(PLACEHOLDER_AMOUNT, args[3])); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-valid-amount", true, msg -> msg.replace(PLACEHOLDER_AMOUNT, args[3]));
} }
} }
@ -87,8 +81,7 @@ class GiveCommand extends SubCommand {
if (args.length == 4) { if (args.length == 4) {
if (PatternUtils.NUMERIC.matcher(args[3]).matches()) { if (PatternUtils.NUMERIC.matcher(args[3]).matches()) {
amount = Integer.parseInt(args[3]); amount = Integer.parseInt(args[3]);
} } else {
else {
return 0; return 0;
} }
} }

View File

@ -21,12 +21,10 @@ class GuideCommand extends SubCommand {
if (sender.hasPermission("slimefun.command.guide")) { if (sender.hasPermission("slimefun.command.guide")) {
SlimefunGuideLayout design = SlimefunGuide.getDefaultLayout(); SlimefunGuideLayout design = SlimefunGuide.getDefaultLayout();
((Player) sender).getInventory().addItem(SlimefunGuide.getItem(design).clone()); ((Player) sender).getInventory().addItem(SlimefunGuide.getItem(design).clone());
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true);
} }
} }

View File

@ -21,12 +21,10 @@ class OpenGuideCommand extends SubCommand {
if (sender.hasPermission("slimefun.command.open_guide")) { if (sender.hasPermission("slimefun.command.open_guide")) {
boolean book = SlimefunPlugin.getCfg().getBoolean("guide.default-view-book"); boolean book = SlimefunPlugin.getCfg().getBoolean("guide.default-view-book");
SlimefunGuide.openGuide((Player) sender, book ? SlimefunGuideLayout.BOOK : SlimefunGuideLayout.CHEST); SlimefunGuide.openGuide((Player) sender, book ? SlimefunGuideLayout.BOOK : SlimefunGuideLayout.CHEST);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true);
} }
} }

View File

@ -40,22 +40,18 @@ class ResearchCommand extends SubCommand {
PlayerProfile.get(p, profile -> { PlayerProfile.get(p, profile -> {
if (args[2].equalsIgnoreCase("all")) { if (args[2].equalsIgnoreCase("all")) {
researchAll(sender, profile, p); researchAll(sender, profile, p);
} } else if (args[2].equalsIgnoreCase("reset")) {
else if (args[2].equalsIgnoreCase("reset")) {
reset(profile, p); reset(profile, p);
} } else {
else {
giveResearch(sender, p, args[2]); giveResearch(sender, p, args[2]);
} }
}); });
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-online", true, msg -> msg.replace(PLACEHOLDER_PLAYER, args[1])); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-online", true, msg -> msg.replace(PLACEHOLDER_PLAYER, args[1]));
} }
} } else
else SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.usage", true, msg -> msg.replace("%usage%", "/sf research <Player> <all/reset/Research>")); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.usage", true, msg -> msg.replace("%usage%", "/sf research <Player> <all/reset/Research>"));
} }
} }
@ -68,8 +64,7 @@ class ResearchCommand extends SubCommand {
UnaryOperator<String> variables = msg -> msg.replace(PLACEHOLDER_PLAYER, player.getName()).replace(PLACEHOLDER_RESEARCH, research.get().getName(player)); UnaryOperator<String> variables = msg -> msg.replace(PLACEHOLDER_PLAYER, player.getName()).replace(PLACEHOLDER_RESEARCH, research.get().getName(player));
SlimefunPlugin.getLocalization().sendMessage(player, "messages.give-research", true, variables); SlimefunPlugin.getLocalization().sendMessage(player, "messages.give-research", true, variables);
}); });
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-valid-research", true, msg -> msg.replace(PLACEHOLDER_RESEARCH, input)); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-valid-research", true, msg -> msg.replace(PLACEHOLDER_RESEARCH, input));
} }
} }

View File

@ -24,16 +24,13 @@ class SearchCommand extends SubCommand {
if (args.length > 1) { if (args.length > 1) {
String query = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); String query = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
PlayerProfile.get((Player) sender, profile -> SlimefunGuide.openSearch(profile, query, true, true)); PlayerProfile.get((Player) sender, profile -> SlimefunGuide.openSearch(profile, query, true, true));
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.usage", true, msg -> msg.replace("%usage%", "/sf search <SearchTerm>")); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.usage", true, msg -> msg.replace("%usage%", "/sf search <SearchTerm>"));
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true);
} }
} }

View File

@ -26,17 +26,14 @@ class StatsCommand extends SubCommand {
if (player.isPresent()) { if (player.isPresent()) {
PlayerProfile.get(player.get(), profile -> profile.sendStats(sender)); PlayerProfile.get(player.get(), profile -> profile.sendStats(sender));
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-online", true, msg -> msg.replace("%player%", args[1])); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.not-online", true, msg -> msg.replace("%player%", args[1]));
} }
} } else
else SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} } else if (sender instanceof Player) {
else if (sender instanceof Player) {
PlayerProfile.get((Player) sender, profile -> profile.sendStats(sender)); PlayerProfile.get((Player) sender, profile -> profile.sendStats(sender));
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players", true);
} }
} }

View File

@ -23,28 +23,23 @@ class TeleporterCommand extends SubCommand {
if (args.length == 1) { if (args.length == 1) {
Player p = (Player) sender; Player p = (Player) sender;
SlimefunPlugin.getGPSNetwork().getTeleportationManager().openTeleporterGUI(p, p.getUniqueId(), p.getLocation().getBlock().getRelative(BlockFace.DOWN), 999999999); SlimefunPlugin.getGPSNetwork().getTeleportationManager().openTeleporterGUI(p, p.getUniqueId(), p.getLocation().getBlock().getRelative(BlockFace.DOWN), 999999999);
} } else if (args.length == 2) {
else if (args.length == 2) {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]); OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
if (player.getName() != null) { if (player.getName() != null) {
SlimefunPlugin.getGPSNetwork().getTeleportationManager().openTeleporterGUI((Player) sender, player.getUniqueId(), ((Player) sender).getLocation().getBlock().getRelative(BlockFace.DOWN), 999999999); SlimefunPlugin.getGPSNetwork().getTeleportationManager().openTeleporterGUI((Player) sender, player.getUniqueId(), ((Player) sender).getLocation().getBlock().getRelative(BlockFace.DOWN), 999999999);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.unknown-player", msg -> msg.replace("%player%", args[1])); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.unknown-player", msg -> msg.replace("%player%", args[1]));
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.usage", msg -> msg.replace("%usage%", "/sf teleporter [Player]")); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.usage", msg -> msg.replace("%usage%", "/sf teleporter [Player]"));
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission"); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission");
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players"); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.only-players");
} }
} }

View File

@ -18,8 +18,7 @@ class TimingsCommand extends SubCommand {
if (sender.hasPermission("slimefun.command.timings") || sender instanceof ConsoleCommandSender) { if (sender.hasPermission("slimefun.command.timings") || sender instanceof ConsoleCommandSender) {
sender.sendMessage("Please wait a second... The results are coming in!"); sender.sendMessage("Please wait a second... The results are coming in!");
SlimefunPlugin.getProfiler().requestSummary(sender); SlimefunPlugin.getProfiler().requestSummary(sender);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} }

View File

@ -51,13 +51,11 @@ class VersionsCommand extends SubCommand {
if (Bukkit.getPluginManager().isPluginEnabled(plugin)) { if (Bukkit.getPluginManager().isPluginEnabled(plugin)) {
sender.sendMessage(ChatColor.GREEN + " " + plugin.getName() + ChatColor.DARK_GREEN + " v" + version); sender.sendMessage(ChatColor.GREEN + " " + plugin.getName() + ChatColor.DARK_GREEN + " v" + version);
} } else {
else {
sender.sendMessage(ChatColor.RED + " " + plugin.getName() + ChatColor.DARK_RED + " v" + version); sender.sendMessage(ChatColor.RED + " " + plugin.getName() + ChatColor.DARK_RED + " v" + version);
} }
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true); SlimefunPlugin.getLocalization().sendMessage(sender, "messages.no-permission", true);
} }
} }

View File

@ -105,8 +105,7 @@ public class GuideHistory {
if (lastEntry != null && lastEntry.getIndexedObject().equals(object)) { if (lastEntry != null && lastEntry.getIndexedObject().equals(object)) {
lastEntry.setPage(page); lastEntry.setPage(page);
} } else {
else {
queue.add(new GuideEntry<>(object, page)); queue.add(new GuideEntry<>(object, page));
} }
} }
@ -167,20 +166,15 @@ public class GuideHistory {
private <T> void open(@Nonnull SlimefunGuideImplementation guide, @Nullable GuideEntry<T> entry) { private <T> void open(@Nonnull SlimefunGuideImplementation guide, @Nullable GuideEntry<T> entry) {
if (entry == null) { if (entry == null) {
guide.openMainMenu(profile, 1); guide.openMainMenu(profile, 1);
} } else if (entry.getIndexedObject() instanceof Category) {
else if (entry.getIndexedObject() instanceof Category) {
guide.openCategory(profile, (Category) entry.getIndexedObject(), entry.getPage()); guide.openCategory(profile, (Category) entry.getIndexedObject(), entry.getPage());
} } else if (entry.getIndexedObject() instanceof SlimefunItem) {
else if (entry.getIndexedObject() instanceof SlimefunItem) {
guide.displayItem(profile, (SlimefunItem) entry.getIndexedObject(), false); guide.displayItem(profile, (SlimefunItem) entry.getIndexedObject(), false);
} } else if (entry.getIndexedObject() instanceof ItemStack) {
else if (entry.getIndexedObject() instanceof ItemStack) {
guide.displayItem(profile, (ItemStack) entry.getIndexedObject(), entry.getPage(), false); guide.displayItem(profile, (ItemStack) entry.getIndexedObject(), entry.getPage(), false);
} } else if (entry.getIndexedObject() instanceof String) {
else if (entry.getIndexedObject() instanceof String) {
guide.openSearch(profile, (String) entry.getIndexedObject(), false); guide.openSearch(profile, (String) entry.getIndexedObject(), false);
} } else {
else {
throw new IllegalStateException("Unknown GuideHistory entry: " + entry.getIndexedObject()); throw new IllegalStateException("Unknown GuideHistory entry: " + entry.getIndexedObject());
} }
} }

View File

@ -41,14 +41,11 @@ public final class SlimefunGuide {
public static void openGuide(Player p, ItemStack guide) { public static void openGuide(Player p, ItemStack guide) {
if (SlimefunUtils.isItemSimilar(guide, getItem(SlimefunGuideLayout.CHEST), true)) { if (SlimefunUtils.isItemSimilar(guide, getItem(SlimefunGuideLayout.CHEST), true)) {
openGuide(p, SlimefunGuideLayout.CHEST); openGuide(p, SlimefunGuideLayout.CHEST);
} } else if (SlimefunUtils.isItemSimilar(guide, getItem(SlimefunGuideLayout.BOOK), true)) {
else if (SlimefunUtils.isItemSimilar(guide, getItem(SlimefunGuideLayout.BOOK), true)) {
openGuide(p, SlimefunGuideLayout.BOOK); openGuide(p, SlimefunGuideLayout.BOOK);
} } else if (SlimefunUtils.isItemSimilar(guide, getItem(SlimefunGuideLayout.CHEAT_SHEET), true)) {
else if (SlimefunUtils.isItemSimilar(guide, getItem(SlimefunGuideLayout.CHEAT_SHEET), true)) {
openGuide(p, SlimefunGuideLayout.CHEAT_SHEET); openGuide(p, SlimefunGuideLayout.CHEAT_SHEET);
} } else {
else {
// When using /sf cheat or /sf open_guide, ItemStack is null. // When using /sf cheat or /sf open_guide, ItemStack is null.
openGuide(p, SlimefunGuideLayout.CHEST); openGuide(p, SlimefunGuideLayout.CHEST);
} }
@ -65,8 +62,7 @@ public final class SlimefunGuide {
PlayerProfile profile = optional.get(); PlayerProfile profile = optional.get();
SlimefunGuideImplementation guide = SlimefunPlugin.getRegistry().getGuideLayout(layout); SlimefunGuideImplementation guide = SlimefunPlugin.getRegistry().getGuideLayout(layout);
profile.getGuideHistory().openLastEntry(guide); profile.getGuideHistory().openLastEntry(guide);
} } else {
else {
openMainMenuAsync(p, layout, 1); openMainMenuAsync(p, layout, 1);
} }
} }
@ -82,13 +78,15 @@ public final class SlimefunGuide {
} }
public static void openCategory(PlayerProfile profile, Category category, SlimefunGuideLayout layout, int selectedPage) { public static void openCategory(PlayerProfile profile, Category category, SlimefunGuideLayout layout, int selectedPage) {
if (category == null) return; if (category == null)
return;
SlimefunPlugin.getRegistry().getGuideLayout(layout).openCategory(profile, category, selectedPage); SlimefunPlugin.getRegistry().getGuideLayout(layout).openCategory(profile, category, selectedPage);
} }
public static void openSearch(PlayerProfile profile, String input, boolean survival, boolean addToHistory) { public static void openSearch(PlayerProfile profile, String input, boolean survival, boolean addToHistory) {
SlimefunGuideImplementation layout = SlimefunPlugin.getRegistry().getGuideLayout(SlimefunGuideLayout.CHEST); SlimefunGuideImplementation layout = SlimefunPlugin.getRegistry().getGuideLayout(SlimefunGuideLayout.CHEST);
if (!survival) layout = SlimefunPlugin.getRegistry().getGuideLayout(SlimefunGuideLayout.CHEAT_SHEET); if (!survival)
layout = SlimefunPlugin.getRegistry().getGuideLayout(SlimefunGuideLayout.CHEAT_SHEET);
layout.openSearch(profile, input, addToHistory); layout.openSearch(profile, input, addToHistory);
} }
@ -107,8 +105,7 @@ public final class SlimefunGuide {
public static SlimefunGuideLayout getDefaultLayout() { public static SlimefunGuideLayout getDefaultLayout() {
if (SlimefunPlugin.getCfg().getBoolean("guide.default-view-book")) { if (SlimefunPlugin.getCfg().getBoolean("guide.default-view-book")) {
return SlimefunGuideLayout.BOOK; return SlimefunGuideLayout.BOOK;
} } else {
else {
return SlimefunGuideLayout.CHEST; return SlimefunGuideLayout.CHEST;
} }
} }

View File

@ -71,8 +71,7 @@ public interface SlimefunGuideImplementation {
if (p.getGameMode() == GameMode.CREATIVE && SlimefunPlugin.getRegistry().isFreeCreativeResearchingEnabled()) { if (p.getGameMode() == GameMode.CREATIVE && SlimefunPlugin.getRegistry().isFreeCreativeResearchingEnabled()) {
research.unlock(p, true, callback); research.unlock(p, true, callback);
} } else {
else {
p.setLevel(p.getLevel() - research.getCost()); p.setLevel(p.getLevel() - research.getCost());
research.unlock(p, false, callback); research.unlock(p, false, callback);
} }

View File

@ -30,8 +30,7 @@ class FireworksOption implements SlimefunGuideOption<Boolean> {
boolean enabled = getSelectedOption(p, guide).orElse(true); boolean enabled = getSelectedOption(p, guide).orElse(true);
ItemStack item = new CustomItem(Material.FIREWORK_ROCKET, "&bFireworks: &" + (enabled ? "aYes" : "4No"), "", "&7You can now toggle whether you", "&7will be presented with a big firework", "&7upon researching an item.", "", "&7\u21E8 &eClick to " + (enabled ? "disable" : "enable") + " your fireworks"); ItemStack item = new CustomItem(Material.FIREWORK_ROCKET, "&bFireworks: &" + (enabled ? "aYes" : "4No"), "", "&7You can now toggle whether you", "&7will be presented with a big firework", "&7upon researching an item.", "", "&7\u21E8 &eClick to " + (enabled ? "disable" : "enable") + " your fireworks");
return Optional.of(item); return Optional.of(item);
} } else {
else {
return Optional.empty(); return Optional.empty();
} }
} }

View File

@ -40,11 +40,9 @@ class GuideLayoutOption implements SlimefunGuideOption<SlimefunGuideLayout> {
if (layout == SlimefunGuideLayout.CHEST) { if (layout == SlimefunGuideLayout.CHEST) {
item.setType(Material.CHEST); item.setType(Material.CHEST);
} } else if (layout == SlimefunGuideLayout.BOOK) {
else if (layout == SlimefunGuideLayout.BOOK) {
item.setType(Material.BOOK); item.setType(Material.BOOK);
} } else {
else {
item.setType(Material.COMMAND_BLOCK); item.setType(Material.COMMAND_BLOCK);
} }
@ -93,8 +91,7 @@ class GuideLayoutOption implements SlimefunGuideOption<SlimefunGuideLayout> {
} }
return SlimefunGuideLayout.CHEST; return SlimefunGuideLayout.CHEST;
} } else {
else {
return layout == SlimefunGuideLayout.CHEST ? SlimefunGuideLayout.BOOK : SlimefunGuideLayout.CHEST; return layout == SlimefunGuideLayout.CHEST ? SlimefunGuideLayout.BOOK : SlimefunGuideLayout.CHEST;
} }
} }

View File

@ -50,8 +50,7 @@ class PlayerLanguageOption implements SlimefunGuideOption<String> {
ItemStack item = new CustomItem(language.getItem(), "&7" + SlimefunPlugin.getLocalization().getMessage(p, "guide.languages.selected-language") + " &a" + languageName, lore.toArray(new String[0])); ItemStack item = new CustomItem(language.getItem(), "&7" + SlimefunPlugin.getLocalization().getMessage(p, "guide.languages.selected-language") + " &a" + languageName, lore.toArray(new String[0]));
return Optional.of(item); return Optional.of(item);
} } else {
else {
return Optional.empty(); return Optional.empty();
} }
} }
@ -70,8 +69,7 @@ class PlayerLanguageOption implements SlimefunGuideOption<String> {
public void setSelectedOption(Player p, ItemStack guide, String value) { public void setSelectedOption(Player p, ItemStack guide, String value) {
if (value == null) { if (value == null) {
PersistentDataAPI.remove(p, getKey()); PersistentDataAPI.remove(p, getKey());
} } else {
else {
PersistentDataAPI.setString(p, getKey(), value); PersistentDataAPI.setString(p, getKey(), value);
} }
} }
@ -88,15 +86,13 @@ class PlayerLanguageOption implements SlimefunGuideOption<String> {
SlimefunGuideSettings.openSettings(pl, guide); SlimefunGuideSettings.openSettings(pl, guide);
return false; return false;
}); });
} } else if (i == 7) {
else if (i == 7) {
menu.addItem(7, new CustomItem(SlimefunUtils.getCustomHead(HeadTexture.ADD_NEW_LANGUAGE.getTexture()), SlimefunPlugin.getLocalization().getMessage(p, "guide.languages.translations.name"), "", "&7\u21E8 &e" + SlimefunPlugin.getLocalization().getMessage(p, "guide.languages.translations.lore")), (pl, slot, item, action) -> { menu.addItem(7, new CustomItem(SlimefunUtils.getCustomHead(HeadTexture.ADD_NEW_LANGUAGE.getTexture()), SlimefunPlugin.getLocalization().getMessage(p, "guide.languages.translations.name"), "", "&7\u21E8 &e" + SlimefunPlugin.getLocalization().getMessage(p, "guide.languages.translations.lore")), (pl, slot, item, action) -> {
ChatUtils.sendURL(pl, "https://github.com/Slimefun/Slimefun4/wiki/Translating-Slimefun"); ChatUtils.sendURL(pl, "https://github.com/Slimefun/Slimefun4/wiki/Translating-Slimefun");
pl.closeInventory(); pl.closeInventory();
return false; return false;
}); });
} } else {
else {
menu.addItem(i, ChestMenuUtils.getBackground(), ChestMenuUtils.getEmptyClickHandler()); menu.addItem(i, ChestMenuUtils.getBackground(), ChestMenuUtils.getEmptyClickHandler());
} }
} }

View File

@ -113,8 +113,7 @@ public final class SlimefunGuideSettings {
ChatUtils.sendURL(pl, "https://github.com/Slimefun/Slimefun4/issues"); ChatUtils.sendURL(pl, "https://github.com/Slimefun/Slimefun4/issues");
return false; return false;
}); });
} } else {
else {
menu.addItem(49, ChestMenuUtils.getBackground(), ChestMenuUtils.getEmptyClickHandler()); menu.addItem(49, ChestMenuUtils.getBackground(), ChestMenuUtils.getEmptyClickHandler());
} }

View File

@ -122,8 +122,7 @@ public abstract class MultiBlockMachine extends SlimefunItem implements NotPlace
} }
return true; return true;
} } else {
else {
return false; return false;
} }
}; };
@ -156,8 +155,7 @@ public abstract class MultiBlockMachine extends SlimefunItem implements NotPlace
// check for the dispenser, only refactored. // check for the dispenser, only refactored.
if (outputInv == null && InvUtils.fits(placeCheckerInv, product)) { if (outputInv == null && InvUtils.fits(placeCheckerInv, product)) {
return dispInv; return dispInv;
} } else {
else {
return outputInv; return outputInv;
} }
} }
@ -195,11 +193,9 @@ public abstract class MultiBlockMachine extends SlimefunItem implements NotPlace
for (ItemStack item : items) { for (ItemStack item : items) {
if (item == null) { if (item == null) {
materials.add(null); materials.add(null);
} } else if (item.getType() == Material.FLINT_AND_STEEL) {
else if (item.getType() == Material.FLINT_AND_STEEL) {
materials.add(Material.FIRE); materials.add(Material.FIRE);
} } else {
else {
materials.add(item.getType()); materials.add(item.getType());
} }
} }

View File

@ -57,8 +57,7 @@ public class CargoNet extends ChestTerminalNetwork {
if (cargoNetwork.isPresent()) { if (cargoNetwork.isPresent()) {
return cargoNetwork.get(); return cargoNetwork.get();
} } else {
else {
CargoNet network = new CargoNet(l); CargoNet network = new CargoNet(l);
SlimefunPlugin.getNetworkManager().registerNetwork(network); SlimefunPlugin.getNetworkManager().registerNetwork(network);
return network; return network;
@ -152,8 +151,7 @@ public class CargoNet extends ChestTerminalNetwork {
if (connectorNodes.isEmpty() && terminusNodes.isEmpty()) { if (connectorNodes.isEmpty() && terminusNodes.isEmpty()) {
SimpleHologram.update(b, "&cNo Cargo Nodes found"); SimpleHologram.update(b, "&cNo Cargo Nodes found");
} } else {
else {
SimpleHologram.update(b, "&7Status: &a&lONLINE"); SimpleHologram.update(b, "&7Status: &a&lONLINE");
// Skip ticking if the threshold is not reached. The delay is not same as minecraft tick, // Skip ticking if the threshold is not reached. The delay is not same as minecraft tick,
@ -192,8 +190,7 @@ public class CargoNet extends ChestTerminalNetwork {
if (frequency == 16) { if (frequency == 16) {
chestTerminalNodes.add(node); chestTerminalNodes.add(node);
} } else if (frequency >= 0 && frequency < 16) {
else if (frequency >= 0 && frequency < 16) {
inputs.put(node, frequency); inputs.put(node, frequency);
} }
} }
@ -252,8 +249,7 @@ public class CargoNet extends ChestTerminalNetwork {
try { try {
String str = BlockStorage.getLocationInfo(node).getString("frequency"); String str = BlockStorage.getLocationInfo(node).getString("frequency");
return str == null ? 0 : Integer.parseInt(str); return str == null ? 0 : Integer.parseInt(str);
} } catch (Exception x) {
catch (Exception x) {
Slimefun.getLogger().log(Level.SEVERE, x, () -> "An Error occurred while parsing a Cargo Node Frequency (" + node.getWorld().getName() + " - " + node.getBlockX() + "," + node.getBlockY() + "," + +node.getBlockZ() + ")"); Slimefun.getLogger().log(Level.SEVERE, x, () -> "An Error occurred while parsing a Cargo Node Frequency (" + node.getWorld().getName() + " - " + node.getBlockX() + "," + node.getBlockY() + "," + +node.getBlockZ() + ")");
return 0; return 0;
} }

View File

@ -111,25 +111,22 @@ class CargoNetworkTask implements Runnable {
// Check if the original slot hasn't been occupied in the meantime // Check if the original slot hasn't been occupied in the meantime
if (inv.getItem(previousSlot) == null) { if (inv.getItem(previousSlot) == null) {
inv.setItem(previousSlot, stack); inv.setItem(previousSlot, stack);
} } else {
else {
// Try to add the item into another available slot then // Try to add the item into another available slot then
ItemStack rest = inv.addItem(stack).get(0); ItemStack rest = inv.addItem(stack).get(0);
if (rest != null) { if (rest != null) {
// If the item still couldn't be inserted, simply drop it on the ground // If the item still couldn't be inserted, simply drop it on the ground
inputTarget.getWorld().dropItem(inputTarget.getLocation().add(0, 1, 0), rest); inputTarget.getWorld().dropItem(inputTarget.getLocation().add(0, 1, 0), rest);
} }
} }
} } else {
else {
DirtyChestMenu menu = CargoUtils.getChestMenu(inputTarget); DirtyChestMenu menu = CargoUtils.getChestMenu(inputTarget);
if (menu != null) { if (menu != null) {
if (menu.getItemInSlot(previousSlot) == null) { if (menu.getItemInSlot(previousSlot) == null) {
menu.replaceExistingItem(previousSlot, stack); menu.replaceExistingItem(previousSlot, stack);
} } else {
else {
inputTarget.getWorld().dropItem(inputTarget.getLocation().add(0, 1, 0), stack); inputTarget.getWorld().dropItem(inputTarget.getLocation().add(0, 1, 0), stack);
} }
} }
@ -183,8 +180,7 @@ class CargoNetworkTask implements Runnable {
} }
index++; index++;
} } else {
else {
index = 1; index = 1;
} }

View File

@ -92,30 +92,24 @@ final class CargoUtils {
if (isSmeltable(item, true)) { if (isSmeltable(item, true)) {
// Any non-smeltable items should not land in the upper slot // Any non-smeltable items should not land in the upper slot
return new int[] { 0, 2 }; return new int[] { 0, 2 };
} } else {
else {
return new int[] { 1, 2 }; return new int[] { 1, 2 };
} }
} } else {
else {
return new int[] { 0, 1 }; return new int[] { 0, 1 };
} }
} } else if (inv instanceof BrewerInventory) {
else if (inv instanceof BrewerInventory) {
if (isPotion(item)) { if (isPotion(item)) {
// Slots for potions // Slots for potions
return new int[] { 0, 3 }; return new int[] { 0, 3 };
} } else if (item != null && item.getType() == Material.BLAZE_POWDER) {
else if (item != null && item.getType() == Material.BLAZE_POWDER) {
// Blaze Powder slot // Blaze Powder slot
return new int[] { 4, 5 }; return new int[] { 4, 5 };
} } else {
else {
// Input slot // Input slot
return new int[] { 3, 4 }; return new int[] { 3, 4 };
} }
} } else {
else {
// Slot 0-size // Slot 0-size
return new int[] { 0, inv.getSize() }; return new int[] { 0, inv.getSize() };
} }
@ -125,12 +119,10 @@ final class CargoUtils {
if (inv instanceof FurnaceInventory) { if (inv instanceof FurnaceInventory) {
// Slot 2-3 // Slot 2-3
return new int[] { 2, 3 }; return new int[] { 2, 3 };
} } else if (inv instanceof BrewerInventory) {
else if (inv instanceof BrewerInventory) {
// Slot 0-3 // Slot 0-3
return new int[] { 0, 3 }; return new int[] { 0, 3 };
} } else {
else {
// Slot 0-size // Slot 0-size
return new int[] { 0, inv.getSize() }; return new int[] { 0, inv.getSize() };
} }
@ -169,8 +161,7 @@ final class CargoUtils {
is.setAmount(is.getAmount() - template.getAmount()); is.setAmount(is.getAmount() - template.getAmount());
menu.replaceExistingItem(slot, is.clone()); menu.replaceExistingItem(slot, is.clone());
return template; return template;
} } else {
else {
menu.replaceExistingItem(slot, null); menu.replaceExistingItem(slot, null);
return is; return is;
} }
@ -196,8 +187,7 @@ final class CargoUtils {
if (itemInSlot.getAmount() > template.getAmount()) { if (itemInSlot.getAmount() > template.getAmount()) {
itemInSlot.setAmount(itemInSlot.getAmount() - template.getAmount()); itemInSlot.setAmount(itemInSlot.getAmount() - template.getAmount());
return template; return template;
} } else {
else {
ItemStack clone = itemInSlot.clone(); ItemStack clone = itemInSlot.clone();
itemInSlot.setAmount(0); itemInSlot.setAmount(0);
return clone; return clone;
@ -220,8 +210,7 @@ final class CargoUtils {
return new ItemStackAndInteger(is, slot); return new ItemStackAndInteger(is, slot);
} }
} }
} } else if (hasInventory(target)) {
else if (hasInventory(target)) {
Inventory inventory = inventories.get(target.getLocation()); Inventory inventory = inventories.get(target.getLocation());
if (inventory != null) { if (inventory != null) {
@ -304,8 +293,7 @@ final class CargoUtils {
itemInSlot.setAmount(Math.min(amount, maxStackSize)); itemInSlot.setAmount(Math.min(amount, maxStackSize));
if (amount > maxStackSize) { if (amount > maxStackSize) {
stack.setAmount(amount - maxStackSize); stack.setAmount(amount - maxStackSize);
} } else {
else {
stack = null; stack = null;
} }
@ -332,8 +320,7 @@ final class CargoUtils {
if (itemInSlot == null) { if (itemInSlot == null) {
inv.setItem(slot, stack); inv.setItem(slot, stack);
return null; return null;
} } else {
else {
int maxStackSize = itemInSlot.getType().getMaxStackSize(); int maxStackSize = itemInSlot.getType().getMaxStackSize();
if (SlimefunUtils.isItemSimilar(itemInSlot, wrapper, true, false) && itemInSlot.getAmount() < maxStackSize) { if (SlimefunUtils.isItemSimilar(itemInSlot, wrapper, true, false) && itemInSlot.getAmount() < maxStackSize) {
@ -341,8 +328,7 @@ final class CargoUtils {
if (amount > maxStackSize) { if (amount > maxStackSize) {
stack.setAmount(amount - maxStackSize); stack.setAmount(amount - maxStackSize);
} } else {
else {
stack = null; stack = null;
} }
@ -372,8 +358,12 @@ final class CargoUtils {
Config blockData = BlockStorage.getLocationInfo(block.getLocation()); Config blockData = BlockStorage.getLocationInfo(block.getLocation());
String id = blockData.getString("id"); String id = blockData.getString("id");
// Cargo Output nodes have no filter actually if (id == null) {
if (id.equals("CARGO_NODE_OUTPUT")) { // This should normally not happen but if it does...
// Don't accept any items.
return false;
} else if (id.equals("CARGO_NODE_OUTPUT")) {
// Cargo Output nodes have no filter actually
return true; return true;
} }
@ -387,8 +377,7 @@ final class CargoUtils {
boolean lore = "true".equals(blockData.getString("filter-lore")); boolean lore = "true".equals(blockData.getString("filter-lore"));
boolean allowByDefault = !"whitelist".equals(blockData.getString("filter-type")); boolean allowByDefault = !"whitelist".equals(blockData.getString("filter-type"));
return matchesFilterList(item, menu, lore, allowByDefault); return matchesFilterList(item, menu, lore, allowByDefault);
} } catch (Exception x) {
catch (Exception x) {
Slimefun.getLogger().log(Level.SEVERE, x, () -> "An Exception occurred while trying to filter items for a Cargo Node (" + id + ") at " + new BlockPosition(block)); Slimefun.getLogger().log(Level.SEVERE, x, () -> "An Exception occurred while trying to filter items for a Cargo Node (" + id + ") at " + new BlockPosition(block));
return false; return false;
} }
@ -449,8 +438,7 @@ final class CargoUtils {
private static boolean isSmeltable(@Nullable ItemStack stack, boolean lazy) { private static boolean isSmeltable(@Nullable ItemStack stack, boolean lazy) {
if (lazy) { if (lazy) {
return stack != null && Tag.LOGS.isTagged(stack.getType()); return stack != null && Tag.LOGS.isTagged(stack.getType());
} } else {
else {
return SlimefunPlugin.getMinecraftRecipeService().isSmeltable(stack); return SlimefunPlugin.getMinecraftRecipeService().isSmeltable(stack);
} }
} }

View File

@ -164,15 +164,13 @@ abstract class ChestTerminalNetwork extends Network {
if (is != null) { if (is != null) {
if (stack == null) { if (stack == null) {
stack = is; stack = is;
} } else {
else {
stack = new CustomItem(stack, stack.getAmount() + is.getAmount()); stack = new CustomItem(stack, stack.getAmount() + is.getAmount());
} }
if (is.getAmount() == item.getAmount()) { if (is.getAmount() == item.getAmount()) {
break; break;
} } else {
else {
item = new CustomItem(item, item.getAmount() - is.getAmount()); item = new CustomItem(item, item.getAmount() - is.getAmount());
} }
} }
@ -184,8 +182,7 @@ abstract class ChestTerminalNetwork extends Network {
if (prev == null) { if (prev == null) {
terminal.replaceExistingItem(slot, stack); terminal.replaceExistingItem(slot, stack);
} } else {
else {
terminal.replaceExistingItem(slot, new CustomItem(stack, stack.getAmount() + prev.getAmount())); terminal.replaceExistingItem(slot, new CustomItem(stack, stack.getAmount() + prev.getAmount()));
} }
} }
@ -316,15 +313,13 @@ abstract class ChestTerminalNetwork extends Network {
firstTerminal = l; firstTerminal = l;
} }
} }
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
item.error("An Exception was caused while trying to tick Chest terminals", x); item.error("An Exception was caused while trying to tick Chest terminals", x);
} }
if (firstTerminal != null) { if (firstTerminal != null) {
return SlimefunPlugin.getProfiler().closeEntry(firstTerminal, item, timestamp); return SlimefunPlugin.getProfiler().closeEntry(firstTerminal, item, timestamp);
} } else {
else {
return System.nanoTime() - timestamp; return System.nanoTime() - timestamp;
} }
} }
@ -350,8 +345,7 @@ abstract class ChestTerminalNetwork extends Network {
if (stack.getMaxStackSize() > 1) { if (stack.getMaxStackSize() > 1) {
int amount = item.getInt() > stack.getMaxStackSize() ? stack.getMaxStackSize() : item.getInt(); int amount = item.getInt() > stack.getMaxStackSize() ? stack.getMaxStackSize() : item.getInt();
lore.add(ChatColors.color("&7<Left Click: Request 1 | Right Click: Request " + amount + ">")); lore.add(ChatColors.color("&7<Left Click: Request 1 | Right Click: Request " + amount + ">"));
} } else {
else {
lore.add(ChatColors.color("&7<Left Click: Request 1>")); lore.add(ChatColors.color("&7<Left Click: Request 1>"));
} }
@ -371,8 +365,7 @@ abstract class ChestTerminalNetwork extends Network {
return false; return false;
}); });
} } else {
else {
terminal.replaceExistingItem(slot, terminalPlaceholderItem); terminal.replaceExistingItem(slot, terminalPlaceholderItem);
terminal.addMenuClickHandler(slot, ChestMenuUtils.getEmptyClickHandler()); terminal.addMenuClickHandler(slot, ChestMenuUtils.getEmptyClickHandler());
} }
@ -403,18 +396,15 @@ abstract class ChestTerminalNetwork extends Network {
ItemStack is = menu.getItemInSlot(slot); ItemStack is = menu.getItemInSlot(slot);
filter(is, items, l); filter(is, items, l);
} }
} } else if (BlockStorage.hasInventory(target)) {
else if (BlockStorage.hasInventory(target)) {
BlockMenu blockMenu = BlockStorage.getInventory(target); BlockMenu blockMenu = BlockStorage.getInventory(target);
if (blockMenu.getPreset().getID().startsWith("BARREL_")) { if (blockMenu.getPreset().getID().startsWith("BARREL_")) {
gatherItemsFromBarrel(l, blockMenu, items); gatherItemsFromBarrel(l, blockMenu, items);
} } else {
else {
handleWithdraw(blockMenu, items, l); handleWithdraw(blockMenu, items, l);
} }
} } else if (CargoUtils.hasInventory(target)) {
else if (CargoUtils.hasInventory(target)) {
BlockState state = PaperLib.getBlockState(target, false).getState(); BlockState state = PaperLib.getBlockState(target, false).getState();
if (state instanceof InventoryHolder) { if (state instanceof InventoryHolder) {
@ -457,8 +447,7 @@ abstract class ChestTerminalNetwork extends Network {
} }
} }
} }
} } catch (Exception x) {
catch (Exception x) {
Slimefun.getLogger().log(Level.SEVERE, "An Exception occurred while trying to read data from a Barrel", x); Slimefun.getLogger().log(Level.SEVERE, "An Exception occurred while trying to read data from a Barrel", x);
} }
} }

View File

@ -47,8 +47,7 @@ class ItemRequest {
if (obj instanceof ItemRequest) { if (obj instanceof ItemRequest) {
ItemRequest request = (ItemRequest) obj; ItemRequest request = (ItemRequest) obj;
return Objects.equals(item, request.item) && Objects.equals(terminal, request.terminal) && slot == request.slot && flow == request.flow; return Objects.equals(item, request.item) && Objects.equals(terminal, request.terminal) && slot == request.slot && flow == request.flow;
} } else {
else {
return false; return false;
} }
} }

View File

@ -68,8 +68,7 @@ public class EnergyNet extends Network {
if (component == null) { if (component == null) {
return null; return null;
} } else {
else {
switch (component.getEnergyComponentType()) { switch (component.getEnergyComponentType()) {
case CONNECTOR: case CONNECTOR:
case CAPACITOR: case CAPACITOR:
@ -103,8 +102,7 @@ public class EnergyNet extends Network {
case GENERATOR: case GENERATOR:
if (component instanceof EnergyNetProvider) { if (component instanceof EnergyNetProvider) {
generators.put(l, (EnergyNetProvider) component); generators.put(l, (EnergyNetProvider) component);
} } else if (component instanceof SlimefunItem) {
else if (component instanceof SlimefunItem) {
((SlimefunItem) component).warn("This Item is marked as a GENERATOR but does not implement the interface EnergyNetProvider!"); ((SlimefunItem) component).warn("This Item is marked as a GENERATOR but does not implement the interface EnergyNetProvider!");
} }
break; break;
@ -127,8 +125,7 @@ public class EnergyNet extends Network {
if (connectorNodes.isEmpty() && terminusNodes.isEmpty()) { if (connectorNodes.isEmpty() && terminusNodes.isEmpty()) {
SimpleHologram.update(b, "&4No Energy Network found"); SimpleHologram.update(b, "&4No Energy Network found");
} } else {
else {
int supply = tickAllGenerators(timestamp::getAndAdd) + tickAllCapacitors(); int supply = tickAllGenerators(timestamp::getAndAdd) + tickAllCapacitors();
int remainingEnergy = supply; int remainingEnergy = supply;
int demand = 0; int demand = 0;
@ -147,8 +144,7 @@ public class EnergyNet extends Network {
if (remainingEnergy > availableSpace) { if (remainingEnergy > availableSpace) {
component.setCharge(loc, capacity); component.setCharge(loc, capacity);
remainingEnergy -= availableSpace; remainingEnergy -= availableSpace;
} } else {
else {
component.setCharge(loc, charge + remainingEnergy); component.setCharge(loc, charge + remainingEnergy);
remainingEnergy = 0; remainingEnergy = 0;
} }
@ -175,13 +171,11 @@ public class EnergyNet extends Network {
if (remainingEnergy > capacity) { if (remainingEnergy > capacity) {
component.setCharge(loc, capacity); component.setCharge(loc, capacity);
remainingEnergy -= capacity; remainingEnergy -= capacity;
} } else {
else {
component.setCharge(loc, remainingEnergy); component.setCharge(loc, remainingEnergy);
remainingEnergy = 0; remainingEnergy = 0;
} }
} } else {
else {
component.setCharge(loc, 0); component.setCharge(loc, 0);
} }
} }
@ -195,13 +189,11 @@ public class EnergyNet extends Network {
if (remainingEnergy > capacity) { if (remainingEnergy > capacity) {
component.setCharge(loc, capacity); component.setCharge(loc, capacity);
remainingEnergy -= capacity; remainingEnergy -= capacity;
} } else {
else {
component.setCharge(loc, remainingEnergy); component.setCharge(loc, remainingEnergy);
remainingEnergy = 0; remainingEnergy = 0;
} }
} } else {
else {
component.setCharge(loc, 0); component.setCharge(loc, 0);
} }
} }
@ -233,12 +225,10 @@ public class EnergyNet extends Network {
loc.getBlock().setType(Material.LAVA); loc.getBlock().setType(Material.LAVA);
loc.getWorld().createExplosion(loc, 0F, false); loc.getWorld().createExplosion(loc, 0F, false);
}); });
} } else {
else {
supply += energy; supply += energy;
} }
} } catch (Exception | LinkageError t) {
catch (Exception | LinkageError t) {
explodedBlocks.add(loc); explodedBlocks.add(loc);
new ErrorReport<>(t, loc, item); new ErrorReport<>(t, loc, item);
} }
@ -266,8 +256,7 @@ public class EnergyNet extends Network {
if (demand > supply) { if (demand > supply) {
String netLoss = DoubleHandler.getFancyDouble(Math.abs(supply - demand)); String netLoss = DoubleHandler.getFancyDouble(Math.abs(supply - demand));
SimpleHologram.update(b, "&4&l- &c" + netLoss + " &7J &e\u26A1"); SimpleHologram.update(b, "&4&l- &c" + netLoss + " &7J &e\u26A1");
} } else {
else {
String netGain = DoubleHandler.getFancyDouble(supply - demand); String netGain = DoubleHandler.getFancyDouble(supply - demand);
SimpleHologram.update(b, "&2&l+ &a" + netGain + " &7J &e\u26A1"); SimpleHologram.update(b, "&2&l+ &a" + netGain + " &7J &e\u26A1");
} }
@ -313,8 +302,7 @@ public class EnergyNet extends Network {
if (energyNetwork.isPresent()) { if (energyNetwork.isPresent()) {
return energyNetwork.get(); return energyNetwork.get();
} } else {
else {
EnergyNet network = new EnergyNet(l); EnergyNet network = new EnergyNet(l);
SlimefunPlugin.getNetworkManager().registerNetwork(network); SlimefunPlugin.getNetworkManager().registerNetwork(network);
return network; return network;

View File

@ -244,8 +244,7 @@ public class Research implements Keyed {
if (!event.isCancelled()) { if (!event.isCancelled()) {
if (instant) { if (instant) {
finishResearch(p, profile, callback); finishResearch(p, profile, callback);
} } else if (SlimefunPlugin.getRegistry().getCurrentlyResearchingPlayers().add(p.getUniqueId())) {
else if (SlimefunPlugin.getRegistry().getCurrentlyResearchingPlayers().add(p.getUniqueId())) {
SlimefunPlugin.getLocalization().sendMessage(p, "messages.research.start", true, msg -> msg.replace(PLACEHOLDER_RESEARCH, getName(p))); SlimefunPlugin.getLocalization().sendMessage(p, "messages.research.start", true, msg -> msg.replace(PLACEHOLDER_RESEARCH, getName(p)));
playResearchAnimation(p); playResearchAnimation(p);

View File

@ -42,8 +42,7 @@ public class BackupService implements Runnable {
if (backups.size() > MAX_BACKUPS) { if (backups.size() > MAX_BACKUPS) {
try { try {
purgeBackups(backups); purgeBackups(backups);
} } catch (IOException e) {
catch (IOException e) {
Slimefun.getLogger().log(Level.WARNING, "Could not delete an old backup", e); Slimefun.getLogger().log(Level.WARNING, "Could not delete an old backup", e);
} }
} }
@ -58,12 +57,10 @@ public class BackupService implements Runnable {
} }
Slimefun.getLogger().log(Level.INFO, "Backed up Slimefun data to: {0}", file.getName()); Slimefun.getLogger().log(Level.INFO, "Backed up Slimefun data to: {0}", file.getName());
} } else {
else {
Slimefun.getLogger().log(Level.WARNING, "Could not create backup-file: {0}", file.getName()); Slimefun.getLogger().log(Level.WARNING, "Could not create backup-file: {0}", file.getName());
} }
} } catch (IOException x) {
catch (IOException x) {
Slimefun.getLogger().log(Level.SEVERE, x, () -> "An Error occurred while creating a backup for Slimefun " + SlimefunPlugin.getVersion()); Slimefun.getLogger().log(Level.SEVERE, x, () -> "An Error occurred while creating a backup for Slimefun " + SlimefunPlugin.getVersion());
} }
} }

View File

@ -65,8 +65,7 @@ public class BlockDataService implements PersistentDataService, Keyed {
if (state instanceof TileState) { if (state instanceof TileState) {
return getString((TileState) state, namespacedKey); return getString((TileState) state, namespacedKey);
} } else {
else {
return Optional.empty(); return Optional.empty();
} }
} }

View File

@ -72,16 +72,14 @@ public class LocalizationService extends SlimefunLocalization implements Persist
if (hasLanguage(serverDefaultLanguage)) { if (hasLanguage(serverDefaultLanguage)) {
setLanguage(serverDefaultLanguage, !serverDefaultLanguage.equals(language)); setLanguage(serverDefaultLanguage, !serverDefaultLanguage.equals(language));
} } else {
else {
setLanguage("en", false); setLanguage("en", false);
plugin.getLogger().log(Level.WARNING, "Could not recognize the given language: \"{0}\"", serverDefaultLanguage); plugin.getLogger().log(Level.WARNING, "Could not recognize the given language: \"{0}\"", serverDefaultLanguage);
} }
Slimefun.getLogger().log(Level.INFO, "Available languages: {0}", String.join(", ", languages.keySet())); Slimefun.getLogger().log(Level.INFO, "Available languages: {0}", String.join(", ", languages.keySet()));
save(); save();
} } else {
else {
translationsEnabled = false; translationsEnabled = false;
defaultLanguage = null; defaultLanguage = null;
} }
@ -186,8 +184,7 @@ public class LocalizationService extends SlimefunLocalization implements Persist
try (BufferedReader reader = new BufferedReader(new InputStreamReader(plugin.getClass().getResourceAsStream(path), StandardCharsets.UTF_8))) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(plugin.getClass().getResourceAsStream(path), StandardCharsets.UTF_8))) {
FileConfiguration config = YamlConfiguration.loadConfiguration(reader); FileConfiguration config = YamlConfiguration.loadConfiguration(reader);
getConfig().getConfiguration().setDefaults(config); getConfig().getConfiguration().setDefaults(config);
} } catch (IOException e) {
catch (IOException e) {
Slimefun.getLogger().log(Level.SEVERE, e, () -> "Failed to load language file: \"" + path + "\""); Slimefun.getLogger().log(Level.SEVERE, e, () -> "Failed to load language file: \"" + path + "\"");
} }
@ -277,8 +274,7 @@ public class LocalizationService extends SlimefunLocalization implements Persist
} }
return config; return config;
} } catch (IOException e) {
catch (IOException e) {
Slimefun.getLogger().log(Level.SEVERE, e, () -> "Failed to load language file into memory: \"" + path + "\""); Slimefun.getLogger().log(Level.SEVERE, e, () -> "Failed to load language file into memory: \"" + path + "\"");
return null; return null;
} }

View File

@ -105,13 +105,11 @@ public class MetricsService {
try { try {
start.invoke(null); start.invoke(null);
plugin.getLogger().info("Metrics build #" + version + " started."); plugin.getLogger().info("Metrics build #" + version + " started.");
} } catch (Exception | LinkageError e) {
catch (Exception | LinkageError e) {
plugin.getLogger().log(Level.WARNING, "Failed to start metrics.", e); plugin.getLogger().log(Level.WARNING, "Failed to start metrics.", e);
} }
}); });
} } catch (Exception | LinkageError e) {
catch (Exception | LinkageError e) {
plugin.getLogger().log(Level.WARNING, "Failed to load the metrics module. Maybe the jar is corrupt?", e); plugin.getLogger().log(Level.WARNING, "Failed to load the metrics module. Maybe the jar is corrupt?", e);
} }
} }
@ -125,8 +123,7 @@ public class MetricsService {
if (moduleClassLoader != null) { if (moduleClassLoader != null) {
moduleClassLoader.close(); moduleClassLoader.close();
} }
} } catch (IOException e) {
catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Could not clean up module class loader. Some memory may have been leaked."); plugin.getLogger().log(Level.WARNING, "Could not clean up module class loader. Some memory may have been leaked.");
} }
} }
@ -177,8 +174,7 @@ public class MetricsService {
} }
return node.getObject().getInt("tag_name"); return node.getObject().getInt("tag_name");
} } catch (UnirestException e) {
catch (UnirestException e) {
plugin.getLogger().log(Level.WARNING, "Failed to fetch latest builds for Metrics: {0}", e.getMessage()); plugin.getLogger().log(Level.WARNING, "Failed to fetch latest builds for Metrics: {0}", e.getMessage());
return -1; return -1;
} }
@ -224,11 +220,9 @@ public class MetricsService {
hasDownloadedUpdate = true; hasDownloadedUpdate = true;
return true; return true;
} }
} } catch (UnirestException e) {
catch (UnirestException e) {
plugin.getLogger().log(Level.WARNING, "Failed to fetch the latest jar file from the builds page. Perhaps GitHub is down?"); plugin.getLogger().log(Level.WARNING, "Failed to fetch the latest jar file from the builds page. Perhaps GitHub is down?");
} } catch (IOException e) {
catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Failed to replace the old metric file with the new one. Please do this manually! Error: {0}", e.getMessage()); plugin.getLogger().log(Level.WARNING, "Failed to replace the old metric file with the new one. Please do this manually! Error: {0}", e.getMessage());
} }

View File

@ -138,8 +138,7 @@ public class MinecraftRecipeService {
} }
return choices.toArray(new RecipeChoice[0]); return choices.toArray(new RecipeChoice[0]);
} } else {
else {
return snapshot.getRecipeInput(recipe); return snapshot.getRecipeInput(recipe);
} }
} }
@ -156,8 +155,7 @@ public class MinecraftRecipeService {
public Recipe[] getRecipesFor(@Nullable ItemStack item) { public Recipe[] getRecipesFor(@Nullable ItemStack item) {
if (snapshot == null || item == null) { if (snapshot == null || item == null) {
return new Recipe[0]; return new Recipe[0];
} } else {
else {
return snapshot.getRecipesFor(item).toArray(new Recipe[0]); return snapshot.getRecipesFor(item).toArray(new Recipe[0]);
} }
} }

View File

@ -106,8 +106,7 @@ public class PerWorldSettingsService {
if (enabled) { if (enabled) {
items.remove(item.getID()); items.remove(item.getID());
} } else {
else {
items.add(item.getID()); items.add(item.getID());
} }
} }
@ -126,8 +125,7 @@ public class PerWorldSettingsService {
if (enabled) { if (enabled) {
disabledWorlds.remove(world.getUID()); disabledWorlds.remove(world.getUID());
} } else {
else {
disabledWorlds.add(world.getUID()); disabledWorlds.add(world.getUID());
} }
} }
@ -196,8 +194,7 @@ public class PerWorldSettingsService {
if (optional.isPresent()) { if (optional.isPresent()) {
return optional.get(); return optional.get();
} } else {
else {
Set<String> items = new LinkedHashSet<>(); Set<String> items = new LinkedHashSet<>();
Config config = getConfig(world); Config config = getConfig(world);
@ -212,8 +209,7 @@ public class PerWorldSettingsService {
if (SlimefunPlugin.getMinecraftVersion() != MinecraftVersion.UNIT_TEST) { if (SlimefunPlugin.getMinecraftVersion() != MinecraftVersion.UNIT_TEST) {
config.save(); config.save();
} }
} } else {
else {
disabledWorlds.add(world.getUID()); disabledWorlds.add(world.getUID());
} }

View File

@ -93,8 +93,7 @@ public class PermissionsService {
if (permission == null || permission.equals("none")) { if (permission == null || permission.equals("none")) {
return Optional.empty(); return Optional.empty();
} } else {
else {
return Optional.of(permission); return Optional.of(permission);
} }
} }

View File

@ -46,31 +46,26 @@ public class UpdaterService {
if (version.contains("UNOFFICIAL")) { if (version.contains("UNOFFICIAL")) {
// This Server is using a modified build that is not a public release. // This Server is using a modified build that is not a public release.
branch = SlimefunBranch.UNOFFICIAL; branch = SlimefunBranch.UNOFFICIAL;
} } else if (version.startsWith("DEV - ")) {
else if (version.startsWith("DEV - ")) {
// If we are using a development build, we want to switch to our custom // If we are using a development build, we want to switch to our custom
try { try {
autoUpdater = new GitHubBuildsUpdater(plugin, file, "TheBusyBiscuit/Slimefun4/master"); autoUpdater = new GitHubBuildsUpdater(plugin, file, "TheBusyBiscuit/Slimefun4/master");
} } catch (Exception x) {
catch (Exception x) {
plugin.getLogger().log(Level.SEVERE, "Failed to create AutoUpdater", x); plugin.getLogger().log(Level.SEVERE, "Failed to create AutoUpdater", x);
} }
branch = SlimefunBranch.DEVELOPMENT; branch = SlimefunBranch.DEVELOPMENT;
} } else if (version.startsWith("RC - ")) {
else if (version.startsWith("RC - ")) {
// If we are using a "stable" build, we want to switch to our custom // If we are using a "stable" build, we want to switch to our custom
try { try {
autoUpdater = new GitHubBuildsUpdater(plugin, file, "TheBusyBiscuit/Slimefun4/stable", "RC - "); autoUpdater = new GitHubBuildsUpdater(plugin, file, "TheBusyBiscuit/Slimefun4/stable", "RC - ");
} } catch (Exception x) {
catch (Exception x) {
plugin.getLogger().log(Level.SEVERE, "Failed to create AutoUpdater", x); plugin.getLogger().log(Level.SEVERE, "Failed to create AutoUpdater", x);
} }
branch = SlimefunBranch.STABLE; branch = SlimefunBranch.STABLE;
} } else {
else {
branch = SlimefunBranch.UNKNOWN; branch = SlimefunBranch.UNKNOWN;
} }
@ -111,8 +106,7 @@ public class UpdaterService {
public void start() { public void start() {
if (updater != null) { if (updater != null) {
updater.start(); updater.start();
} } else {
else {
printBorder(); printBorder();
plugin.getLogger().log(Level.WARNING, "It looks like you are using an unofficially modified build of Slimefun!"); plugin.getLogger().log(Level.WARNING, "It looks like you are using an unofficially modified build of Slimefun!");
plugin.getLogger().log(Level.WARNING, "Auto-Updates have been disabled, this build is not considered safe."); plugin.getLogger().log(Level.WARNING, "Auto-Updates have been disabled, this build is not considered safe.");

View File

@ -66,8 +66,7 @@ class ContributionsConnector extends GitHubConnector {
if (response.isArray()) { if (response.isArray()) {
computeContributors(response.getArray()); computeContributors(response.getArray());
} } else {
else {
Slimefun.getLogger().log(Level.WARNING, "Received an unusual answer from GitHub, possibly a timeout? ({0})", response); Slimefun.getLogger().log(Level.WARNING, "Received an unusual answer from GitHub, possibly a timeout? ({0})", response);
} }
} }

View File

@ -176,12 +176,10 @@ public class Contributor {
if (github != null) { if (github != null) {
String cached = github.getCachedTexture(githubUsername); String cached = github.getCachedTexture(githubUsername);
return cached != null ? cached : HeadTexture.UNKNOWN.getTexture(); return cached != null ? cached : HeadTexture.UNKNOWN.getTexture();
} } else {
else {
return HeadTexture.UNKNOWN.getTexture(); return HeadTexture.UNKNOWN.getTexture();
} }
} } else {
else {
return headTexture.get(); return headTexture.get();
} }
} }

View File

@ -78,8 +78,7 @@ abstract class GitHubConnector {
if (resp.isSuccess()) { if (resp.isSuccess()) {
onSuccess(resp.getBody()); onSuccess(resp.getBody());
writeCacheFile(resp.getBody()); writeCacheFile(resp.getBody());
} } else {
else {
if (github.isLoggingEnabled()) { if (github.isLoggingEnabled()) {
Slimefun.getLogger().log(Level.WARNING, "Failed to fetch {0}: {1} - {2}", new Object[] { repository + getURLSuffix(), resp.getStatus(), resp.getBody() }); Slimefun.getLogger().log(Level.WARNING, "Failed to fetch {0}: {1} - {2}", new Object[] { repository + getURLSuffix(), resp.getStatus(), resp.getBody() });
} }
@ -93,8 +92,7 @@ abstract class GitHubConnector {
} }
} }
} }
} } catch (UnirestException e) {
catch (UnirestException e) {
if (github.isLoggingEnabled()) { if (github.isLoggingEnabled()) {
Slimefun.getLogger().log(Level.WARNING, "Could not connect to GitHub in time."); Slimefun.getLogger().log(Level.WARNING, "Could not connect to GitHub in time.");
} }
@ -118,8 +116,7 @@ abstract class GitHubConnector {
private JsonNode readCacheFile() { private JsonNode readCacheFile() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
return new JsonNode(reader.readLine()); return new JsonNode(reader.readLine());
} } catch (IOException | JSONException e) {
catch (IOException | JSONException e) {
Slimefun.getLogger().log(Level.WARNING, "Failed to read Github cache file: {0} - {1}: {2}", new Object[] { file.getName(), e.getClass().getSimpleName(), e.getMessage() }); Slimefun.getLogger().log(Level.WARNING, "Failed to read Github cache file: {0} - {1}: {2}", new Object[] { file.getName(), e.getClass().getSimpleName(), e.getMessage() });
return null; return null;
} }
@ -128,8 +125,7 @@ abstract class GitHubConnector {
private void writeCacheFile(@Nonnull JsonNode node) { private void writeCacheFile(@Nonnull JsonNode node) {
try (FileOutputStream output = new FileOutputStream(file)) { try (FileOutputStream output = new FileOutputStream(file)) {
output.write(node.toString().getBytes(StandardCharsets.UTF_8)); output.write(node.toString().getBytes(StandardCharsets.UTF_8));
} } catch (IOException e) {
catch (IOException e) {
Slimefun.getLogger().log(Level.WARNING, "Failed to populate GitHub cache: {0} - {1}", new Object[] { e.getClass().getSimpleName(), e.getMessage() }); Slimefun.getLogger().log(Level.WARNING, "Failed to populate GitHub cache: {0} - {1}", new Object[] { e.getClass().getSimpleName(), e.getMessage() });
} }
} }

View File

@ -33,15 +33,13 @@ class GitHubIssuesConnector extends GitHubConnector {
if (obj.has("pull_request")) { if (obj.has("pull_request")) {
pullRequests++; pullRequests++;
} } else {
else {
issues++; issues++;
} }
} }
callback.accept(issues, pullRequests); callback.accept(issues, pullRequests);
} } else {
else {
Slimefun.getLogger().log(Level.WARNING, "Received an unusual answer from GitHub, possibly a timeout? ({0})", response); Slimefun.getLogger().log(Level.WARNING, "Received an unusual answer from GitHub, possibly a timeout? ({0})", response);
} }
} }

View File

@ -78,17 +78,14 @@ class GitHubTask implements Runnable {
try { try {
if (skins.containsKey(contributor.getMinecraftName())) { if (skins.containsKey(contributor.getMinecraftName())) {
contributor.setTexture(skins.get(contributor.getMinecraftName())); contributor.setTexture(skins.get(contributor.getMinecraftName()));
} } else {
else {
contributor.setTexture(pullTexture(contributor, skins)); contributor.setTexture(pullTexture(contributor, skins));
return contributor.getUniqueId().isPresent() ? 1 : 2; return contributor.getUniqueId().isPresent() ? 1 : 2;
} }
} } catch (IllegalArgumentException x) {
catch (IllegalArgumentException x) {
// There cannot be a texture found because it is not a valid MC username // There cannot be a texture found because it is not a valid MC username
contributor.setTexture(null); contributor.setTexture(null);
} } catch (IOException x) {
catch (IOException x) {
// Too many requests // Too many requests
Slimefun.getLogger().log(Level.WARNING, "Attempted to connect to mojang.com, got this response: {0}: {1}", new Object[] { x.getClass().getSimpleName(), x.getMessage() }); Slimefun.getLogger().log(Level.WARNING, "Attempted to connect to mojang.com, got this response: {0}: {1}", new Object[] { x.getClass().getSimpleName(), x.getMessage() });
Slimefun.getLogger().log(Level.WARNING, "This usually means mojang.com is down or started to rate-limit this connection, this is not an error message!"); Slimefun.getLogger().log(Level.WARNING, "This usually means mojang.com is down or started to rate-limit this connection, this is not an error message!");
@ -99,8 +96,7 @@ class GitHubTask implements Runnable {
} }
return -1; return -1;
} } catch (TooManyRequestsException x) {
catch (TooManyRequestsException x) {
Slimefun.getLogger().log(Level.WARNING, "Received a rate-limit from mojang.com, retrying in 4 minutes"); Slimefun.getLogger().log(Level.WARNING, "Received a rate-limit from mojang.com, retrying in 4 minutes");
Bukkit.getScheduler().runTaskLaterAsynchronously(SlimefunPlugin.instance(), this::grabTextures, 4 * 60 * 20L); Bukkit.getScheduler().runTaskLaterAsynchronously(SlimefunPlugin.instance(), this::grabTextures, 4 * 60 * 20L);
@ -124,8 +120,7 @@ class GitHubTask implements Runnable {
Optional<String> skin = MinecraftAccount.getSkin(uuid.get()); Optional<String> skin = MinecraftAccount.getSkin(uuid.get());
skins.put(contributor.getMinecraftName(), skin.orElse("")); skins.put(contributor.getMinecraftName(), skin.orElse(""));
return skin.orElse(null); return skin.orElse(null);
} } else {
else {
return null; return null;
} }
} }

View File

@ -75,8 +75,7 @@ public final class Language {
public double getTranslationProgress() { public double getTranslationProgress() {
if (id.equals("en")) { if (id.equals("en")) {
return 100.0; return 100.0;
} } else {
else {
if (progress < 0) { if (progress < 0) {
progress = SlimefunPlugin.getLocalization().calculateProgress(this); progress = SlimefunPlugin.getLocalization().calculateProgress(this);
} }

View File

@ -160,8 +160,7 @@ public abstract class SlimefunLocalization extends Localization implements Keyed
if (value != null) { if (value != null) {
return value; return value;
} } else {
else {
Language fallback = getLanguage(SupportedLanguage.ENGLISH.getLanguageId()); Language fallback = getLanguage(SupportedLanguage.ENGLISH.getLanguageId());
return fallback.getResourcesFile().getString(key); return fallback.getResourcesFile().getString(key);
} }
@ -199,8 +198,7 @@ public abstract class SlimefunLocalization extends Localization implements Keyed
if (sender instanceof Player) { if (sender instanceof Player) {
sender.sendMessage(ChatColors.color(prefix + getMessage((Player) sender, key))); sender.sendMessage(ChatColors.color(prefix + getMessage((Player) sender, key)));
} } else {
else {
sender.sendMessage(ChatColor.stripColor(ChatColors.color(prefix + getMessage(key)))); sender.sendMessage(ChatColor.stripColor(ChatColors.color(prefix + getMessage(key))));
} }
} }
@ -224,8 +222,7 @@ public abstract class SlimefunLocalization extends Localization implements Keyed
if (sender instanceof Player) { if (sender instanceof Player) {
sender.sendMessage(ChatColors.color(prefix + function.apply(getMessage((Player) sender, key)))); sender.sendMessage(ChatColors.color(prefix + function.apply(getMessage((Player) sender, key))));
} } else {
else {
sender.sendMessage(ChatColor.stripColor(ChatColors.color(prefix + function.apply(getMessage(key))))); sender.sendMessage(ChatColor.stripColor(ChatColors.color(prefix + function.apply(getMessage(key)))));
} }
} }
@ -239,8 +236,7 @@ public abstract class SlimefunLocalization extends Localization implements Keyed
String message = ChatColors.color(prefix + translation); String message = ChatColors.color(prefix + translation);
sender.sendMessage(message); sender.sendMessage(message);
} }
} } else {
else {
for (String translation : getMessages(key)) { for (String translation : getMessages(key)) {
String message = ChatColors.color(prefix + translation); String message = ChatColors.color(prefix + translation);
sender.sendMessage(ChatColor.stripColor(message)); sender.sendMessage(ChatColor.stripColor(message));
@ -257,8 +253,7 @@ public abstract class SlimefunLocalization extends Localization implements Keyed
String message = ChatColors.color(prefix + function.apply(translation)); String message = ChatColors.color(prefix + function.apply(translation));
sender.sendMessage(message); sender.sendMessage(message);
} }
} } else {
else {
for (String translation : getMessages(key)) { for (String translation : getMessages(key)) {
String message = ChatColors.color(prefix + function.apply(translation)); String message = ChatColors.color(prefix + function.apply(translation));
sender.sendMessage(ChatColor.stripColor(message)); sender.sendMessage(ChatColor.stripColor(message));

View File

@ -56,8 +56,7 @@ class PlaceholderAPIHook extends PlaceholderExpansion {
private boolean isPlaceholder(@Nullable OfflinePlayer p, boolean requiresProfile, @Nonnull String params, @Nonnull String placeholder) { private boolean isPlaceholder(@Nullable OfflinePlayer p, boolean requiresProfile, @Nonnull String params, @Nonnull String placeholder) {
if (requiresProfile) { if (requiresProfile) {
return p != null && placeholder.equals(params) && PlayerProfile.request(p); return p != null && placeholder.equals(params) && PlayerProfile.request(p);
} } else {
else {
return placeholder.equals(params); return placeholder.equals(params);
} }
} }

View File

@ -50,8 +50,7 @@ public class ThirdPartyPluginService {
PlaceholderAPIHook hook = new PlaceholderAPIHook(plugin); PlaceholderAPIHook hook = new PlaceholderAPIHook(plugin);
hook.register(); hook.register();
isPlaceholderAPIInstalled = true; isPlaceholderAPIInstalled = true;
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
String version = plugin.getServer().getPluginManager().getPlugin("PlaceholderAPI").getDescription().getVersion(); String version = plugin.getServer().getPluginManager().getPlugin("PlaceholderAPI").getDescription().getVersion();
Slimefun.getLogger().log(Level.WARNING, "Maybe consider updating PlaceholderAPI or Slimefun?"); Slimefun.getLogger().log(Level.WARNING, "Maybe consider updating PlaceholderAPI or Slimefun?");
@ -71,8 +70,7 @@ public class ThirdPartyPluginService {
try { try {
Class.forName("com.sk89q.worldedit.extent.Extent"); Class.forName("com.sk89q.worldedit.extent.Extent");
new WorldEditHook(); new WorldEditHook();
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
String version = plugin.getServer().getPluginManager().getPlugin("WorldEdit").getDescription().getVersion(); String version = plugin.getServer().getPluginManager().getPlugin("WorldEdit").getDescription().getVersion();
Slimefun.getLogger().log(Level.WARNING, "Maybe consider updating WorldEdit or Slimefun?"); Slimefun.getLogger().log(Level.WARNING, "Maybe consider updating WorldEdit or Slimefun?");
@ -98,8 +96,7 @@ public class ThirdPartyPluginService {
if (plugin.getServer().getPluginManager().isPluginEnabled(hook)) { if (plugin.getServer().getPluginManager().isPluginEnabled(hook)) {
Slimefun.getLogger().log(Level.INFO, "Hooked into Plugin: {0}", hook); Slimefun.getLogger().log(Level.INFO, "Hooked into Plugin: {0}", hook);
return true; return true;
} } else {
else {
return false; return false;
} }
} }

View File

@ -37,7 +37,7 @@ class WorldEditHook {
} }
} }
} }
return getExtent().setBlock(pos, block); return getExtent().setBlock(pos, block);
} }

View File

@ -70,8 +70,7 @@ class PerformanceSummary {
String average = NumberUtils.getAsMillis(entry.getValue() / count); String average = NumberUtils.getAsMillis(entry.getValue() / count);
return entry.getKey() + " - " + count + "x (" + time + " | avg: " + average + ')'; return entry.getKey() + " - " + count + "x (" + time + " | avg: " + average + ')';
} } else {
else {
return entry.getKey() + " - " + count + "x (" + time + ')'; return entry.getKey() + " - " + count + "x (" + time + ')';
} }
}); });
@ -100,8 +99,7 @@ class PerformanceSummary {
if (sender instanceof Player) { if (sender instanceof Player) {
TextComponent component = summarizeAsTextComponent(count, prefix, results, formatter); TextComponent component = summarizeAsTextComponent(count, prefix, results, formatter);
sender.spigot().sendMessage(component); sender.spigot().sendMessage(component);
} } else {
else {
String text = summarizeAsString(count, prefix, results, formatter); String text = summarizeAsString(count, prefix, results, formatter);
sender.sendMessage(text); sender.sendMessage(text);
} }
@ -125,8 +123,7 @@ class PerformanceSummary {
if (shownEntries < MAX_ITEMS && (shownEntries < MIN_ITEMS || entry.getValue() > VISIBILITY_THRESHOLD)) { if (shownEntries < MAX_ITEMS && (shownEntries < MIN_ITEMS || entry.getValue() > VISIBILITY_THRESHOLD)) {
builder.append("\n").append(ChatColor.YELLOW).append(formatter.apply(entry)); builder.append("\n").append(ChatColor.YELLOW).append(formatter.apply(entry));
shownEntries++; shownEntries++;
} } else {
else {
hiddenEntries++; hiddenEntries++;
} }
} }
@ -161,8 +158,7 @@ class PerformanceSummary {
builder.append("\n "); builder.append("\n ");
builder.append(ChatColor.stripColor(formatter.apply(entry))); builder.append(ChatColor.stripColor(formatter.apply(entry)));
shownEntries++; shownEntries++;
} } else {
else {
hiddenEntries++; hiddenEntries++;
} }
} }

View File

@ -164,8 +164,7 @@ public class SlimefunProfiler {
} }
return; return;
} }
} } catch (InterruptedException e) {
catch (InterruptedException e) {
Slimefun.getLogger().log(Level.SEVERE, "A Profiler Thread was interrupted", e); Slimefun.getLogger().log(Level.SEVERE, "A Profiler Thread was interrupted", e);
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }

View File

@ -679,7 +679,6 @@ public final class SlimefunItems {
public static final SlimefunItemStack CARBONADO_EDGED_CAPACITOR = new SlimefunItemStack("CARBONADO_EDGED_CAPACITOR", HeadTexture.CAPACITOR_25, "&aCarbonado Edged Energy Capacitor", "", LoreBuilder.machine(MachineTier.END_GAME, MachineType.CAPACITOR), "&8\u21E8 &e\u26A1 &765536 J Capacity"); public static final SlimefunItemStack CARBONADO_EDGED_CAPACITOR = new SlimefunItemStack("CARBONADO_EDGED_CAPACITOR", HeadTexture.CAPACITOR_25, "&aCarbonado Edged Energy Capacitor", "", LoreBuilder.machine(MachineTier.END_GAME, MachineType.CAPACITOR), "&8\u21E8 &e\u26A1 &765536 J Capacity");
public static final SlimefunItemStack ENERGIZED_CAPACITOR = new SlimefunItemStack("ENERGIZED_CAPACITOR", HeadTexture.CAPACITOR_25, "&aEnergized Energy Capacitor", "", LoreBuilder.machine(MachineTier.END_GAME, MachineType.CAPACITOR), "&8\u21E8 &e\u26A1 &7524288 J Capacity"); public static final SlimefunItemStack ENERGIZED_CAPACITOR = new SlimefunItemStack("ENERGIZED_CAPACITOR", HeadTexture.CAPACITOR_25, "&aEnergized Energy Capacitor", "", LoreBuilder.machine(MachineTier.END_GAME, MachineType.CAPACITOR), "&8\u21E8 &e\u26A1 &7524288 J Capacity");
/* Robots */ /* Robots */
public static final SlimefunItemStack PROGRAMMABLE_ANDROID = new SlimefunItemStack("PROGRAMMABLE_ANDROID", HeadTexture.PROGRAMMABLE_ANDROID, "&cProgrammable Android &7(Normal)", "", "&8\u21E8 &7Function: None", "&8\u21E8 &7Fuel Efficiency: 1.0x"); public static final SlimefunItemStack PROGRAMMABLE_ANDROID = new SlimefunItemStack("PROGRAMMABLE_ANDROID", HeadTexture.PROGRAMMABLE_ANDROID, "&cProgrammable Android &7(Normal)", "", "&8\u21E8 &7Function: None", "&8\u21E8 &7Fuel Efficiency: 1.0x");
public static final SlimefunItemStack PROGRAMMABLE_ANDROID_FARMER = new SlimefunItemStack("PROGRAMMABLE_ANDROID_FARMER", HeadTexture.PROGRAMMABLE_ANDROID_FARMER, "&cProgrammable Android &7(Farmer)", "", "&8\u21E8 &7Function: Farming", "&8\u21E8 &7Fuel Efficiency: 1.0x"); public static final SlimefunItemStack PROGRAMMABLE_ANDROID_FARMER = new SlimefunItemStack("PROGRAMMABLE_ANDROID_FARMER", HeadTexture.PROGRAMMABLE_ANDROID_FARMER, "&cProgrammable Android &7(Farmer)", "", "&8\u21E8 &7Function: Farming", "&8\u21E8 &7Fuel Efficiency: 1.0x");
@ -848,8 +847,7 @@ public final class SlimefunItems {
MAKESHIFT_SMELTERY = new SlimefunItemStack("MAKESHIFT_SMELTERY", Material.BLAST_FURNACE, "&eMakeshift Smeltery", "", "&fImprovised version of the Smeltery", "&fthat only allows you to", "&fsmelt dusts into ingots"); MAKESHIFT_SMELTERY = new SlimefunItemStack("MAKESHIFT_SMELTERY", Material.BLAST_FURNACE, "&eMakeshift Smeltery", "", "&fImprovised version of the Smeltery", "&fthat only allows you to", "&fsmelt dusts into ingots");
AUTO_DRIER = new SlimefunItemStack("AUTO_DRIER", Material.SMOKER, "&6Auto Drier", "", LoreBuilder.machine(MachineTier.MEDIUM, MachineType.MACHINE), LoreBuilder.speed(1), LoreBuilder.powerPerSecond(10)); AUTO_DRIER = new SlimefunItemStack("AUTO_DRIER", Material.SMOKER, "&6Auto Drier", "", LoreBuilder.machine(MachineTier.MEDIUM, MachineType.MACHINE), LoreBuilder.speed(1), LoreBuilder.powerPerSecond(10));
AUTO_BREWER = new SlimefunItemStack("AUTO_BREWER", Material.SMOKER, "&6Auto Brewer", "", LoreBuilder.machine(MachineTier.MEDIUM, MachineType.MACHINE), LoreBuilder.speed(1), LoreBuilder.powerPerSecond(12)); AUTO_BREWER = new SlimefunItemStack("AUTO_BREWER", Material.SMOKER, "&6Auto Brewer", "", LoreBuilder.machine(MachineTier.MEDIUM, MachineType.MACHINE), LoreBuilder.speed(1), LoreBuilder.powerPerSecond(12));
} } else {
else {
TABLE_SAW = null; TABLE_SAW = null;
MAKESHIFT_SMELTERY = new SlimefunItemStack("MAKESHIFT_SMELTERY", Material.FURNACE, "&eMakeshift Smeltery", "", "&fImprovised version of the Smeltery", "&fthat only allows you to", "&fsmelt dusts into ingots"); MAKESHIFT_SMELTERY = new SlimefunItemStack("MAKESHIFT_SMELTERY", Material.FURNACE, "&eMakeshift Smeltery", "", "&fImprovised version of the Smeltery", "&fthat only allows you to", "&fsmelt dusts into ingots");
AUTO_DRIER = new SlimefunItemStack("AUTO_DRIER", Material.FURNACE, "&6Auto Drier", "", LoreBuilder.machine(MachineTier.MEDIUM, MachineType.MACHINE), LoreBuilder.speed(1), LoreBuilder.powerPerSecond(10)); AUTO_DRIER = new SlimefunItemStack("AUTO_DRIER", Material.FURNACE, "&6Auto Drier", "", LoreBuilder.machine(MachineTier.MEDIUM, MachineType.MACHINE), LoreBuilder.speed(1), LoreBuilder.powerPerSecond(10));

View File

@ -173,8 +173,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon {
networkManager = new NetworkManager(200); networkManager = new NetworkManager(200);
command.register(); command.register();
registry.load(config); registry.load(config);
} } else if (getServer().getPluginManager().isPluginEnabled("CS-CoreLib")) {
else if (getServer().getPluginManager().isPluginEnabled("CS-CoreLib")) {
long timestamp = System.nanoTime(); long timestamp = System.nanoTime();
PaperLib.suggestPaper(this); PaperLib.suggestPaper(this);
@ -221,8 +220,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon {
if (config.getBoolean("options.auto-update")) { if (config.getBoolean("options.auto-update")) {
getLogger().log(Level.INFO, "Starting Auto-Updater..."); getLogger().log(Level.INFO, "Starting Auto-Updater...");
updaterService.start(); updaterService.start();
} } else {
else {
updaterService.disable(); updaterService.disable();
} }
@ -251,8 +249,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon {
// This try/catch should prevent buggy Spigot builds from blocking item loading // This try/catch should prevent buggy Spigot builds from blocking item loading
try { try {
recipeService.refresh(); recipeService.refresh();
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
getLogger().log(Level.SEVERE, x, () -> "An Exception occurred while iterating through the Recipe list on Minecraft Version " + minecraftVersion.getName() + " (Slimefun v" + getVersion() + ")"); getLogger().log(Level.SEVERE, x, () -> "An Exception occurred while iterating through the Recipe list on Minecraft Version " + minecraftVersion.getName() + " (Slimefun v" + getVersion() + ")");
} }
@ -274,8 +271,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon {
// Hooray! // Hooray!
getLogger().log(Level.INFO, "Slimefun has finished loading in {0}", getStartupTime(timestamp)); getLogger().log(Level.INFO, "Slimefun has finished loading in {0}", getStartupTime(timestamp));
} } else {
else {
instance = null; instance = null;
getLogger().log(Level.INFO, "#################### - INFO - ####################"); getLogger().log(Level.INFO, "#################### - INFO - ####################");
@ -299,8 +295,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon {
if (ms > 1000) { if (ms > 1000) {
return DoubleHandler.fixDouble(ms / 1000.0) + "s"; return DoubleHandler.fixDouble(ms / 1000.0) + "s";
} } else {
else {
return DoubleHandler.fixDouble(ms) + "ms"; return DoubleHandler.fixDouble(ms) + "ms";
} }
} }
@ -376,8 +371,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon {
for (Map.Entry<String, BlockStorage> entry : getRegistry().getWorlds().entrySet()) { for (Map.Entry<String, BlockStorage> entry : getRegistry().getWorlds().entrySet()) {
try { try {
entry.getValue().saveAndRemove(); entry.getValue().saveAndRemove();
} } catch (Exception x) {
catch (Exception x) {
getLogger().log(Level.SEVERE, x, () -> "An Error occurred while saving Slimefun-Blocks in World '" + entry.getKey() + "' for Slimefun " + getVersion()); getLogger().log(Level.SEVERE, x, () -> "An Error occurred while saving Slimefun-Blocks in World '" + entry.getKey() + "' for Slimefun " + getVersion());
} }
} }
@ -498,8 +492,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon {
private void loadItems() { private void loadItems() {
try { try {
SlimefunItemSetup.setup(this); SlimefunItemSetup.setup(this);
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
getLogger().log(Level.SEVERE, x, () -> "An Error occurred while initializing SlimefunItems for Slimefun " + getVersion()); getLogger().log(Level.SEVERE, x, () -> "An Error occurred while initializing SlimefunItems for Slimefun " + getVersion());
} }
} }
@ -507,8 +500,7 @@ public final class SlimefunPlugin extends JavaPlugin implements SlimefunAddon {
private void loadResearches() { private void loadResearches() {
try { try {
ResearchSetup.setupResearches(); ResearchSetup.setupResearches();
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
getLogger().log(Level.SEVERE, x, () -> "An Error occurred while initializing Slimefun Researches for Slimefun " + getVersion()); getLogger().log(Level.SEVERE, x, () -> "An Error occurred while initializing Slimefun Researches for Slimefun " + getVersion());
} }
} }

View File

@ -157,8 +157,7 @@ public class BookSlimefunGuide implements SlimefunGuideImplementation {
ChatComponent chatComponent = new ChatComponent(ChatUtils.crop(ChatColor.RED, ItemUtils.getItemName(category.getItem(p))) + "\n"); ChatComponent chatComponent = new ChatComponent(ChatUtils.crop(ChatColor.RED, ItemUtils.getItemName(category.getItem(p))) + "\n");
chatComponent.setHoverEvent(new HoverEvent(lore)); chatComponent.setHoverEvent(new HoverEvent(lore));
lines.add(chatComponent); lines.add(chatComponent);
} } else {
else {
ChatComponent chatComponent = new ChatComponent(ChatUtils.crop(ChatColor.DARK_GREEN, ItemUtils.getItemName(category.getItem(p))) + "\n"); ChatComponent chatComponent = new ChatComponent(ChatUtils.crop(ChatColor.DARK_GREEN, ItemUtils.getItemName(category.getItem(p))) + "\n");
chatComponent.setHoverEvent(new HoverEvent(ItemUtils.getItemName(category.getItem(p)), "", ChatColor.GRAY + "\u21E8 " + ChatColor.GREEN + SlimefunPlugin.getLocalization().getMessage(p, "guide.tooltips.open-category"))); chatComponent.setHoverEvent(new HoverEvent(ItemUtils.getItemName(category.getItem(p)), "", ChatColor.GRAY + "\u21E8 " + ChatColor.GREEN + SlimefunPlugin.getLocalization().getMessage(p, "guide.tooltips.open-category")));
chatComponent.setClickEvent(new ClickEvent(category.getKey(), pl -> openCategory(profile, category, 1))); chatComponent.setClickEvent(new ClickEvent(category.getKey(), pl -> openCategory(profile, category, 1)));
@ -176,8 +175,7 @@ public class BookSlimefunGuide implements SlimefunGuideImplementation {
if (category instanceof FlexCategory) { if (category instanceof FlexCategory) {
((FlexCategory) category).open(p, profile, getLayout()); ((FlexCategory) category).open(p, profile, getLayout());
} } else if (category.getItems().size() < 250) {
else if (category.getItems().size() < 250) {
profile.getGuideHistory().add(category, page); profile.getGuideHistory().add(category, page);
List<ChatComponent> items = new LinkedList<>(); List<ChatComponent> items = new LinkedList<>();
@ -187,8 +185,7 @@ public class BookSlimefunGuide implements SlimefunGuideImplementation {
if (Slimefun.isEnabled(p, slimefunItem, false)) { if (Slimefun.isEnabled(p, slimefunItem, false)) {
addSlimefunItem(category, page, p, profile, slimefunItem, items); addSlimefunItem(category, page, p, profile, slimefunItem, items);
} }
} } else {
else {
ChatComponent component = new ChatComponent(ChatUtils.crop(ChatColor.DARK_RED, ItemUtils.getItemName(slimefunItem.getItem())) + "\n"); ChatComponent component = new ChatComponent(ChatUtils.crop(ChatColor.DARK_RED, ItemUtils.getItemName(slimefunItem.getItem())) + "\n");
List<String> lore = new ArrayList<>(); List<String> lore = new ArrayList<>();
@ -205,8 +202,7 @@ public class BookSlimefunGuide implements SlimefunGuideImplementation {
} }
openBook(p, profile, items, true); openBook(p, profile, items, true);
} } else {
else {
p.sendMessage(ChatColor.RED + "That Category is too big to open :/"); p.sendMessage(ChatColor.RED + "That Category is too big to open :/");
} }
} }
@ -222,8 +218,7 @@ public class BookSlimefunGuide implements SlimefunGuideImplementation {
component.setClickEvent(new ClickEvent(key, player -> research(player, profile, item, research, category, page))); component.setClickEvent(new ClickEvent(key, player -> research(player, profile, item, research, category, page)));
items.add(component); items.add(component);
} } else {
else {
ChatComponent component = new ChatComponent(ChatUtils.crop(ChatColor.DARK_GREEN, item.getItemName()) + "\n"); ChatComponent component = new ChatComponent(ChatUtils.crop(ChatColor.DARK_GREEN, item.getItemName()) + "\n");
List<String> lore = new ArrayList<>(); List<String> lore = new ArrayList<>();
@ -245,12 +240,10 @@ public class BookSlimefunGuide implements SlimefunGuideImplementation {
if (research.canUnlock(p)) { if (research.canUnlock(p)) {
if (profile.hasUnlocked(research)) { if (profile.hasUnlocked(research)) {
openCategory(profile, category, page); openCategory(profile, category, page);
} } else {
else {
unlockItem(p, item, pl -> openCategory(profile, category, page)); unlockItem(p, item, pl -> openCategory(profile, category, page));
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(p, "messages.not-enough-xp", true); SlimefunPlugin.getLocalization().sendMessage(p, "messages.not-enough-xp", true);
} }
} }

View File

@ -77,8 +77,7 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_14)) { if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_14)) {
sound = Sound.ITEM_BOOK_PAGE_TURN; sound = Sound.ITEM_BOOK_PAGE_TURN;
} } else {
else {
sound = Sound.ENTITY_BAT_TAKEOFF; sound = Sound.ENTITY_BAT_TAKEOFF;
} }
} }
@ -184,8 +183,7 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
openCategory(profile, category, 1); openCategory(profile, category, 1);
return false; return false;
}); });
} } else {
else {
List<String> lore = new ArrayList<>(); List<String> lore = new ArrayList<>();
lore.add(""); lore.add("");
@ -235,14 +233,16 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
menu.addItem(46, ChestMenuUtils.getPreviousButton(p, page, pages)); menu.addItem(46, ChestMenuUtils.getPreviousButton(p, page, pages));
menu.addMenuClickHandler(46, (pl, slot, item, action) -> { menu.addMenuClickHandler(46, (pl, slot, item, action) -> {
int next = page - 1; int next = page - 1;
if (next != page && next > 0) openCategory(profile, category, next); if (next != page && next > 0)
openCategory(profile, category, next);
return false; return false;
}); });
menu.addItem(52, ChestMenuUtils.getNextButton(p, page, pages)); menu.addItem(52, ChestMenuUtils.getNextButton(p, page, pages));
menu.addMenuClickHandler(52, (pl, slot, item, action) -> { menu.addMenuClickHandler(52, (pl, slot, item, action) -> {
int next = page + 1; int next = page + 1;
if (next != page && next <= pages) openCategory(profile, category, next); if (next != page && next <= pages)
openCategory(profile, category, next);
return false; return false;
}); });
@ -274,44 +274,37 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
List<String> message = SlimefunPlugin.getPermissionsService().getLore(sfitem); List<String> message = SlimefunPlugin.getPermissionsService().getLore(sfitem);
menu.addItem(index, new CustomItem(Material.BARRIER, sfitem.getItemName(), message.toArray(new String[0]))); menu.addItem(index, new CustomItem(Material.BARRIER, sfitem.getItemName(), message.toArray(new String[0])));
menu.addMenuClickHandler(index, ChestMenuUtils.getEmptyClickHandler()); menu.addMenuClickHandler(index, ChestMenuUtils.getEmptyClickHandler());
} } else if (isSurvivalMode() && research != null && !profile.hasUnlocked(research)) {
else if (isSurvivalMode() && research != null && !profile.hasUnlocked(research)) {
menu.addItem(index, new CustomItem(Material.BARRIER, ChatColor.WHITE + ItemUtils.getItemName(sfitem.getItem()), "&4&l" + SlimefunPlugin.getLocalization().getMessage(p, "guide.locked"), "", "&a> Click to unlock", "", "&7Cost: &b" + research.getCost() + " Level(s)")); menu.addItem(index, new CustomItem(Material.BARRIER, ChatColor.WHITE + ItemUtils.getItemName(sfitem.getItem()), "&4&l" + SlimefunPlugin.getLocalization().getMessage(p, "guide.locked"), "", "&a> Click to unlock", "", "&7Cost: &b" + research.getCost() + " Level(s)"));
menu.addMenuClickHandler(index, (pl, slot, item, action) -> { menu.addMenuClickHandler(index, (pl, slot, item, action) -> {
if (!SlimefunPlugin.getRegistry().getCurrentlyResearchingPlayers().contains(pl.getUniqueId())) { if (!SlimefunPlugin.getRegistry().getCurrentlyResearchingPlayers().contains(pl.getUniqueId())) {
if (research.canUnlock(pl)) { if (research.canUnlock(pl)) {
if (profile.hasUnlocked(research)) { if (profile.hasUnlocked(research)) {
openCategory(profile, category, page); openCategory(profile, category, page);
} } else {
else {
unlockItem(pl, sfitem, player -> openCategory(profile, category, page)); unlockItem(pl, sfitem, player -> openCategory(profile, category, page));
} }
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(pl, "messages.not-enough-xp", true); SlimefunPlugin.getLocalization().sendMessage(pl, "messages.not-enough-xp", true);
} }
} }
return false; return false;
}); });
} } else {
else {
menu.addItem(index, sfitem.getItem()); menu.addItem(index, sfitem.getItem());
menu.addMenuClickHandler(index, (pl, slot, item, action) -> { menu.addMenuClickHandler(index, (pl, slot, item, action) -> {
try { try {
if (isSurvivalMode()) { if (isSurvivalMode()) {
displayItem(profile, sfitem, true); displayItem(profile, sfitem, true);
} } else {
else {
if (sfitem instanceof MultiBlockMachine) { if (sfitem instanceof MultiBlockMachine) {
SlimefunPlugin.getLocalization().sendMessage(pl, "guide.cheat.no-multiblocks"); SlimefunPlugin.getLocalization().sendMessage(pl, "guide.cheat.no-multiblocks");
} } else {
else {
pl.getInventory().addItem(sfitem.getItem().clone()); pl.getInventory().addItem(sfitem.getItem().clone());
} }
} }
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
printErrorMessage(pl, x); printErrorMessage(pl, x);
} }
@ -370,12 +363,10 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
try { try {
if (!isSurvivalMode()) { if (!isSurvivalMode()) {
pl.getInventory().addItem(slimefunItem.getItem().clone()); pl.getInventory().addItem(slimefunItem.getItem().clone());
} } else {
else {
displayItem(profile, slimefunItem, true); displayItem(profile, slimefunItem, true);
} }
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
printErrorMessage(pl, x); printErrorMessage(pl, x);
} }
@ -432,8 +423,7 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
recipeType = new RecipeType(optional.get()); recipeType = new RecipeType(optional.get());
result = recipe.getResult(); result = recipe.getResult();
} } else {
else {
recipeItems = new ItemStack[] { null, null, null, null, new CustomItem(Material.BARRIER, "&4We are somehow unable to show you this Recipe :/"), null, null, null, null }; recipeItems = new ItemStack[] { null, null, null, null, new CustomItem(Material.BARRIER, "&4We are somehow unable to show you this Recipe :/"), null, null, null, null };
} }
@ -481,8 +471,7 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
if (((MaterialChoice) choices[0]).getChoices().size() > 1) { if (((MaterialChoice) choices[0]).getChoices().size() > 1) {
task.add(recipeSlots[4], (MaterialChoice) choices[0]); task.add(recipeSlots[4], (MaterialChoice) choices[0]);
} }
} } else {
else {
for (int i = 0; i < choices.length; i++) { for (int i = 0; i < choices.length; i++) {
if (choices[i] instanceof MaterialChoice) { if (choices[i] instanceof MaterialChoice) {
recipeItems[i] = new ItemStack(((MaterialChoice) choices[i]).getChoices().get(0)); recipeItems[i] = new ItemStack(((MaterialChoice) choices[i]).getChoices().get(0));
@ -546,8 +535,7 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
if (itemstack != null && itemstack.getType() != Material.BARRIER) { if (itemstack != null && itemstack.getType() != Material.BARRIER) {
displayItem(profile, itemstack, 0, true); displayItem(profile, itemstack, 0, true);
} }
} } catch (Exception | LinkageError x) {
catch (Exception | LinkageError x) {
printErrorMessage(pl, x); printErrorMessage(pl, x);
} }
return false; return false;
@ -610,15 +598,13 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
menu.addMenuClickHandler(slot, (pl, s, is, action) -> { menu.addMenuClickHandler(slot, (pl, s, is, action) -> {
if (action.isShiftClicked()) { if (action.isShiftClicked()) {
openMainMenu(profile, 1); openMainMenu(profile, 1);
} } else {
else {
history.goBack(this); history.goBack(this);
} }
return false; return false;
}); });
} } else {
else {
menu.addItem(slot, new CustomItem(ChestMenuUtils.getBackButton(p, "", ChatColor.GRAY + SlimefunPlugin.getLocalization().getMessage(p, "guide.back.guide")))); menu.addItem(slot, new CustomItem(ChestMenuUtils.getBackButton(p, "", ChatColor.GRAY + SlimefunPlugin.getLocalization().getMessage(p, "guide.back.guide"))));
menu.addMenuClickHandler(slot, (pl, s, is, action) -> { menu.addMenuClickHandler(slot, (pl, s, is, action) -> {
openMainMenu(profile, 1); openMainMenu(profile, 1);
@ -637,8 +623,7 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
String lore = Slimefun.hasPermission(p, slimefunItem, false) ? "&fNeeds to be unlocked elsewhere" : "&fNo Permission"; String lore = Slimefun.hasPermission(p, slimefunItem, false) ? "&fNeeds to be unlocked elsewhere" : "&fNo Permission";
return Slimefun.hasUnlocked(p, slimefunItem, false) ? item : new CustomItem(Material.BARRIER, ItemUtils.getItemName(item), "&4&l" + SlimefunPlugin.getLocalization().getMessage(p, "guide.locked"), "", lore); return Slimefun.hasUnlocked(p, slimefunItem, false) ? item : new CustomItem(Material.BARRIER, ItemUtils.getItemName(item), "&4&l" + SlimefunPlugin.getLocalization().getMessage(p, "guide.locked"), "", lore);
} } else {
else {
return item; return item;
} }
} }
@ -687,8 +672,7 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
if (i % 2 == 0) { if (i % 2 == 0) {
slot = inputs; slot = inputs;
inputs++; inputs++;
} } else {
else {
slot = outputs; slot = outputs;
outputs++; outputs++;
} }
@ -716,8 +700,7 @@ public class ChestSlimefunGuide implements SlimefunGuideImplementation {
return false; return false;
}); });
} }
} } else {
else {
menu.replaceExistingItem(slot, null); menu.replaceExistingItem(slot, null);
menu.addMenuClickHandler(slot, ChestMenuUtils.getEmptyClickHandler()); menu.addMenuClickHandler(slot, ChestMenuUtils.getEmptyClickHandler());
} }

View File

@ -81,8 +81,7 @@ public class AncientPedestal extends SlimefunItem {
ItemMeta meta = item.getItemStack().getItemMeta(); ItemMeta meta = item.getItemStack().getItemMeta();
return meta.hasDisplayName() && meta.getDisplayName().startsWith(ITEM_PREFIX); return meta.hasDisplayName() && meta.getDisplayName().startsWith(ITEM_PREFIX);
} } else {
else {
return false; return false;
} }
} }
@ -95,8 +94,7 @@ public class AncientPedestal extends SlimefunItem {
ItemMeta im = stack.getItemMeta(); ItemMeta im = stack.getItemMeta();
im.setDisplayName(null); im.setDisplayName(null);
stack.setItemMeta(im); stack.setItemMeta(im);
} } else {
else {
ItemMeta im = stack.getItemMeta(); ItemMeta im = stack.getItemMeta();
if (!customName.startsWith(String.valueOf(ChatColor.COLOR_CHAR))) { if (!customName.startsWith(String.valueOf(ChatColor.COLOR_CHAR))) {

View File

@ -96,12 +96,10 @@ public class MinerAndroid extends ProgrammableAndroid {
block.setType(Material.AIR); block.setType(Material.AIR);
move(b, face, block); move(b, face, block);
} }
} } else {
else {
move(b, face, block); move(b, face, block);
} }
} } else {
else {
move(b, face, block); move(b, face, block);
} }
} }

View File

@ -256,8 +256,7 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
BlockStorage.getInventory(b).open(pl); BlockStorage.getInventory(b).open(pl);
return false; return false;
}); });
} } else {
else {
Instruction instruction = Instruction.getFromCache(script[i]); Instruction instruction = Instruction.getFromCache(script[i]);
if (instruction == null) { if (instruction == null) {
@ -276,13 +275,11 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
String code = duplicateInstruction(script, index); String code = duplicateInstruction(script, index);
setScript(b.getLocation(), code); setScript(b.getLocation(), code);
openScript(pl, b, code); openScript(pl, b, code);
} } else if (action.isRightClicked()) {
else if (action.isRightClicked()) {
String code = deleteInstruction(script, index); String code = deleteInstruction(script, index);
setScript(b.getLocation(), code); setScript(b.getLocation(), code);
openScript(pl, b, code); openScript(pl, b, code);
} } else {
else {
editInstruction(pl, b, script, index); editInstruction(pl, b, script, index);
} }
@ -303,8 +300,7 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
if (i > 0) { if (i > 0) {
if (i == index) { if (i == index) {
builder.append(instruction).append('-'); builder.append(instruction).append('-');
} } else if (i < script.length - 1) {
else if (i < script.length - 1) {
builder.append(current).append('-'); builder.append(current).append('-');
} }
} }
@ -323,8 +319,7 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
if (i > 0) { if (i > 0) {
if (i == index) { if (i == index) {
builder.append(script[i]).append('-').append(script[i]).append('-'); builder.append(script[i]).append('-').append(script[i]).append('-');
} } else if (i < script.length - 1) {
else if (i < script.length - 1) {
builder.append(instruction).append('-'); builder.append(instruction).append('-');
} }
} }
@ -409,23 +404,19 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
if (target >= scripts.size()) { if (target >= scripts.size()) {
break; break;
} } else {
else {
Script script = scripts.get(target); Script script = scripts.get(target);
menu.addItem(index, script.getAsItemStack(this, p), (player, slot, stack, action) -> { menu.addItem(index, script.getAsItemStack(this, p), (player, slot, stack, action) -> {
if (action.isShiftClicked()) { if (action.isShiftClicked()) {
if (script.isAuthor(player)) { if (script.isAuthor(player)) {
SlimefunPlugin.getLocalization().sendMessage(player, "android.scripts.rating.own", true); SlimefunPlugin.getLocalization().sendMessage(player, "android.scripts.rating.own", true);
} } else if (script.canRate(player)) {
else if (script.canRate(player)) {
script.rate(player, !action.isRightClicked()); script.rate(player, !action.isRightClicked());
openScriptDownloader(player, b, page); openScriptDownloader(player, b, page);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(player, "android.scripts.rating.already", true); SlimefunPlugin.getLocalization().sendMessage(player, "android.scripts.rating.already", true);
} }
} } else if (!action.isRightClicked()) {
else if (!action.isRightClicked()) {
script.download(); script.download();
setScript(b.getLocation(), script.getSourceCode()); setScript(b.getLocation(), script.getSourceCode());
openScriptEditor(player, b); openScriptEditor(player, b);
@ -643,8 +634,7 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
if (fuel < 0.001) { if (fuel < 0.001) {
consumeFuel(b, menu); consumeFuel(b, menu);
} } else {
else {
String code = data.getString("script"); String code = data.getString("script");
String[] script = PatternUtils.DASH.split(code == null ? DEFAULT_SCRIPT : code); String[] script = PatternUtils.DASH.split(code == null ? DEFAULT_SCRIPT : code);
@ -703,8 +693,7 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
if (index == POSSIBLE_ROTATIONS.size()) { if (index == POSSIBLE_ROTATIONS.size()) {
index = 0; index = 0;
} } else if (index < 0) {
else if (index < 0) {
index = POSSIBLE_ROTATIONS.size() - 1; index = POSSIBLE_ROTATIONS.size() - 1;
} }
@ -736,8 +725,7 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
if (optional.isPresent()) { if (optional.isPresent()) {
menu.replaceExistingItem(slot, optional.get()); menu.replaceExistingItem(slot, optional.get());
} } else {
else {
menu.replaceExistingItem(slot, null); menu.replaceExistingItem(slot, null);
} }
} }
@ -769,8 +757,7 @@ public class ProgrammableAndroid extends SlimefunItem implements InventoryBlock,
menu.replaceExistingItem(43, newFuel); menu.replaceExistingItem(43, newFuel);
dispenser.setItem(slot, null); dispenser.setItem(slot, null);
return true; return true;
} } else if (SlimefunUtils.isItemSimilar(newFuel, currentFuel, true, false)) {
else if (SlimefunUtils.isItemSimilar(newFuel, currentFuel, true, false)) {
int rest = newFuel.getType().getMaxStackSize() - currentFuel.getAmount(); int rest = newFuel.getType().getMaxStackSize() - currentFuel.getAmount();
if (rest > 0) { if (rest > 0) {

View File

@ -221,8 +221,7 @@ public final class Script {
if (config.contains("code") && config.contains("author")) { if (config.contains("code") && config.contains("author")) {
scripts.add(new Script(config)); scripts.add(new Script(config));
} }
} } catch (Exception x) {
catch (Exception x) {
Slimefun.getLogger().log(Level.SEVERE, x, () -> "An Exception occurred while trying to load Android Script '" + file.getName() + "'"); Slimefun.getLogger().log(Level.SEVERE, x, () -> "An Exception occurred while trying to load Android Script '" + file.getName() + "'");
} }
} }

View File

@ -70,8 +70,7 @@ public class WoodcutterAndroid extends ProgrammableAndroid {
Optional<Material> sapling = MaterialConverter.getSaplingFromLog(log.getType()); Optional<Material> sapling = MaterialConverter.getSaplingFromLog(log.getType());
sapling.ifPresent(log::setType); sapling.ifPresent(log::setType);
} } else {
else {
log.setType(Material.AIR); log.setType(Material.AIR);
} }
} }

View File

@ -83,8 +83,7 @@ public class StomperBoots extends SlimefunItem {
// As the distance approaches zero we might slip into a "division by zero" when normalizing // As the distance approaches zero we might slip into a "division by zero" when normalizing
if (origin.distanceSquared(target) < 0.05) { if (origin.distanceSquared(target) < 0.05) {
return new Vector(0, 1, 0); return new Vector(0, 1, 0);
} } else {
else {
Vector direction = target.toVector().subtract(origin.toVector()); Vector direction = target.toVector().subtract(origin.toVector());
return direction.normalize().multiply(1.4); return direction.normalize().multiply(1.4);
} }

View File

@ -91,8 +91,7 @@ public class BlockPlacer extends SlimefunItem {
if (!(item instanceof NotPlaceable)) { if (!(item instanceof NotPlaceable)) {
placeSlimefunBlock(item, e.getItem(), facedBlock, dispenser); placeSlimefunBlock(item, e.getItem(), facedBlock, dispenser);
} }
} } else {
else {
placeBlock(e.getItem(), facedBlock, dispenser); placeBlock(e.getItem(), facedBlock, dispenser);
} }
} }
@ -153,8 +152,7 @@ public class BlockPlacer extends SlimefunItem {
if (dispenser.getInventory().containsAtLeast(item, 2)) { if (dispenser.getInventory().containsAtLeast(item, 2)) {
dispenser.getInventory().removeItem(new CustomItem(item, 1)); dispenser.getInventory().removeItem(new CustomItem(item, 1));
} } else {
else {
SlimefunPlugin.runSync(() -> dispenser.getInventory().removeItem(item), 2L); SlimefunPlugin.runSync(() -> dispenser.getInventory().removeItem(item), 2L);
} }
} }
@ -168,8 +166,7 @@ public class BlockPlacer extends SlimefunItem {
if (dispenser.getInventory().containsAtLeast(item, 2)) { if (dispenser.getInventory().containsAtLeast(item, 2)) {
dispenser.getInventory().removeItem(new CustomItem(item, 1)); dispenser.getInventory().removeItem(new CustomItem(item, 1));
} } else {
else {
SlimefunPlugin.runSync(() -> dispenser.getInventory().removeItem(item), 2L); SlimefunPlugin.runSync(() -> dispenser.getInventory().removeItem(item), 2L);
} }
} }
@ -206,8 +203,7 @@ public class BlockPlacer extends SlimefunItem {
if (dispenser.getInventory().containsAtLeast(item, 2)) { if (dispenser.getInventory().containsAtLeast(item, 2)) {
dispenser.getInventory().removeItem(new CustomItem(item, 1)); dispenser.getInventory().removeItem(new CustomItem(item, 1));
} } else {
else {
SlimefunPlugin.runSync(() -> dispenser.getInventory().removeItem(item), 2L); SlimefunPlugin.runSync(() -> dispenser.getInventory().removeItem(item), 2L);
} }
} }

View File

@ -101,8 +101,7 @@ public class Composter extends SimpleSlimefunItem<BlockUseHandler> implements Re
}); });
tasks.execute(SlimefunPlugin.instance()); tasks.execute(SlimefunPlugin.instance());
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(p, "machines.wrong-item", true); SlimefunPlugin.getLocalization().sendMessage(p, "machines.wrong-item", true);
} }
} }
@ -115,8 +114,7 @@ public class Composter extends SimpleSlimefunItem<BlockUseHandler> implements Re
if (outputChest.isPresent()) { if (outputChest.isPresent()) {
outputChest.get().addItem(output); outputChest.get().addItem(output);
} } else {
else {
Location loc = b.getRelative(BlockFace.UP).getLocation(); Location loc = b.getRelative(BlockFace.UP).getLocation();
b.getWorld().dropItemNaturally(loc, output); b.getWorld().dropItemNaturally(loc, output);
} }

View File

@ -93,8 +93,7 @@ public class Crucible extends SimpleSlimefunItem<BlockUseHandler> implements Rec
if (craft(p, input)) { if (craft(p, input)) {
boolean water = Tag.LEAVES.isTagged(input.getType()); boolean water = Tag.LEAVES.isTagged(input.getType());
generateLiquid(block, water); generateLiquid(block, water);
} } else {
else {
SlimefunPlugin.getLocalization().sendMessage(p, "machines.wrong-item", true); SlimefunPlugin.getLocalization().sendMessage(p, "machines.wrong-item", true);
} }
} }
@ -122,13 +121,11 @@ public class Crucible extends SimpleSlimefunItem<BlockUseHandler> implements Rec
private void generateLiquid(@Nonnull Block block, boolean water) { private void generateLiquid(@Nonnull Block block, boolean water) {
if (block.getType() == (water ? Material.WATER : Material.LAVA)) { if (block.getType() == (water ? Material.WATER : Material.LAVA)) {
addLiquidLevel(block, water); addLiquidLevel(block, water);
} } else if (block.getType() == (water ? Material.LAVA : Material.WATER)) {
else if (block.getType() == (water ? Material.LAVA : Material.WATER)) {
int level = ((Levelled) block.getBlockData()).getLevel(); int level = ((Levelled) block.getBlockData()).getLevel();
block.setType(level == 0 || level == 8 ? Material.OBSIDIAN : Material.STONE); block.setType(level == 0 || level == 8 ? Material.OBSIDIAN : Material.STONE);
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_LAVA_EXTINGUISH, 1F, 1F); block.getWorld().playSound(block.getLocation(), Sound.BLOCK_LAVA_EXTINGUISH, 1F, 1F);
} } else {
else {
SlimefunPlugin.runSync(() -> placeLiquid(block, water), 50L); SlimefunPlugin.runSync(() -> placeLiquid(block, water), 50L);
} }
} }
@ -142,8 +139,7 @@ public class Crucible extends SimpleSlimefunItem<BlockUseHandler> implements Rec
if (level == 0) { if (level == 0) {
block.getWorld().playSound(block.getLocation(), water ? Sound.ENTITY_PLAYER_SPLASH : Sound.BLOCK_LAVA_POP, 1F, 1F); block.getWorld().playSound(block.getLocation(), water ? Sound.ENTITY_PLAYER_SPLASH : Sound.BLOCK_LAVA_POP, 1F, 1F);
} } else {
else {
int finalLevel = 7 - level; int finalLevel = 7 - level;
SlimefunPlugin.runSync(() -> runPostTask(block, water ? Sound.ENTITY_PLAYER_SPLASH : Sound.BLOCK_LAVA_POP, finalLevel), 50L); SlimefunPlugin.runSync(() -> runPostTask(block, water ? Sound.ENTITY_PLAYER_SPLASH : Sound.BLOCK_LAVA_POP, finalLevel), 50L);
} }
@ -152,8 +148,7 @@ public class Crucible extends SimpleSlimefunItem<BlockUseHandler> implements Rec
private void placeLiquid(@Nonnull Block block, boolean water) { private void placeLiquid(@Nonnull Block block, boolean water) {
if (block.getType() == Material.AIR || block.getType() == Material.CAVE_AIR || block.getType() == Material.VOID_AIR) { if (block.getType() == Material.AIR || block.getType() == Material.CAVE_AIR || block.getType() == Material.VOID_AIR) {
block.setType(water ? Material.WATER : Material.LAVA); block.setType(water ? Material.WATER : Material.LAVA);
} } else {
else {
if (water && block.getBlockData() instanceof Waterlogged) { if (water && block.getBlockData() instanceof Waterlogged) {
Waterlogged wl = (Waterlogged) block.getBlockData(); Waterlogged wl = (Waterlogged) block.getBlockData();
wl.setWaterlogged(true); wl.setWaterlogged(true);
@ -185,8 +180,7 @@ public class Crucible extends SimpleSlimefunItem<BlockUseHandler> implements Rec
if (times < 8) { if (times < 8) {
SlimefunPlugin.runSync(() -> runPostTask(block, sound, times + 1), 50L); SlimefunPlugin.runSync(() -> runPostTask(block, sound, times + 1), 50L);
} } else {
else {
block.getWorld().playSound(block.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1F, 1F); block.getWorld().playSound(block.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1F, 1F);
} }
} }

View File

@ -76,8 +76,7 @@ public class EnhancedFurnace extends SimpleSlimefunItem<BlockTicker> {
if (b.getType() != Material.FURNACE) { if (b.getType() != Material.FURNACE) {
// The Furnace has been destroyed, we can clear the block data // The Furnace has been destroyed, we can clear the block data
BlockStorage.clearBlockInfo(b); BlockStorage.clearBlockInfo(b);
} } else {
else {
BlockStateSnapshotResult result = PaperLib.getBlockState(b, false); BlockStateSnapshotResult result = PaperLib.getBlockState(b, false);
BlockState state = result.getState(); BlockState state = result.getState();

View File

@ -79,7 +79,7 @@ public class RepairedSpawner extends SimpleSlimefunItem<BlockPlaceHandler> {
return Optional.empty(); return Optional.empty();
} }
@Override @Override
public Collection<ItemStack> getDrops() { public Collection<ItemStack> getDrops() {
// There should be no drops by default since drops are handled by the // There should be no drops by default since drops are handled by the

View File

@ -86,8 +86,7 @@ abstract class AbstractCargoNode extends SlimefunItem {
if (newChannel < 0) { if (newChannel < 0) {
if (isChestTerminalInstalled) { if (isChestTerminalInstalled) {
newChannel = 16; newChannel = 16;
} } else {
else {
newChannel = 15; newChannel = 15;
} }
} }
@ -100,8 +99,7 @@ abstract class AbstractCargoNode extends SlimefunItem {
if (channel == 16) { if (channel == 16) {
menu.replaceExistingItem(slotCurrent, new CustomItem(HeadTexture.CHEST_TERMINAL.getAsItemStack(), "&bChannel ID: &3" + (channel + 1))); menu.replaceExistingItem(slotCurrent, new CustomItem(HeadTexture.CHEST_TERMINAL.getAsItemStack(), "&bChannel ID: &3" + (channel + 1)));
menu.addMenuClickHandler(slotCurrent, ChestMenuUtils.getEmptyClickHandler()); menu.addMenuClickHandler(slotCurrent, ChestMenuUtils.getEmptyClickHandler());
} } else {
else {
menu.replaceExistingItem(slotCurrent, new CustomItem(MaterialCollections.getAllWoolColors().get(channel), "&bChannel ID: &3" + (channel + 1))); menu.replaceExistingItem(slotCurrent, new CustomItem(MaterialCollections.getAllWoolColors().get(channel), "&bChannel ID: &3" + (channel + 1)));
menu.addMenuClickHandler(slotCurrent, ChestMenuUtils.getEmptyClickHandler()); menu.addMenuClickHandler(slotCurrent, ChestMenuUtils.getEmptyClickHandler());
} }
@ -114,8 +112,7 @@ abstract class AbstractCargoNode extends SlimefunItem {
if (newChannel > 16) { if (newChannel > 16) {
newChannel = 0; newChannel = 0;
} }
} } else if (newChannel > 15) {
else if (newChannel > 15) {
newChannel = 0; newChannel = 0;
} }
@ -128,14 +125,12 @@ abstract class AbstractCargoNode extends SlimefunItem {
private int getSelectedChannel(Block b) { private int getSelectedChannel(Block b) {
if (!BlockStorage.hasBlockInfo(b)) { if (!BlockStorage.hasBlockInfo(b)) {
return 0; return 0;
} } else {
else {
String frequency = BlockStorage.getLocationInfo(b.getLocation(), FREQUENCY); String frequency = BlockStorage.getLocationInfo(b.getLocation(), FREQUENCY);
if (frequency == null) { if (frequency == null) {
return 0; return 0;
} } else {
else {
int channel = Integer.parseInt(frequency); int channel = Integer.parseInt(frequency);
return NumberUtils.clamp(0, channel, 16); return NumberUtils.clamp(0, channel, 16);
} }

View File

@ -74,8 +74,7 @@ abstract class AbstractFilterNode extends AbstractCargoNode {
updateBlockMenu(menu, b); updateBlockMenu(menu, b);
return false; return false;
}); });
} } else {
else {
menu.replaceExistingItem(15, new CustomItem(Material.BLACK_WOOL, "&7Type: &8Blacklist", "", "&e> Click to change it to Whitelist")); menu.replaceExistingItem(15, new CustomItem(Material.BLACK_WOOL, "&7Type: &8Blacklist", "", "&e> Click to change it to Whitelist"));
menu.addMenuClickHandler(15, (p, slot, item, action) -> { menu.addMenuClickHandler(15, (p, slot, item, action) -> {
BlockStorage.addBlockInfo(b, FILTER_TYPE, "whitelist"); BlockStorage.addBlockInfo(b, FILTER_TYPE, "whitelist");
@ -93,8 +92,7 @@ abstract class AbstractFilterNode extends AbstractCargoNode {
updateBlockMenu(menu, b); updateBlockMenu(menu, b);
return false; return false;
}); });
} } else {
else {
menu.replaceExistingItem(25, new CustomItem(Material.MAP, "&7Include Lore: &4\u2718", "", "&e> Click to toggle whether the Lore has to match")); menu.replaceExistingItem(25, new CustomItem(Material.MAP, "&7Include Lore: &4\u2718", "", "&e> Click to toggle whether the Lore has to match"));
menu.addMenuClickHandler(25, (p, slot, item, action) -> { menu.addMenuClickHandler(25, (p, slot, item, action) -> {
BlockStorage.addBlockInfo(b, FILTER_LORE, String.valueOf(true)); BlockStorage.addBlockInfo(b, FILTER_LORE, String.valueOf(true));

View File

@ -31,8 +31,7 @@ public class CargoConnectorNode extends SimpleSlimefunItem<BlockUseHandler> {
if (CargoNet.getNetworkFromLocation(b.getLocation()) != null) { if (CargoNet.getNetworkFromLocation(b.getLocation()) != null) {
p.sendMessage(ChatColors.color("&7Connected: " + "&2\u2714")); p.sendMessage(ChatColors.color("&7Connected: " + "&2\u2714"));
} } else {
else {
p.sendMessage(ChatColors.color("&7Connected: " + "&4\u2718")); p.sendMessage(ChatColors.color("&7Connected: " + "&4\u2718"));
} }
}; };

View File

@ -44,8 +44,7 @@ public class CargoInputNode extends AbstractFilterNode {
updateBlockMenu(menu, b); updateBlockMenu(menu, b);
return false; return false;
}); });
} } else {
else {
menu.replaceExistingItem(24, new CustomItem(HeadTexture.ENERGY_REGULATOR.getAsItemStack(), "&7Round-Robin Mode: &2\u2714", "", "&e> Click to disable Round Robin Mode", "&e(Items will be equally distributed on the Channel)")); menu.replaceExistingItem(24, new CustomItem(HeadTexture.ENERGY_REGULATOR.getAsItemStack(), "&7Round-Robin Mode: &2\u2714", "", "&e> Click to disable Round Robin Mode", "&e(Items will be equally distributed on the Channel)"));
menu.addMenuClickHandler(24, (p, slot, item, action) -> { menu.addMenuClickHandler(24, (p, slot, item, action) -> {
BlockStorage.addBlockInfo(b, ROUND_ROBIN_MODE, String.valueOf(false)); BlockStorage.addBlockInfo(b, ROUND_ROBIN_MODE, String.valueOf(false));

View File

@ -57,8 +57,7 @@ public class CargoManager extends SlimefunItem {
if (BlockStorage.getLocationInfo(b.getLocation(), "visualizer") == null) { if (BlockStorage.getLocationInfo(b.getLocation(), "visualizer") == null) {
BlockStorage.addBlockInfo(b, "visualizer", "disabled"); BlockStorage.addBlockInfo(b, "visualizer", "disabled");
p.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cCargo Net Visualizer: " + "&4\u2718")); p.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cCargo Net Visualizer: " + "&4\u2718"));
} } else {
else {
BlockStorage.addBlockInfo(b, "visualizer", null); BlockStorage.addBlockInfo(b, "visualizer", null);
p.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cCargo Net Visualizer: " + "&2\u2714")); p.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cCargo Net Visualizer: " + "&2\u2714"));
} }

View File

@ -62,8 +62,7 @@ public class ReactorAccessPort extends SlimefunItem {
return false; return false;
}); });
} } else {
else {
menu.replaceExistingItem(INFO_SLOT, new CustomItem(Material.RED_WOOL, "&7Reactor", "", "&cNot detected", "", "&7Reactor must be", "&7placed 3 blocks below", "&7the access port!")); menu.replaceExistingItem(INFO_SLOT, new CustomItem(Material.RED_WOOL, "&7Reactor", "", "&cNot detected", "", "&7Reactor must be", "&7placed 3 blocks below", "&7the access port!"));
menu.addMenuClickHandler(INFO_SLOT, (p, slot, item, action) -> { menu.addMenuClickHandler(INFO_SLOT, (p, slot, item, action) -> {
newInstance(menu, b); newInstance(menu, b);
@ -76,8 +75,7 @@ public class ReactorAccessPort extends SlimefunItem {
public int[] getSlotsAccessedByItemTransport(ItemTransportFlow flow) { public int[] getSlotsAccessedByItemTransport(ItemTransportFlow flow) {
if (flow == ItemTransportFlow.INSERT) { if (flow == ItemTransportFlow.INSERT) {
return getInputSlots(); return getInputSlots();
} } else {
else {
return getOutputSlots(); return getOutputSlots();
} }
} }
@ -87,12 +85,10 @@ public class ReactorAccessPort extends SlimefunItem {
if (flow == ItemTransportFlow.INSERT) { if (flow == ItemTransportFlow.INSERT) {
if (SlimefunItem.getByItem(item) instanceof CoolantCell) { if (SlimefunItem.getByItem(item) instanceof CoolantCell) {
return getCoolantSlots(); return getCoolantSlots();
} } else {
else {
return getFuelSlots(); return getFuelSlots();
} }
} } else {
else {
return getOutputSlots(); return getOutputSlots();
} }
} }

View File

@ -73,8 +73,7 @@ public class MultiTool extends SlimefunItem implements Rechargeable {
sfItem.callItemHandler(ItemUseHandler.class, handler -> handler.onRightClick(e)); sfItem.callItemHandler(ItemUseHandler.class, handler -> handler.onRightClick(e));
} }
} }
} } else {
else {
index = nextIndex(index); index = nextIndex(index);
SlimefunItem selectedItem = modes.get(index).getItem(); SlimefunItem selectedItem = modes.get(index).getItem();

View File

@ -11,7 +11,7 @@ class MultiToolMode {
MultiToolMode(MultiTool multiTool, int id, String itemId) { MultiToolMode(MultiTool multiTool, int id, String itemId) {
this.item = new ItemSetting<>("mode." + id + ".item", itemId); this.item = new ItemSetting<>("mode." + id + ".item", itemId);
this.enabled = new ItemSetting<>("mode." + id + ".enabled", true); this.enabled = new ItemSetting<>("mode." + id + ".enabled", true);
multiTool.addItemSetting(item, enabled); multiTool.addItemSetting(item, enabled);
} }

View File

@ -71,18 +71,15 @@ public class SolarGenerator extends SlimefunItem implements EnergyNetProvider {
if (world.getEnvironment() != Environment.NORMAL) { if (world.getEnvironment() != Environment.NORMAL) {
return 0; return 0;
} } else {
else {
boolean isDaytime = isDaytime(world); boolean isDaytime = isDaytime(world);
// Performance optimization for daytime-only solar generators // Performance optimization for daytime-only solar generators
if (!isDaytime && getNightEnergy() < 1) { if (!isDaytime && getNightEnergy() < 1) {
return 0; return 0;
} } else if (!world.isChunkLoaded(l.getBlockX() >> 4, l.getBlockZ() >> 4) || l.getBlock().getLightFromSky() < 15) {
else if (!world.isChunkLoaded(l.getBlockX() >> 4, l.getBlockZ() >> 4) || l.getBlock().getLightFromSky() < 15) {
return 0; return 0;
} } else {
else {
return isDaytime ? getDayEnergy() : getNightEnergy(); return isDaytime ? getDayEnergy() : getNightEnergy();
} }
} }

View File

@ -95,8 +95,7 @@ public abstract class AbstractEntityAssembler<T extends Entity> extends SimpleSl
public int[] getSlotsAccessedByItemTransport(ItemTransportFlow flow) { public int[] getSlotsAccessedByItemTransport(ItemTransportFlow flow) {
if (flow == ItemTransportFlow.INSERT) { if (flow == ItemTransportFlow.INSERT) {
return inputSlots; return inputSlots;
} } else {
else {
return new int[0]; return new int[0];
} }
} }
@ -162,8 +161,7 @@ public abstract class AbstractEntityAssembler<T extends Entity> extends SimpleSl
updateBlockInventory(menu, b); updateBlockInventory(menu, b);
return false; return false;
}); });
} } else {
else {
menu.replaceExistingItem(22, new CustomItem(Material.REDSTONE, "&7Enabled: &2\u2714", "", "&e> Click to disable this Machine")); menu.replaceExistingItem(22, new CustomItem(Material.REDSTONE, "&7Enabled: &2\u2714", "", "&e> Click to disable this Machine"));
menu.addMenuClickHandler(22, (p, slot, item, action) -> { menu.addMenuClickHandler(22, (p, slot, item, action) -> {
BlockStorage.addBlockInfo(b, KEY_ENABLED, String.valueOf(false)); BlockStorage.addBlockInfo(b, KEY_ENABLED, String.valueOf(false));
@ -254,8 +252,7 @@ public abstract class AbstractEntityAssembler<T extends Entity> extends SimpleSl
if (amount >= bodyCount) { if (amount >= bodyCount) {
inv.consumeItem(slot, bodyCount); inv.consumeItem(slot, bodyCount);
break; break;
} } else {
else {
bodyCount -= amount; bodyCount -= amount;
inv.replaceExistingItem(slot, null); inv.replaceExistingItem(slot, null);
} }
@ -269,8 +266,7 @@ public abstract class AbstractEntityAssembler<T extends Entity> extends SimpleSl
if (amount >= headCount) { if (amount >= headCount) {
inv.consumeItem(slot, headCount); inv.consumeItem(slot, headCount);
break; break;
} } else {
else {
headCount -= amount; headCount -= amount;
inv.replaceExistingItem(slot, null); inv.replaceExistingItem(slot, null);
} }

View File

@ -90,8 +90,7 @@ public abstract class AutoBrewer extends AContainer {
} }
return new MachineRecipe(30, new ItemStack[] { input1, input2 }, new ItemStack[] { output }); return new MachineRecipe(30, new ItemStack[] { input1, input2 }, new ItemStack[] { output });
} } else {
else {
return null; return null;
} }
} }
@ -103,35 +102,28 @@ public abstract class AutoBrewer extends AContainer {
if (input == Material.FERMENTED_SPIDER_EYE) { if (input == Material.FERMENTED_SPIDER_EYE) {
potion.setBasePotionData(new PotionData(PotionType.WEAKNESS, false, false)); potion.setBasePotionData(new PotionData(PotionType.WEAKNESS, false, false));
return new ItemStack(potionType); return new ItemStack(potionType);
} } else if (input == Material.NETHER_WART) {
else if (input == Material.NETHER_WART) {
potion.setBasePotionData(new PotionData(PotionType.AWKWARD, false, false)); potion.setBasePotionData(new PotionData(PotionType.AWKWARD, false, false));
return new ItemStack(potionType); return new ItemStack(potionType);
} } else if (potionType == Material.POTION && input == Material.GUNPOWDER) {
else if (potionType == Material.POTION && input == Material.GUNPOWDER) {
return new ItemStack(Material.SPLASH_POTION); return new ItemStack(Material.SPLASH_POTION);
} } else if (potionType == Material.SPLASH_POTION && input == Material.DRAGON_BREATH) {
else if (potionType == Material.SPLASH_POTION && input == Material.DRAGON_BREATH) {
return new ItemStack(Material.LINGERING_POTION); return new ItemStack(Material.LINGERING_POTION);
} }
} } else if (input == Material.FERMENTED_SPIDER_EYE) {
else if (input == Material.FERMENTED_SPIDER_EYE) {
PotionType fermented = fermentations.get(data.getType()); PotionType fermented = fermentations.get(data.getType());
if (fermented != null) { if (fermented != null) {
potion.setBasePotionData(new PotionData(fermented, false, false)); potion.setBasePotionData(new PotionData(fermented, false, false));
return new ItemStack(potionType); return new ItemStack(potionType);
} }
} } else if (input == Material.REDSTONE) {
else if (input == Material.REDSTONE) {
potion.setBasePotionData(new PotionData(data.getType(), true, data.isUpgraded())); potion.setBasePotionData(new PotionData(data.getType(), true, data.isUpgraded()));
return new ItemStack(potionType); return new ItemStack(potionType);
} } else if (input == Material.GLOWSTONE_DUST) {
else if (input == Material.GLOWSTONE_DUST) {
potion.setBasePotionData(new PotionData(data.getType(), data.isExtended(), true)); potion.setBasePotionData(new PotionData(data.getType(), data.isExtended(), true));
return new ItemStack(potionType); return new ItemStack(potionType);
} } else if (data.getType() == PotionType.AWKWARD) {
else if (data.getType() == PotionType.AWKWARD) {
PotionType potionRecipe = potionRecipes.get(input); PotionType potionRecipe = potionRecipes.get(input);
if (potionRecipe != null) { if (potionRecipe != null) {

View File

@ -108,7 +108,7 @@ public class AutoDisenchanter extends AContainer {
EmeraldEnchants.getInstance().getRegistry().applyEnchantment(disenchantedItem, ench.getEnchantment(), 0); EmeraldEnchants.getInstance().getRegistry().applyEnchantment(disenchantedItem, ench.getEnchantment(), 0);
} }
MachineRecipe recipe = new MachineRecipe(90 * amount / this.getSpeed() , new ItemStack[] { target, item }, new ItemStack[] { disenchantedItem, book }); MachineRecipe recipe = new MachineRecipe(90 * amount / this.getSpeed(), new ItemStack[] { target, item }, new ItemStack[] { disenchantedItem, book });
if (!InvUtils.fitAll(menu.toInventory(), recipe.getOutput(), getOutputSlots())) { if (!InvUtils.fitAll(menu.toInventory(), recipe.getOutput(), getOutputSlots())) {
return null; return null;
@ -152,8 +152,7 @@ public class AutoDisenchanter extends AContainer {
else if (item.getType() != Material.BOOK) { else if (item.getType() != Material.BOOK) {
SlimefunItem sfItem = SlimefunItem.getByItem(item); SlimefunItem sfItem = SlimefunItem.getByItem(item);
return sfItem == null || sfItem.isDisenchantable(); return sfItem == null || sfItem.isDisenchantable();
} } else {
else {
return true; return true;
} }

View File

@ -61,8 +61,7 @@ public abstract class AutomatedCraftingChamber extends SlimefunItem implements I
newInstance(menu, b); newInstance(menu, b);
return false; return false;
}); });
} } else {
else {
menu.replaceExistingItem(6, new CustomItem(Material.REDSTONE, "&7Enabled: &2\u2714", "", "&e> Click to disable this Machine")); menu.replaceExistingItem(6, new CustomItem(Material.REDSTONE, "&7Enabled: &2\u2714", "", "&e> Click to disable this Machine"));
menu.addMenuClickHandler(6, (p, slot, item, action) -> { menu.addMenuClickHandler(6, (p, slot, item, action) -> {
BlockStorage.addBlockInfo(b, "enabled", String.valueOf(false)); BlockStorage.addBlockInfo(b, "enabled", String.valueOf(false));
@ -235,8 +234,10 @@ public abstract class AutomatedCraftingChamber extends SlimefunItem implements I
ItemStack item = menu.getItemInSlot(getInputSlots()[j]); ItemStack item = menu.getItemInSlot(getInputSlots()[j]);
if (item != null && item.getAmount() == 1) { if (item != null && item.getAmount() == 1) {
if (craftLast) lastIteration = true; if (craftLast)
else return ""; lastIteration = true;
else
return "";
} }
builder.append(CustomItemSerializer.serialize(item, ItemFlag.MATERIAL, ItemFlag.ITEMMETA_DISPLAY_NAME, ItemFlag.ITEMMETA_LORE)); builder.append(CustomItemSerializer.serialize(item, ItemFlag.MATERIAL, ItemFlag.ITEMMETA_DISPLAY_NAME, ItemFlag.ITEMMETA_LORE));
@ -247,7 +248,8 @@ public abstract class AutomatedCraftingChamber extends SlimefunItem implements I
// we're only executing the last possible shaped recipe // we're only executing the last possible shaped recipe
// we don't want to allow this to be pressed instead of the default timer-based // we don't want to allow this to be pressed instead of the default timer-based
// execution to prevent abuse and auto clickers // execution to prevent abuse and auto clickers
if (craftLast && !lastIteration) return ""; if (craftLast && !lastIteration)
return "";
return builder.toString(); return builder.toString();
} }

View File

@ -67,15 +67,13 @@ public class ChargingBench extends AContainer {
if (((Rechargeable) sfItem).addItemCharge(item, charge)) { if (((Rechargeable) sfItem).addItemCharge(item, charge)) {
removeCharge(b.getLocation(), getEnergyConsumption()); removeCharge(b.getLocation(), getEnergyConsumption());
} } else if (inv.fits(item, getOutputSlots())) {
else if (inv.fits(item, getOutputSlots())) {
inv.pushItem(item, getOutputSlots()); inv.pushItem(item, getOutputSlots());
inv.replaceExistingItem(slot, null); inv.replaceExistingItem(slot, null);
} }
return true; return true;
} } else if (sfItem != null && inv.fits(item, getOutputSlots())) {
else if (sfItem != null && inv.fits(item, getOutputSlots())) {
inv.pushItem(item, getOutputSlots()); inv.pushItem(item, getOutputSlots());
inv.replaceExistingItem(slot, null); inv.replaceExistingItem(slot, null);
} }

View File

@ -52,8 +52,7 @@ public abstract class ElectricDustWasher extends AContainer {
menu.consumeItem(slot); menu.consumeItem(slot);
return recipe; return recipe;
} }
} } else if (SlimefunUtils.isItemSimilar(menu.getItemInSlot(slot), SlimefunItems.PULVERIZED_ORE, true)) {
else if (SlimefunUtils.isItemSimilar(menu.getItemInSlot(slot), SlimefunItems.PULVERIZED_ORE, true)) {
MachineRecipe recipe = new MachineRecipe(4 / getSpeed(), new ItemStack[0], new ItemStack[] { SlimefunItems.PURE_ORE_CLUSTER }); MachineRecipe recipe = new MachineRecipe(4 / getSpeed(), new ItemStack[0], new ItemStack[] { SlimefunItems.PURE_ORE_CLUSTER });
if (menu.fits(recipe.getOutput()[0], getOutputSlots())) { if (menu.fits(recipe.getOutput()[0], getOutputSlots())) {

View File

@ -56,8 +56,7 @@ public abstract class ElectricGoldPan extends AContainer implements RecipeDispla
menu.consumeItem(slot); menu.consumeItem(slot);
return recipe; return recipe;
} }
} } else if (SlimefunUtils.isItemSimilar(menu.getItemInSlot(slot), new ItemStack(Material.SOUL_SAND), true, false)) {
else if (SlimefunUtils.isItemSimilar(menu.getItemInSlot(slot), new ItemStack(Material.SOUL_SAND), true, false)) {
ItemStack output = netherGoldPan.getRandomOutput(); ItemStack output = netherGoldPan.getRandomOutput();
MachineRecipe recipe = new MachineRecipe(4 / getSpeed(), new ItemStack[0], new ItemStack[] { output }); MachineRecipe recipe = new MachineRecipe(4 / getSpeed(), new ItemStack[0], new ItemStack[] { output });

View File

@ -83,12 +83,10 @@ public abstract class ElectricSmeltery extends AContainer {
if (slots.isEmpty()) { if (slots.isEmpty()) {
return getInputSlots(); return getInputSlots();
} } else if (fullSlots == slots.size()) {
else if (fullSlots == slots.size()) {
// All slots with that item are already full // All slots with that item are already full
return new int[0]; return new int[0];
} } else {
else {
Collections.sort(slots, compareSlots(menu)); Collections.sort(slots, compareSlots(menu));
int[] array = new int[slots.size()]; int[] array = new int[slots.size()];

View File

@ -151,8 +151,7 @@ public class FluidPump extends SimpleSlimefunItem<BlockTicker> implements Invent
if (isSource(fluid)) { if (isSource(fluid)) {
return fluid; return fluid;
} }
} } else if (fluid.getType() == Material.LAVA) {
else if (fluid.getType() == Material.LAVA) {
List<Block> list = Vein.find(fluid, RANGE, block -> block.getType() == fluid.getType()); List<Block> list = Vein.find(fluid, RANGE, block -> block.getType() == fluid.getType());
for (int i = list.size() - 1; i >= 0; i--) { for (int i = list.size() - 1; i >= 0; i--) {
@ -169,11 +168,9 @@ public class FluidPump extends SimpleSlimefunItem<BlockTicker> implements Invent
private ItemStack getFilledBucket(Block fluid) { private ItemStack getFilledBucket(Block fluid) {
if (fluid.getType() == Material.LAVA) { if (fluid.getType() == Material.LAVA) {
return new ItemStack(Material.LAVA_BUCKET); return new ItemStack(Material.LAVA_BUCKET);
} } else if (fluid.getType() == Material.WATER || fluid.getType() == Material.BUBBLE_COLUMN) {
else if (fluid.getType() == Material.WATER || fluid.getType() == Material.BUBBLE_COLUMN) {
return new ItemStack(Material.WATER_BUCKET); return new ItemStack(Material.WATER_BUCKET);
} } else {
else {
// Fallback for any new liquids // Fallback for any new liquids
return new ItemStack(Material.BUCKET); return new ItemStack(Material.BUCKET);
} }

Some files were not shown because too many files have changed in this diff Show More