Compare commits

..
Author SHA1 Message Date
main() caf4f1b566 Bukkit perms are broken.
Or at least they don't work the way they (in my opinion) should. Take a
look at HierarchyPermission.java for a detailed explanation.
2013-04-13 02:26:19 +02:00
129 changed files with 2689 additions and 4808 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: 💬 ​Multiverse Discord Server
url: https://discord.gg/NZtfKky
about: Need help with using Multiverse-Core or just want to chat with the devs? Join the Multiverse Discord Server for help!
-56
View File
@@ -1,56 +0,0 @@
---
name: ❓ Help!
about: Encountered a problem with Multiverse-Core? Not sure how to fix it?
title: ''
labels: 'Type: Assistance'
assignees: ''
---
<!-- Multiverse-Core help guide
Don't write inside the arrows as they will be hidden when you post your issue.
Get latest build from: http://ci.onarandombox.com/view/Multiverse/
If you need help other submodules of Multiverse, go to their respective git repo:
Multiverse-Portals: https://github.com/Multiverse/Multiverse-Portals/issues
Multiverse-NetherPortals: https://github.com/Multiverse/Multiverse-NetherPortals/issues
Multiverse-Inventories: https://github.com/Multiverse/Multiverse-Inventories/issues
Multiverse-SignPortals: https://github.com/Multiverse/Multiverse-SignPortals/issues
Or come join our Discord server to get help sooner: https://discord.gg/NZtfKky
If you're happy to wait (or you were sent here from Discord), read on:
1. Check the Usage and FAQ pages to see if it answers your queries:
https://github.com/Multiverse/Multiverse-Core/wiki/Basics
https://github.com/Multiverse/Multiverse-Core/wiki/FAQ
2. Fill out the template.
This will help us understand what problem you've encountered and help us
find a solution.
3. When linking files, do not attach them to the post!
Copy and paste any logs into https://gist.github.com/ or other similar service.
4. Delete this line and all above lines before posting your issue! -->
### Information
* **Server version:** <!-- Insert output of `/version` command -->
* **Full output of `/mv version -p`:** <!-- Replace this with the command output's https://paste.gg/ link -->
* **Server log:** <!-- Upload `logs/latest.log` to https://gist.github.com/ -->
### Help request
**Problem**
<!-- What problem did you encounter? -->
**What I have tried**
<!-- What have you tried so far? -->
**Screenshots**
<!-- If relevant, include any screenshots here. -->
-59
View File
@@ -1,59 +0,0 @@
---
name: 🐛 Report a Bug
about: Report a Multiverse-Core bug. Only use this if you're 100% sure it's something wrong with Multiverse-Core - otherwise, try "Help!".
title: ''
labels: 'Bug: Unconfirmed'
assignees: ''
---
<!-- Multiverse-Core bug reporting guide
Don't put anything inside this block, as it won't be included in the issue.
Get latest build from: http://ci.onarandombox.com/view/Multiverse/
If you are having issues with other submodules of Multiverse, go to their respective git repo:
Multiverse-Portals: https://github.com/Multiverse/Multiverse-Portals/issues
Multiverse-NetherPortals: https://github.com/Multiverse/Multiverse-NetherPortals/issues
Multiverse-Inventories: https://github.com/Multiverse/Multiverse-Inventories/issues
Multiverse-SignPortals: https://github.com/Multiverse/Multiverse-SignPortals/issues
If you are reporting a bug, please follow the following steps:
1. Fill out the template in full.
Run the commands in the console. Don't just put "latest" as a version,
or we will ignore it.
2. When linking files, do not attach them to the post!
Copy and paste any logs into https://gist.github.com/, then paste a
link to them in the relevant parts of the template.
**DO NOT drag files into this box!**
3. Make sure not to write between the arrows, as anything there will be
hidden.
4. Delete this line and all above lines before posting your issue! -->
### Information
* **Server version:** <!-- Insert output of `/version` command -->
* **Full output of `/mv version -p`:** <!-- Replace this with the command output's https://paste.gg/ link -->
* **Server log:** <!-- Upload `logs/latest.log` to https://gist.github.com/ -->
### Details
I was **`<able / not able>`** to reproduce my issue on a freshly setup and up-to-date server with the latest version of Multiverse plugins with no other plugins and with no kinds of other server or client mods.
**Description**
<!-- Replace this with a brief summary of the bug. -->
**Steps to reproduce**
<!-- Replace this with exactly what you did to cause the bug. -->
**Expected behavior**
<!-- Replace this with what you expected to happen. -->
**Screenshots**
<!-- Replace this with screenshots, if necessary. -->
@@ -1,54 +0,0 @@
---
name: 💡 Request a Feature
about: Suggest a feature you want to see in Multiverse-Core!
title: ''
labels: 'Type: Idea'
assignees: ''
---
<!-- Multiverse-Core feature request guide
Fill out the template. Don't write inside the arrows as they will be hidden
when you post your issue.
Get latest build from: http://ci.onarandombox.com/view/Multiverse/
If you are look for other submodules of Multiverse, go to their respective git repo:
Multiverse-Portals: https://github.com/Multiverse/Multiverse-Portals/issues
Multiverse-NetherPortals: https://github.com/Multiverse/Multiverse-NetherPortals/issues
Multiverse-Inventories: https://github.com/Multiverse/Multiverse-Inventories/issues
Multiverse-SignPortals: https://github.com/Multiverse/Multiverse-SignPortals/issues
Not sure if your feature fits in Multiverse-Core? Feel free to ask on our Discord
server: https://discord.gg/NZtfKky
If you have a feature suggestion for Multiverse-Core, read the following tips:
1. Fill out the template.
This will help us understand what you're requesting and why you want us
to add it.
2. Keep it simple.
Make sure it's easy to understand what you're requesting. A good way is
to keep it to one request per GitHub issue, as we can then easily track
feature requests.
3. Check whether it has already been asked or added.
You can search the issue tracker to see if your feature has already been
requested at https://github.com/Multiverse/Multiverse-Core/issues.
4. Ask yourself: "Does this belong in Multiverse-Core?"
There are lots of features that we reject because most servers won't
need or use them. If your feature is very specific or already exists in
another plugin, it might not be a good fit for Multiverse-Core.
5. Delete this line and all above lines before posting your issue! -->
### Feature request
**Feature description**
<!-- What feature are you suggesting? -->
**How the feature is useful**
<!-- How is the feature useful to players, server owners and/or developers? -->
-1
View File
@@ -12,7 +12,6 @@
# maven
/target
dependency-reduced-pom.xml
# vim
.*.sw[a-p]
+5 -6
View File
@@ -1,6 +1,5 @@
language: java
jdk:
- oraclejdk8
notifications:
email: false
dist: trusty
language: java
jdk:
- oraclejdk6
notifications:
email: false
-1
View File
@@ -13,4 +13,3 @@ Copyright (c) 2011, The Multiverse Team All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the The Multiverse Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+1
View File
@@ -115,6 +115,7 @@
<property name="ignoreNumbers" value="-1, 0, 0.5, 1, 2, 3"/>
</module>
<module name="MissingSwitchDefault"/>
<module name="RedundantThrows"/>
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<!-- Don't like errors for `final` missing
+129 -155
View File
@@ -3,41 +3,33 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.onarandombox.multiversecore</groupId>
<artifactId>Multiverse-Core</artifactId>
<version>4.2.3-SNAPSHOT</version>
<version>2.5</version>
<name>Multiverse-Core</name>
<description>World Management Plugin</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.number>UNKNOWN</project.build.number>
<project.bitly-access-token>bitly-access-token</project.bitly-access-token>
</properties>
<repositories>
<!-- Spigot -->
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>onarandombox</id>
<url>http://repo.onarandombox.com/content/groups/public</url>
</repository>
<repository>
<id>spigot</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
<id>Bukkit Official</id>
<url>http://repo.bukkit.org/content/repositories/public</url>
</repository>
<!-- Required for Metrics -->
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<repository>
<id>minebench-repo</id>
<url>https://repo.minebench.de/</url>
</repository>
<repository>
<id>CodeMC</id>
<url>https://repo.codemc.org/repository/maven-public</url>
<id>mcstats</id>
<url>http://repo.mcstats.org/content/repositories/snapshots</url>
</repository>
<!-- Required for Vault -->
<!--repository>
<id>herocraft</id>
<url>http://ci.herocraftonline.com/plugin/repository/everything/</url>
</repository-->
</repositories>
<pluginRepositories>
@@ -70,17 +62,6 @@
<project.build.number>${env.BUILD_NUMBER}</project.build.number>
</properties>
</profile>
<profile>
<id>bitly</id>
<activation>
<property>
<name>env.BITLY_ACCESS_TOKEN</name>
</property>
</activation>
<properties>
<project.bitly-access-token>${env.BITLY_ACCESS_TOKEN}</project.bitly-access-token>
</properties>
</profile>
</profiles>
<build>
@@ -90,62 +71,39 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>maven-replacer-plugin</artifactId>
<version>1.4.1</version>
<version>1.3.8</version>
<executions>
<execution>
<id>replace-bitly-access-token</id>
<phase>generate-sources</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<basedir>${project.build.sourceDirectory}</basedir>
<includes>
<include>com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java</include>
</includes>
<replacements>
<replacement>
<token>bitly-access-token</token>
<value>${project.bitly-access-token}</value>
</replacement>
</replacements>
</configuration>
</execution>
<execution>
<id>replace-maven-version-number</id>
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<basedir>${project.build.directory}/classes</basedir>
<includes>
<include>plugin.yml</include>
</includes>
<replacements>
<replacement>
<token>maven-version-number</token>
<value>${project.version}-b${project.build.number}</value>
</replacement>
</replacements>
</configuration>
</execution>
</executions>
<configuration>
<file>target/classes/plugin.yml</file>
<replacements>
<replacement>
<token>maven-version-number</token>
<value>${project.version}-b${project.build.number}</value>
</replacement>
</replacements>
</configuration>
</plugin>
<!-- Jar Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<version>2.3.1</version>
<configuration>
<archive>
<manifestEntries>
@@ -156,7 +114,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<version>2.11</version>
<configuration>
<parallel>methods</parallel>
<threadCount>10</threadCount>
@@ -169,14 +127,14 @@
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>3.0.0-M3</version>
<version>2.11</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.17</version>
<version>2.10</version>
<configuration>
<enableRulesSummary>true</enableRulesSummary>
<configLocation>${project.basedir}/config/mv_checks.xml</configLocation>
@@ -185,7 +143,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<version>2.1.2</version>
<executions>
<execution>
<id>attach-sources</id>
@@ -198,7 +156,7 @@
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<version>2.8.1</version>
<executions>
<execution>
<id>javadoc-jar</id>
@@ -206,16 +164,13 @@
<goals>
<goal>jar</goal>
</goals>
<configuration>
<failOnError>false</failOnError>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<version>1.5</version>
<executions>
<execution>
<phase>package</phase>
@@ -223,22 +178,36 @@
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>me.main__.util:SerializationConfig</include>
<include>com.pneumaticraft.commandhandler:CommandHandler</include>
<include>com.dumptruckman.minecraft:buscript</include>
<include>org.mcstats:metrics</include>
<include>com.dumptruckman.minecraft:Logging</include>
<include>com.fernferret.allpay:AllPay</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>com.fernferret.allpay</pattern>
<shadedPattern>com.fernferret.allpay.multiverse</shadedPattern>
</relocation>
<relocation>
<pattern>me.main__.util</pattern>
<shadedPattern>com.onarandombox.serializationconfig</shadedPattern>
<shadedPattern>me.main__.util.multiverse</shadedPattern>
</relocation>
<relocation>
<pattern>com.pneumaticraft.commandhandler</pattern>
<shadedPattern>com.onarandombox.commandhandler</shadedPattern>
<shadedPattern>com.pneumaticraft.commandhandler.multiverse</shadedPattern>
</relocation>
<relocation>
<pattern>buscript</pattern>
<shadedPattern>com.onarandombox.buscript</shadedPattern>
<shadedPattern>buscript.multiverse</shadedPattern>
</relocation>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>com.onarandombox.bstats</shadedPattern>
<pattern>org.mcstats</pattern>
<shadedPattern>org.mcstats.multiverse</shadedPattern>
</relocation>
<relocation>
<pattern>com.dumptruckman.minecraft.util.Logging</pattern>
@@ -248,34 +217,28 @@
<pattern>com.dumptruckman.minecraft.util.DebugLog</pattern>
<shadedPattern>com.onarandombox.MultiverseCore.utils.DebugFileLogger</shadedPattern>
</relocation>
<relocation>
<pattern>org.codehaus.jettison</pattern>
<shadedPattern>com.onarandombox.jettison</shadedPattern>
</relocation>
<relocation>
<pattern>de.themoep.idconverter</pattern>
<shadedPattern>com.onarandombox.idconverter</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>se.eris</groupId>
<artifactId>notnull-instrumenter-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<id>apache-commons-io</id>
<phase>package</phase>
<goals>
<goal>instrument</goal>
<goal>tests-instrument</goal>
<goal>shade</goal>
</goals>
<configuration>
<notNull>
<param>org.jetbrains.annotations.NotNull</param>
<param>javax.validation.constraints.NotNull</param>
</notNull>
<artifactSet>
<includes>
<include>org.apache.commons:commons-io</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>org.apache.commons</pattern>
<shadedPattern>org.apache.commons.multiverse</shadedPattern>
</relocation>
</relocations>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
@@ -285,119 +248,130 @@
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.13.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Bukkit Dependency -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.5-R0.2</version>
<!-- If you want the lates, use this -->
<!-- <version>LATEST</version> -->
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Bukkit Dependency -->
<!-- Start of Spout (disabled because we aren't using it)
<dependency>
<groupId>org.getspout</groupId>
<artifactId>spoutpluginapi</artifactId>
<version>dev-SNAPSHOT</version>
</dependency>
End of Spout -->
<!-- SerializationConfig Dependency -->
<dependency>
<groupId>me.main__.util</groupId>
<artifactId>SerializationConfig</artifactId>
<version>1.7</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of SerializationConfig Dependency -->
<!-- Start of Economy Dependency -->
<dependency>
<groupId>com.fernferret.allpay</groupId>
<artifactId>AllPay</artifactId>
<version>13</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
<artifactId>Vault</artifactId>
<version>1.2.20</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of Economy Dependency -->
<!-- Start of CommandHandler Dependency -->
<dependency>
<groupId>com.pneumaticraft.commandhandler</groupId>
<artifactId>CommandHandler</artifactId>
<version>11</version>
<version>7</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of CommandHandler Dependency -->
<!-- Start of Buscript Dependency -->
<dependency>
<groupId>com.dumptruckman.minecraft</groupId>
<artifactId>buscript</artifactId>
<version>2.0-SNAPSHOT</version>
<version>1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of Buscript Dependency -->
<!-- Start of Metrics Dependency -->
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.8</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
<groupId>org.mcstats</groupId>
<artifactId>metrics</artifactId>
<version>1.2-SNAPSHOT</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of Metrics Dependency -->
<!-- Start of Logging Dependency -->
<dependency>
<groupId>com.dumptruckman.minecraft</groupId>
<artifactId>Logging</artifactId>
<version>1.1.1</version>
<version>1.0.9</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>16.0.2</version>
</dependency>
<dependency>
<groupId>de.themoep.idconverter</groupId>
<artifactId>mappings</artifactId>
<version>1.2-SNAPSHOT</version>
</dependency>
<!-- End of Logging Dependency -->
<!-- Start of Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
<version>4.8.2</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
<version>1.4.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>2.0.9</version>
<version>1.4.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.9</version>
<artifactId>powermock-api-mockito</artifactId>
<version>1.4.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>4.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
<version>3.0</version>
<scope>test</scope>
</dependency>
<!-- End of Test Dependencies -->
</dependencies>
<distributionManagement>
<repository>
<id>OnARandomBox</id>
<url>http://repo.onarandombox.com/content/repositories/multiverse</url>
</repository>
<snapshotRepository>
<id>OnARandomBox</id>
<url>http://repo.onarandombox.com/content/repositories/multiverse-snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
@@ -12,7 +12,6 @@ import com.onarandombox.MultiverseCore.api.BlockSafety;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.configuration.SpawnLocation;
import com.onarandombox.MultiverseCore.configuration.SpawnSettings;
import com.onarandombox.MultiverseCore.configuration.WorldPropertyValidator;
import com.onarandombox.MultiverseCore.enums.AllowedPortalType;
import com.onarandombox.MultiverseCore.enums.EnglishChatColor;
@@ -24,7 +23,6 @@ import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldType;
@@ -34,7 +32,6 @@ import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.Nullable;
import org.json.simple.JSONObject;
import java.util.Collections;
@@ -187,22 +184,14 @@ public class MVWorld implements MultiverseWorld {
//this.props.validate();
}
/**
* This method is here to provide a stopgap until the add/remove/clear methods are implemented with
* SerializationConfig.
*/
public void validateEntitySpawns() {
setAllowAnimalSpawn(canAnimalsSpawn());
setAllowMonsterSpawn(canMonstersSpawn());
}
private void validateProperties() {
setPVPMode(isPVPEnabled());
setDifficulty(getDifficulty());
setKeepSpawnInMemory(isKeepingSpawnInMemory());
setScaling(getScaling());
setRespawnToWorld(this.props.getRespawnToWorld());
validateEntitySpawns();
setAllowAnimalSpawn(canAnimalsSpawn());
setAllowMonsterSpawn(canMonstersSpawn());
setGameMode(getGameMode());
}
@@ -214,7 +203,7 @@ public class MVWorld implements MultiverseWorld {
public Double validateChange(String property, Double newValue, Double oldValue,
MVWorld object) throws ChangeDeniedException {
if (newValue <= 0) {
Logging.fine("Someone tried to set a scale <= 0, aborting!");
plugin.log(Level.FINE, "Someone tried to set a scale <= 0, aborting!");
throw new ChangeDeniedException();
}
return super.validateChange(property, newValue, oldValue, object);
@@ -257,10 +246,10 @@ public class MVWorld implements MultiverseWorld {
/**
* Used to apply the spawning-property.
*/
private final class SpawningPropertyValidator extends WorldPropertyValidator<SpawnSettings> {
private final class SpawningPropertyValidator extends WorldPropertyValidator<Boolean> {
@Override
public SpawnSettings validateChange(String property, SpawnSettings newValue, SpawnSettings oldValue,
MVWorld object) throws ChangeDeniedException {
public Boolean validateChange(String property, Boolean newValue, Boolean oldValue,
MVWorld object) throws ChangeDeniedException {
boolean allowMonsters, allowAnimals;
if (getAnimalList().isEmpty()) {
allowAnimals = canAnimalsSpawn();
@@ -282,9 +271,7 @@ public class MVWorld implements MultiverseWorld {
}
world.setSpawnFlags(allowMonsters, allowAnimals);
}
if (MultiverseCoreConfiguration.getInstance().isAutoPurgeEnabled()) {
plugin.getMVWorldManager().getTheWorldPurger().purgeWorld(MVWorld.this);
}
plugin.getMVWorldManager().getTheWorldPurger().purgeWorld(MVWorld.this);
return super.validateChange(property, newValue, oldValue, object);
}
}
@@ -297,7 +284,7 @@ public class MVWorld implements MultiverseWorld {
public GameMode validateChange(String property, GameMode newValue, GameMode oldValue,
MVWorld object) throws ChangeDeniedException {
for (Player p : plugin.getServer().getWorld(getName()).getPlayers()) {
Logging.finer(String.format("Setting %s's GameMode to %s",
plugin.log(Level.FINER, String.format("Setting %s's GameMode to %s",
p.getName(), newValue.toString()));
plugin.getPlayerListener().handleGameModeAndFlight(p, MVWorld.this);
}
@@ -319,16 +306,16 @@ public class MVWorld implements MultiverseWorld {
// verify that the location is safe
if (!bs.playerCanSpawnHereSafely(newValue)) {
// it's not ==> find a better one!
Logging.warning(String.format("Somebody tried to set the spawn location for '%s' to an unsafe value! Adjusting...", getAlias()));
Logging.warning("Old Location: " + plugin.getLocationManipulation().strCoordsRaw(oldValue));
Logging.warning("New (unsafe) Location: " + plugin.getLocationManipulation().strCoordsRaw(newValue));
plugin.log(Level.WARNING, String.format("Somebody tried to set the spawn location for '%s' to an unsafe value! Adjusting...", getAlias()));
plugin.log(Level.WARNING, "Old Location: " + plugin.getLocationManipulation().strCoordsRaw(oldValue));
plugin.log(Level.WARNING, "New (unsafe) Location: " + plugin.getLocationManipulation().strCoordsRaw(newValue));
SafeTTeleporter teleporter = plugin.getSafeTTeleporter();
newValue = teleporter.getSafeLocation(newValue, SPAWN_LOCATION_SEARCH_TOLERANCE, SPAWN_LOCATION_SEARCH_RADIUS);
if (newValue == null) {
Logging.warning("Couldn't fix the location. I have to abort the spawn location-change :/");
plugin.log(Level.WARNING, "Couldn't fix the location. I have to abort the spawn location-change :/");
throw new ChangeDeniedException();
}
Logging.warning("New (safe) Location: " + plugin.getLocationManipulation().strCoordsRaw(newValue));
plugin.log(Level.WARNING, "New (safe) Location: " + plugin.getLocationManipulation().strCoordsRaw(newValue));
}
}
return super.validateChange(property, newValue, oldValue, object);
@@ -411,7 +398,7 @@ public class MVWorld implements MultiverseWorld {
// Add limit bypass to it's parent
this.limitbypassperm.addParent("mv.bypass.playerlimit.*", true);
} catch (IllegalArgumentException e) {
Logging.finer("Permissions nodes were already added for " + this.name);
this.plugin.log(Level.FINER, "Permissions nodes were already added for " + this.name);
}
}
@@ -422,16 +409,16 @@ public class MVWorld implements MultiverseWorld {
// Verify that location was safe
if (!bs.playerCanSpawnHereSafely(location)) {
if (!this.getAdjustSpawn()) {
Logging.fine("Spawn location from world.dat file was unsafe!!");
Logging.fine("NOT adjusting spawn for '" + this.getAlias() + "' because you told me not to.");
Logging.fine("To turn on spawn adjustment for this world simply type:");
Logging.fine("/mvm set adjustspawn true " + this.getAlias());
this.plugin.log(Level.FINE, "Spawn location from world.dat file was unsafe!!");
this.plugin.log(Level.FINE, "NOT adjusting spawn for '" + this.getAlias() + "' because you told me not to.");
this.plugin.log(Level.FINE, "To turn on spawn adjustment for this world simply type:");
this.plugin.log(Level.FINE, "/mvm set adjustspawn true " + this.getAlias());
return location;
}
// If it's not, find a better one.
SafeTTeleporter teleporter = this.plugin.getSafeTTeleporter();
Logging.warning("Spawn location from world.dat file was unsafe. Adjusting...");
Logging.warning("Original Location: " + plugin.getLocationManipulation().strCoordsRaw(location));
this.plugin.log(Level.WARNING, "Spawn location from world.dat file was unsafe. Adjusting...");
this.plugin.log(Level.WARNING, "Original Location: " + plugin.getLocationManipulation().strCoordsRaw(location));
Location newSpawn = teleporter.getSafeLocation(location,
SPAWN_LOCATION_SEARCH_TOLERANCE, SPAWN_LOCATION_SEARCH_RADIUS);
// I think we could also do this, as I think this is what Notch does.
@@ -450,7 +437,7 @@ public class MVWorld implements MultiverseWorld {
this.getName(), plugin.getLocationManipulation().locationToString(newerSpawn));
return newerSpawn;
} else {
Logging.severe("Safe spawn NOT found!!!");
this.plugin.log(Level.SEVERE, "Safe spawn NOT found!!!");
}
}
}
@@ -555,7 +542,6 @@ public class MVWorld implements MultiverseWorld {
if (list == null)
return false;
list.clear();
validateEntitySpawns();
return true;
}
@@ -571,7 +557,6 @@ public class MVWorld implements MultiverseWorld {
if (list == null)
return false;
list.add(value);
validateEntitySpawns();
return true;
}
@@ -587,7 +572,6 @@ public class MVWorld implements MultiverseWorld {
if (list == null)
return false;
list.remove(value);
validateEntitySpawns();
return true;
}
@@ -605,6 +589,29 @@ public class MVWorld implements MultiverseWorld {
return null;
}
/**
* {@inheritDoc}
*
* @deprecated This is deprecated.
*/
@Override
@Deprecated
public <T> com.onarandombox.MultiverseCore.configuration.MVConfigProperty<T> getProperty(String property,
Class<T> expected) throws PropertyDoesNotExistException {
throw new UnsupportedOperationException("'MVConfigProperty<T> getProperty(String,Class<T>)' is no longer supported!");
}
/**
* {@inheritDoc}
*
* @deprecated This is deprecated.
*/
@Override
@Deprecated
public boolean setProperty(String name, String value, CommandSender sender) throws PropertyDoesNotExistException {
return this.setPropertyValue(name, value);
}
/**
* {@inheritDoc}
*/
@@ -924,7 +931,7 @@ public class MVWorld implements MultiverseWorld {
* {@inheritDoc}
*/
@Override
public Material getCurrency() {
public int getCurrency() {
return this.props.getCurrency();
}
@@ -932,7 +939,7 @@ public class MVWorld implements MultiverseWorld {
* {@inheritDoc}
*/
@Override
public void setCurrency(@Nullable Material currency) {
public void setCurrency(int currency) {
this.props.setCurrency(currency);
}
@@ -7,23 +7,10 @@
package com.onarandombox.MultiverseCore;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import buscript.Buscript;
import com.dumptruckman.minecraft.util.Logging;
import com.fernferret.allpay.AllPay;
import com.fernferret.allpay.commons.GenericBank;
import com.onarandombox.MultiverseCore.MVWorld.NullLocation;
import com.onarandombox.MultiverseCore.api.BlockSafety;
import com.onarandombox.MultiverseCore.api.Core;
@@ -32,6 +19,7 @@ import com.onarandombox.MultiverseCore.api.MVPlugin;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseCoreConfig;
import com.onarandombox.MultiverseCore.api.MultiverseMessaging;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.commands.AnchorCommand;
import com.onarandombox.MultiverseCore.commands.CheckCommand;
@@ -75,29 +63,20 @@ import com.onarandombox.MultiverseCore.destination.DestinationFactory;
import com.onarandombox.MultiverseCore.destination.ExactDestination;
import com.onarandombox.MultiverseCore.destination.PlayerDestination;
import com.onarandombox.MultiverseCore.destination.WorldDestination;
import com.onarandombox.MultiverseCore.event.MVDebugModeEvent;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
import com.onarandombox.MultiverseCore.generators.GeneratorManager;
import com.onarandombox.MultiverseCore.api.MVGeneratorManager;
import com.onarandombox.MultiverseCore.listeners.MVAsyncPlayerChatListener;
import com.onarandombox.MultiverseCore.listeners.MVChatListener;
import com.onarandombox.MultiverseCore.listeners.MVEntityListener;
import com.onarandombox.MultiverseCore.listeners.MVMapListener;
import com.onarandombox.MultiverseCore.listeners.MVPlayerChatListener;
import com.onarandombox.MultiverseCore.listeners.MVPlayerListener;
import com.onarandombox.MultiverseCore.listeners.MVPluginListener;
import com.onarandombox.MultiverseCore.listeners.MVPortalListener;
import com.onarandombox.MultiverseCore.listeners.MVWeatherListener;
import com.onarandombox.MultiverseCore.listeners.MVWorldInitListener;
import com.onarandombox.MultiverseCore.listeners.MVWorldListener;
import com.onarandombox.MultiverseCore.utils.AnchorManager;
import com.onarandombox.MultiverseCore.utils.CompatibilityLayer;
import com.onarandombox.MultiverseCore.utils.MVEconomist;
import com.onarandombox.MultiverseCore.utils.MVMessaging;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import com.onarandombox.MultiverseCore.utils.MVPlayerSession;
import com.onarandombox.MultiverseCore.utils.MaterialConverter;
import com.onarandombox.MultiverseCore.utils.TestingMode;
import com.onarandombox.MultiverseCore.utils.metrics.MetricsConfigurator;
import com.onarandombox.MultiverseCore.utils.SimpleBlockSafety;
import com.onarandombox.MultiverseCore.utils.SimpleLocationManipulation;
import com.onarandombox.MultiverseCore.utils.SimpleSafeTTeleporter;
@@ -111,24 +90,36 @@ import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World.Environment;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.mcstats.Metrics;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
/**
* The implementation of the Multiverse-{@link Core}.
*/
public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
private static final int PROTOCOL = 24;
private static final int PROTOCOL = 18;
// TODO: Investigate if this one is really needed to be static.
// Doubt it. -- FernFerret
private static Map<String, String> teleportQueue = new HashMap<String, String>();
@@ -137,21 +128,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// TODO please let's make this non-static
private volatile MultiverseCoreConfiguration config;
public MultiverseCore() {
super();
}
/**
* This is for unit testing.
* @param loader The PluginLoader to use.
* @param description The Description file to use.
* @param dataFolder The folder that other datafiles can be found in.
* @param file The location of the plugin.
*/
public MultiverseCore(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file);
}
/**
* This method is used to find out who is teleporting a player.
* @param playerName The teleported player (the teleportee).
@@ -177,6 +153,11 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
teleportQueue.put(teleportee, teleporter);
}
@Override
public String toString() {
return "The Multiverse-Core Plugin";
}
/**
* {@inheritDoc}
* @deprecated This is now deprecated, nobody needs it any longer.
@@ -215,23 +196,25 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Configurations
private FileConfiguration multiverseConfig = null;
private MVGeneratorManager generatorManager;
private final MVWorldManager worldManager = new WorldManager(this);
// Setup the block/player/entity listener.
private final MVPlayerListener playerListener = new MVPlayerListener(this);
private final MVEntityListener entityListener = new MVEntityListener(this);
private final MVPluginListener pluginListener = new MVPluginListener(this);
private final MVWeatherListener weatherListener = new MVWeatherListener(this);
private final MVPortalListener portalListener = new MVPortalListener(this);
private final MVWorldListener worldListener = new MVWorldListener(this);
private MVChatListener chatListener;
// HashMap to contain information relating to the Players.
private HashMap<String, MVPlayerSession> playerSessions;
private MVEconomist economist;
private VaultHandler vaultHandler;
private GenericBank bank = null;
private AllPay banker;
private Buscript buscript;
private int pluginCount;
private DestinationFactory destFactory;
//private SpoutInterface spoutInterface = null;
private MultiverseMessaging messaging;
private BlockSafety blockSafety;
private LocationManipulation locationManipulation;
@@ -258,19 +241,21 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Setup our SafeTTeleporter
this.safeTTeleporter = new SimpleSafeTTeleporter(this);
this.unsafeCallWrapper = new UnsafeCallWrapper(this);
// Setup our CompatibilityLayer
CompatibilityLayer.init();
}
/**
* {@inheritDoc}
* @deprecated Now using Vault.
*/
@Override
@Deprecated
public VaultHandler getVaultHandler() {
return getEconomist().getVaultHandler();
public GenericBank getBank() {
return this.bank;
}
public MVEconomist getEconomist() {
return economist;
@Override
public VaultHandler getVaultHandler() {
return vaultHandler;
}
/**
@@ -278,17 +263,18 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*/
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(new MVWorldInitListener(this), this);
this.messaging = new MVMessaging();
this.economist = new MVEconomist(this);
this.banker = new AllPay(this, LOG_TAG + " ");
this.vaultHandler = new VaultHandler(this);
// Load the defaultWorldGenerators
this.generatorManager = new GeneratorManager(this);
this.worldManager.getDefaultWorldGenerators();
this.registerEvents();
// Setup Permissions, we'll do an initial check for the Permissions plugin then fall back on isOP().
this.ph = new MVPermissions(this);
this.bank = this.banker.loadEconPlugin();
// Setup the command manager
this.commandHandler = new CommandHandler(this, this.ph);
// Call the Function to assign all the Commands to their Class.
@@ -308,11 +294,12 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Setup & Load our Configuration files.
loadConfigs();
if (this.multiverseConfig != null) {
Logging.setDebugLevel(getMVConfig().getGlobalDebug());
Logging.setShowingConfig(!getMVConfig().getSilentStart());
this.worldManager.loadDefaultWorlds();
this.worldManager.loadWorlds(true);
} else {
Logging.severe("Your configs were not loaded. Very little will function in Multiverse.");
this.log(Level.SEVERE, "Your configs were not loaded. Very little will function in Multiverse.");
}
this.anchorManager.loadAnchors();
@@ -336,39 +323,118 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.chatListener = new MVPlayerChatListener(this, this.playerListener);
}
getServer().getPluginManager().registerEvents(this.chatListener, this);
/*
// Check to see if spout was already loaded (most likely):
if (this.getServer().getPluginManager().getPlugin("Spout") != null) {
this.setSpout();
this.log(Level.INFO, "Spout integration enabled.");
}
*/
this.initializeBuscript();
this.setupMetrics();
// Output a little snippet to show it's enabled.
Logging.config("Version %s (API v%s) Enabled - By %s", this.getDescription().getVersion(), PROTOCOL, getAuthors());
if (getMVConfig().isShowingDonateMessage()) {
getLogger().config("Help dumptruckman keep this project alive. Become a patron! https://www.patreon.com/dumptruckman");
getLogger().config("One time donations are also appreciated: https://www.paypal.me/dumptruckman");
}
}
private void setupMetrics() {
if (TestingMode.isDisabled()) {
MetricsConfigurator.configureMetrics(this);
}
}
/**
* Initializes the buscript javascript library.
*/
private void initializeBuscript() {
buscript = null;
buscript = new Buscript(this);
// Add global variable "multiverse" to javascript environment
buscript.getGlobalScope().put("multiverse", buscript.getGlobalScope(), this);
}
if (this.getMVConfig().getEnableBuscript()) {
try {
buscript = new Buscript(this);
// Add global variable "multiverse" to javascript environment
buscript.setScriptVariable("multiverse", this);
} catch (NullPointerException e) {
Logging.warning("Buscript failed to load! The script command will be disabled!");
}
/**
* Plotter for Environment-Values.
*/
private static final class EnvironmentPlotter extends Metrics.Plotter {
private MultiverseCore core;
private final Environment env;
public EnvironmentPlotter(MultiverseCore core, Environment env) {
super(envToString(env));
this.core = core;
this.env = env;
}
private static String envToString(Environment env) {
return new StringBuilder().append(env.name().toUpperCase().charAt(0))
.append(env.name().toLowerCase().substring(1)).toString();
}
@Override
public int getValue() {
int count = 0;
for (MultiverseWorld w : core.getMVWorldManager().getMVWorlds())
if (w.getEnvironment() == env)
count++;
core.log(Level.FINE, String.format("Tracking %d worlds of type %s", count, env));
return count;
}
}
/**
* Plotter for Generator-Values.
*/
private static final class GeneratorPlotter extends Metrics.Plotter {
private MultiverseCore core;
private final String gen;
public GeneratorPlotter(MultiverseCore core, String gen) {
super(gen);
this.core = core;
this.gen = gen;
}
@Override
public int getValue() {
int count = 0;
for (MultiverseWorld w : core.getMVWorldManager().getMVWorlds())
if (gen.equals(w.getGenerator()))
count++;
core.log(Level.FINE, String.format("Tracking %d worlds of type %s", count, gen));
return count;
}
}
private void setupMetrics() {
try {
Metrics m = new Metrics(this);
Metrics.Graph envGraph = m.createGraph("worlds_by_env");
for (Environment env : Environment.values())
envGraph.addPlotter(new EnvironmentPlotter(this, env));
m.addCustomData(new Metrics.Plotter("Loaded worlds") {
@Override
public int getValue() {
return getMVWorldManager().getMVWorlds().size();
}
});
m.addCustomData(new Metrics.Plotter("Total number of worlds") {
@Override
public int getValue() {
return getMVWorldManager().getMVWorlds().size()
+ getMVWorldManager().getUnloadedWorlds().size();
}
});
Set<String> gens = new HashSet<String>();
for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds())
gens.add(w.getGenerator());
gens.remove(null);
gens.remove("null");
Metrics.Graph genGraph = m.createGraph("custom_gens");
for (String gen : gens)
genGraph.addPlotter(new GeneratorPlotter(this, gen));
m.start();
log(Level.FINE, "Metrics have run!");
} catch (IOException e) {
log(Level.WARNING, "There was an issue while enabling metrics: " + e.getMessage());
}
}
@@ -390,10 +456,9 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(this.playerListener, this);
pm.registerEvents(this.entityListener, this);
pm.registerEvents(this.pluginListener, this);
pm.registerEvents(this.weatherListener, this);
pm.registerEvents(this.portalListener, this);
Logging.info(ChatColor.GREEN + "We are aware of the warning about the deprecated event. There is no alternative that allows us to do what we need to do and performance impact is negligible. It is safe to ignore.");
pm.registerEvents(this.worldListener, this);
pm.registerEvents(new MVMapListener(this), this);
}
@@ -404,19 +469,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
public void loadConfigs() {
// Now grab the Configuration Files.
this.multiverseConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "config.yml"));
InputStream resourceURL = this.getClass().getResourceAsStream("/defaults/config.yml");
// Read in our default config with UTF-8 now
Configuration coreDefaults;
try {
coreDefaults = YamlConfiguration.loadConfiguration(new BufferedReader(new InputStreamReader(resourceURL, "UTF-8")));
this.multiverseConfig.setDefaults(coreDefaults);
} catch (UnsupportedEncodingException e) {
Logging.severe("Couldn't load default config with UTF-8 encoding. Details follow:");
e.printStackTrace();
Logging.severe("Default configs NOT loaded.");
}
Configuration coreDefaults = YamlConfiguration.loadConfiguration(this.getClass().getResourceAsStream("/defaults/config.yml"));
this.multiverseConfig.setDefaults(coreDefaults);
this.multiverseConfig.options().copyDefaults(false);
this.multiverseConfig.options().copyHeader(true);
@@ -440,12 +494,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Old Config Format
this.migrate22Values();
this.saveMVConfigs();
int level = Logging.getDebugLevel();
Logging.setDebugLevel(getMVConfig().getGlobalDebug());
if (level != Logging.getDebugLevel()) {
getServer().getPluginManager().callEvent(new MVDebugModeEvent(level));
}
}
/**
@@ -499,25 +547,15 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
}
}
private static final char PATH_SEPARATOR = '\uF8FF';
/**
* Migrate the worlds.yml to SerializationConfig.
*/
private void migrateWorldConfig() { // SUPPRESS CHECKSTYLE: MethodLength
FileConfiguration wconf = new YamlConfiguration();
wconf.options().pathSeparator(PATH_SEPARATOR);
File worldsFile = new File(getDataFolder(), "worlds.yml");
try {
wconf.load(worldsFile);
} catch (IOException e) {
Logging.warning("Cannot load worlds.yml");
} catch (InvalidConfigurationException e) {
Logging.warning("Your worlds.yml is invalid!");
}
FileConfiguration wconf = YamlConfiguration
.loadConfiguration(new File(getDataFolder(), "worlds.yml"));
if (!wconf.isConfigurationSection("worlds")) { // empty config
Logging.fine("No worlds to migrate!");
this.log(Level.FINE, "No worlds to migrate!");
return;
}
@@ -530,7 +568,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// fine
newValues.put(entry.getKey(), entry.getValue());
} else if (entry.getValue() instanceof ConfigurationSection) {
Logging.fine("Migrating: " + entry.getKey());
this.log(Level.FINE, "Migrating: " + entry.getKey());
// we have to migrate this
WorldProperties world = new WorldProperties(Collections.EMPTY_MAP);
ConfigurationSection section = (ConfigurationSection) entry.getValue();
@@ -566,9 +604,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// migrate entryfee
if (section.isConfigurationSection("entryfee")) {
ConfigurationSection feeSection = section.getConfigurationSection("entryfee");
if (feeSection.isInt("currency")) {
world.setCurrency(MaterialConverter.convertConfigType(feeSection, "currency"));
}
if (feeSection.isInt("currency"))
world.setCurrency(feeSection.getInt("currency"));
if (feeSection.isDouble("amount"))
world.setPrice(feeSection.getDouble("amount"));
@@ -692,14 +729,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// migrate difficulty
if (section.isString("difficulty")) {
Difficulty difficulty;
try {
difficulty = Difficulty.valueOf(section.getString("difficulty").toUpperCase());
} catch (IllegalArgumentException e) {
Logging.warning("Could not parse difficulty: " + section.getString("difficulty"));
Logging.warning("Setting world " + entry.getKey() + " difficulty to NORMAL");
difficulty = Difficulty.NORMAL;
}
final Difficulty difficulty = Difficulty.valueOf(section.getString("difficulty").toUpperCase());
if (difficulty != null) {
world.setDifficulty(difficulty);
}
@@ -714,7 +744,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
wasChanged = true;
} else {
// huh?
Logging.warning("Removing unknown entry in the config: " + entry);
this.log(Level.WARNING, "Removing unknown entry in the config: " + entry);
// just don't add to newValues
wasChanged = true;
}
@@ -798,6 +828,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
@Override
public void onDisable() {
this.saveMVConfigs();
this.banker = null;
this.bank = null;
Logging.shutdown();
}
@@ -814,6 +846,17 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
}
}
/**
* {@inheritDoc}
*
* @deprecated This is deprecated.
*/
@Override
@Deprecated
public com.onarandombox.MultiverseCore.utils.SafeTTeleporter getTeleporter() {
return new com.onarandombox.MultiverseCore.utils.SafeTTeleporter(this);
}
/**
* {@inheritDoc}
*/
@@ -848,12 +891,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
/**
* {@inheritDoc}
*
* @deprecated This is now deprecated, nobody needs it any longer.
* All logging is now done with {@link Logging}.
*/
@Override
@Deprecated
public void log(Level level, String msg) {
Logging.log(level, msg);
}
@@ -976,6 +1015,26 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.pluginCount -= 1;
}
/**
* {@inheritDoc}
* @deprecated Now using Vault.
*/
@Override
@Deprecated
public AllPay getBanker() {
return this.banker;
}
/**
* {@inheritDoc}
* @deprecated Now using Vault.
*/
@Override
@Deprecated
public void setBank(GenericBank bank) {
this.bank = bank;
}
/**
* {@inheritDoc}
*/
@@ -1017,14 +1076,25 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.serverFolder = newServerFolder;
}
/*
/**
* {@inheritDoc}
*/
@Override
public MVGeneratorManager getMVGeneratorManager() {
return generatorManager;
* Initializes Spout.
* /
public void setSpout() {
this.spoutInterface = new SpoutInterface();
this.commandHandler.registerCommand(new SpoutCommand(this));
}
/**
* Gets our {@link SpoutInterface}.
*
* @return The {@link SpoutInterface} we're using.
* /
public SpoutInterface getSpout() {
return this.spoutInterface;
}
*/
/**
* {@inheritDoc}
*/
@@ -1080,7 +1150,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.multiverseConfig.save(new File(getDataFolder(), "config.yml"));
return true;
} catch (IOException e) {
Logging.severe("Could not save Multiverse config.yml config. Please check your file permissions.");
this.log(Level.SEVERE, "Could not save Multiverse config.yml config. Please check your file permissions.");
return false;
}
}
@@ -1,14 +1,10 @@
package com.onarandombox.MultiverseCore;
import java.util.Map;
import com.dumptruckman.minecraft.util.*;
import com.onarandombox.MultiverseCore.api.*;
import me.main__.util.SerializationConfig.*;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.api.MultiverseCoreConfig;
import com.onarandombox.MultiverseCore.event.MVDebugModeEvent;
import me.main__.util.SerializationConfig.NoSuchPropertyException;
import me.main__.util.SerializationConfig.Property;
import me.main__.util.SerializationConfig.SerializationConfig;
import org.bukkit.Bukkit;
import java.util.*;
/**
* Our configuration.
@@ -46,8 +42,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
@Property
private volatile boolean prefixchat;
@Property
private volatile String prefixchatformat;
@Property
private volatile boolean useasyncchat;
@Property
private volatile boolean teleportintercept;
@@ -56,8 +50,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
@Property
private volatile boolean displaypermerrors;
@Property
private volatile boolean enablebuscript;
@Property
private volatile int globaldebug;
@Property
private volatile boolean silentstart;
@@ -73,10 +65,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
private volatile boolean defaultportalsearch;
@Property
private volatile int portalsearchradius;
@Property
private volatile boolean autopurge;
@Property
private volatile boolean idonotwanttodonate;
public MultiverseCoreConfiguration() {
super();
@@ -97,11 +85,9 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
enforceaccess = false;
useasyncchat = true;
prefixchat = true;
prefixchatformat = "[%world%]%chat%";
teleportintercept = true;
firstspawnoverride = true;
displaypermerrors = true;
enablebuscript = true;
globaldebug = 0;
messagecooldown = 5000;
teleportcooldown = 1000;
@@ -109,8 +95,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
silentstart = false;
defaultportalsearch = false;
portalsearchradius = 128;
autopurge = true;
idonotwanttodonate = false;
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
}
@@ -159,22 +143,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
public void setPrefixChat(boolean prefixChat) {
this.prefixchat = prefixChat;
}
/**
* {@inheritDoc}
*/
@Override
public String getPrefixChatFormat() {
return this.prefixchatformat;
}
/**
* {@inheritDoc}
*/
@Override
public void setPrefixChatFormat(String prefixChatFormat) {
this.prefixchatformat = prefixChatFormat;
}
/**
* {@inheritDoc}
@@ -216,22 +184,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
return this.displaypermerrors;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getEnableBuscript() {
return this.enablebuscript;
}
/**
* {@inheritDoc}
*/
@Override
public void setEnableBuscript(boolean enableBuscript) {
this.enablebuscript = enableBuscript;
}
/**
* {@inheritDoc}
*/
@@ -255,7 +207,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
public void setGlobalDebug(int globalDebug) {
this.globaldebug = globalDebug;
Logging.setDebugLevel(globalDebug);
Bukkit.getPluginManager().callEvent(new MVDebugModeEvent(globalDebug));
}
/**
@@ -362,24 +313,4 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
public int getPortalSearchRadius() {
return portalsearchradius;
}
@Override
public boolean isAutoPurgeEnabled() {
return autopurge;
}
@Override
public void setAutoPurgeEnabled(boolean autopurge) {
this.autopurge = autopurge;
}
@Override
public boolean isShowingDonateMessage() {
return !idonotwanttodonate;
}
@Override
public void setShowDonateMessage(boolean showDonateMessage) {
this.idonotwanttodonate = !showDonateMessage;
}
}
@@ -18,10 +18,8 @@ import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World.Environment;
import org.bukkit.configuration.serialization.SerializableAs;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
@@ -43,9 +41,7 @@ public class WorldProperties extends SerializationConfig {
static {
PROPERTY_ALIASES = new HashMap<String, String>();
PROPERTY_ALIASES.put("curr", "entryfee.currency");
PROPERTY_ALIASES.put("currency", "entryfee.currency");
PROPERTY_ALIASES.put("price", "entryfee.amount");
PROPERTY_ALIASES.put("curr", "currency");
PROPERTY_ALIASES.put("scaling", "scale");
PROPERTY_ALIASES.put("aliascolor", "color");
PROPERTY_ALIASES.put("heal", "autoHeal");
@@ -66,17 +62,12 @@ public class WorldProperties extends SerializationConfig {
PROPERTY_ALIASES.put("allowfly", "allowFlight");
}
private final boolean keepSpawnFallback;
public WorldProperties(Map<String, Object> values) {
super(values);
Object keepSpawnObject = values.get("keepSpawnInMemory");
keepSpawnFallback = keepSpawnObject == null || Boolean.parseBoolean(keepSpawnObject.toString());
}
public WorldProperties() {
super();
keepSpawnFallback = true;
}
public WorldProperties(final boolean fixSpawn, final Environment environment) {
@@ -85,7 +76,6 @@ public class WorldProperties extends SerializationConfig {
this.adjustSpawn = false;
}
setScaling(getDefaultScale(environment));
keepSpawnFallback = true;
}
void setMVWorld(MVWorld world) {
@@ -263,7 +253,7 @@ public class WorldProperties extends SerializationConfig {
@Property(description = "Sorry, 'animals' must either be: true or false.")
private volatile SpawnSettings spawning;
@Property
volatile EntryFee entryfee;
private volatile EntryFee entryfee;
@Property(description = "Sorry, 'hunger' must either be: true or false.")
private volatile boolean hunger;
@Property(description = "Sorry, 'autoheal' must either be: true or false.")
@@ -376,7 +366,7 @@ public class WorldProperties extends SerializationConfig {
this.flushPendingVPropChanges();
}
public String getAlias() {
String getAlias() {
return this.alias;
}
@@ -498,11 +488,11 @@ public class WorldProperties extends SerializationConfig {
return this.setPropertyValueUnchecked("respawnWorld", respawnToWorld);
}
public Material getCurrency() {
public int getCurrency() {
return this.entryfee.getCurrency();
}
public void setCurrency(@Nullable Material currency) {
public void setCurrency(int currency) {
this.setPropertyValueUnchecked("entryfee.currency", currency);
}
@@ -535,14 +525,7 @@ public class WorldProperties extends SerializationConfig {
}
public boolean isKeepingSpawnInMemory() {
if (keepSpawnInMemory == null) {
return keepSpawnFallback;
}
try {
return this.keepSpawnInMemory.get();
} catch (IllegalStateException e) {
return keepSpawnFallback;
}
return this.keepSpawnInMemory.get();
}
public void setKeepSpawnInMemory(boolean value) {
@@ -8,9 +8,10 @@
package com.onarandombox.MultiverseCore.api;
import buscript.Buscript;
import com.fernferret.allpay.AllPay;
import com.fernferret.allpay.commons.GenericBank;
import com.onarandombox.MultiverseCore.destination.DestinationFactory;
import com.onarandombox.MultiverseCore.utils.AnchorManager;
import com.onarandombox.MultiverseCore.utils.MVEconomist;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import com.onarandombox.MultiverseCore.utils.MVPlayerSession;
import com.onarandombox.MultiverseCore.utils.SimpleBlockSafety;
@@ -27,24 +28,23 @@ import org.bukkit.entity.Player;
*/
public interface Core {
/**
* Gets the Banking system that Multiverse-Core has hooked into.
*
* @return A {@link GenericBank} that can be used for payments.
* @deprecated Now using vault, see {@link VaultHandler#getEconomy}
*/
@Deprecated
GenericBank getBank();
/**
* Returns the Vault handler used by Multiverse. The returned object will have all methods necessary for
* interfacing with Vault.
*
* @return the Vault handler for Multiverse.
* @deprecated we are now using {@link #getEconomist()} for all economy needs.
*/
@Deprecated
VaultHandler getVaultHandler();
/**
* Retrieves Multiverse's friendly economist. The economist can be used for dealing with economies without
* worrying about any of the messy details.
*
* @return the economy manager for Multiverse.
*/
MVEconomist getEconomist();
/**
* Reloads the Multiverse Configuration files:
* worlds.yml and config.yml.
@@ -70,6 +70,17 @@ public interface Core {
*/
MVPlayerSession getPlayerSession(Player player);
/**
* Gets the instantiated Safe-T-Teleporter for performing
* safe teleports.
*
* @return A non-null {@link SafeTTeleporter}.
*
* @deprecated Use {@link #getSafeTTeleporter()} instead.
*/
@Deprecated
com.onarandombox.MultiverseCore.utils.SafeTTeleporter getTeleporter();
/**
* Multiverse uses an advanced permissions setup, this object
* simplifies getting/setting permissions.
@@ -94,17 +105,10 @@ public interface Core {
*/
DestinationFactory getDestFactory();
/**
* Gets the class responsible for managing world generators plugins installed on the server.
*
* @return A valid {@link MVGeneratorManager}.
*/
MVGeneratorManager getMVGeneratorManager();
/**
* Gets the primary class responsible for managing Multiverse Worlds.
*
* @return {@link MVWorldManager}.
* @return {@link WorldManager}.
*/
MVWorldManager getMVWorldManager();
@@ -137,6 +141,24 @@ public interface Core {
@Deprecated
Boolean regenWorld(String name, Boolean useNewSeed, Boolean randomSeed, String seed);
/**
* Sets the {@link GenericBank}-Bank AllPay is using.
*
* @param bank The new {@link GenericBank}
* @deprecated Now using vault, see {@link VaultHandler#getEconomy}
*/
@Deprecated
void setBank(GenericBank bank);
/**
* Gets this plugin's {@link AllPay}-Banker.
*
* @return An {@link AllPay}-Banker
* @deprecated Now using vault, see {@link VaultHandler#getEconomy}
*/
@Deprecated
AllPay getBanker();
/**
* Decrements the number of plugins that have specifically hooked into core.
*/
@@ -1,101 +0,0 @@
package com.onarandombox.MultiverseCore.api;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* <p>A generator API for Multiverse.</p>
*
* <p>Any generator plugin can register themselves to Multiverse. This will provide Multiverse with addition
* information about your generator plugin such as generator id suggestions, example usages and link to more
* info on your generator plugin.</p>
*
* <p>To register your plugin, implement this class and see {@link MVGeneratorManager#register(GeneratorPlugin)}.</p>
*/
public interface GeneratorPlugin {
/**
* <p>Suggest possible generator ids. To be used in command tab-completion.</p>
*
* <p>These suggestions can be static without relying on currentIdInput, or dynamically changed based
* on the currentIdInput.</p>
*
* @param currentIdInput The current state user input. This may be null or empty if user has not started
* any input for generator id.
* @return Collection of suggested generator ids.
*/
@NotNull
Collection<String> suggestIds(@Nullable String currentIdInput);
/**
* <p>Gets a default or any valid {@link ChunkGenerator}.</p>
*
* <p>This is used on {@link MVGeneratorManager#register(GeneratorPlugin)} to prove to Multiverse that
* you are a valid generator plugin. If this returns null or throw an exception, your generator plugin
* will not be registered.</p>
*
* @return A {@link ChunkGenerator} if possible, else null.
* @throws Exception When an error occurs in getting {@link ChunkGenerator}.
*/
@Nullable
ChunkGenerator getDefaultChunkGenerator() throws Exception;
/**
* <p>Gets a chunk generator based on a world name and id specified.</p>
*
* <p>If this returns null or throw an exception, it will indicate to Multiverse that there is either an issue
* with your plugin, or the generator id given is invalid.</p>
*
* @param id Target generator id.
* @param worldName Target world name to use generator on.
* @return A {@link ChunkGenerator} if possible, else null.
* @throws Exception When an error occurs in getting a {@link ChunkGenerator}.
*/
@Nullable
ChunkGenerator getChunkGenerator(String id, String worldName) throws Exception;
/**
* <p>Gets command usages that users can try to generate a world with your generator plugin. Returning null means
* you do not wish to show any usage examples for your generator plugin.</p>
*
* <p>An example command: '/mv create myworld normal -g CoolGen:FunWorld'</p>
*
* <p>Notes on usage of this method:</p>
* <ul>
* <li>Feel free to have colors in your command usage, but not Multiverse won't parse color codes for you.</li>
* <li>Please include the starting slash '/' in your usage examples.</li>
* <li>We suggest keeping the usage to at most 5 examples.</li>
* <li>This should not be a full explanation on all your generator plugin, just basics usages to get people
* started. For full guide, you can use {@link #getInfoLink()} to direct users.</li>
* </ul>
*
* @return A collection of command usage examples.
*/
@Nullable
Collection<String> getExampleUsages();
/**
* <p>Gets a link with more information on your generator plugin. Returning null means you do not wish to link
* users to any website related to your generator plugin.</p>
*
* <p>An example info: 'Click on https://www.amazinggenerator.io ;)'</p>
*
* <p>Some suggested places you can link to are: spigot resource page, github repo or your own plugin site.</p>
*
* @return Link to more info on your generator plugin.
*/
@Nullable
String getInfoLink();
/**
* Gets the java plugin for this generator. In short, return your own generator plugin instance.
*
* @return The associated plugin for this generator.
*/
@NotNull
Plugin getPlugin();
}
@@ -7,17 +7,11 @@
package com.onarandombox.MultiverseCore.api;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.Server;
import java.util.logging.Level;
/**
* A simple API to require plugins to have a log method.
*
* @deprecated Replaced by {@link Logging}.
* */
@Deprecated
/** A simple API to require plugins to have a log method. */
public interface LoggablePlugin {
/**
* Logs a message at the specified level.
@@ -1,134 +0,0 @@
package com.onarandombox.MultiverseCore.api;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Map;
/**
* API for handling generator plugins installed on the user's server.
*/
public interface MVGeneratorManager {
/**
* Register a generator plugin.
*
* @param generatorPlugin The {@link GeneratorPlugin} to register.
* @return True if successfully registered, else false.
*/
boolean register(@NotNull GeneratorPlugin generatorPlugin);
/**
* Check if a given generator string is valid.
*
* @param genString The generator string to check on.
* @param worldName The target world name to generate on.
* @return True if valid, else false.
*/
boolean isValidGenerator(@NotNull String genString, @NotNull String worldName);
/**
* Check if a given generator string is valid with reason of failure with {@link TestResult}.
*
* @param genString The generator string to check on.
* @param worldName The target world name to generate on.
* @return Result of the validation.
*/
@NotNull
TestResult validateGenerator(@NotNull String genString, @NotNull String worldName);
/**
* Checks if a plugin is a registered generator plugin.
*
* @param genPlugin The plugin to check on.
* @return True if is valid, else false.
*/
boolean isGeneratorPlugin(@NotNull Plugin genPlugin);
/**
* Checks if a plugin is a registered generator plugin.
*
* @param pluginName The plugin name to check on.
* @return True if is valid, else false.
*/
boolean isGeneratorPlugin(@NotNull String pluginName);
/**
* Gets the {@link GeneratorPlugin} for a given plugin if present.
*
* @param genPlugin The plugin that is associated to a {@link GeneratorPlugin}.
* @return The {@link GeneratorPlugin} if present, else null.
*/
@Nullable
GeneratorPlugin getGeneratorPlugin(@NotNull Plugin genPlugin);
/**
* Gets the {@link GeneratorPlugin} for a given plugin if present.
*
* @param pluginName The plugin name that is associated to a {@link GeneratorPlugin}.
* @return The {@link GeneratorPlugin} if present, else null.
*/
@Nullable
GeneratorPlugin getGeneratorPlugin(@NotNull String pluginName);
/**
* Gets all registered {@link GeneratorPlugin}.
*
* @return A collection of registered generator plugins.
*/
@NotNull
Collection<GeneratorPlugin> getGeneratorPlugins();
/**
* Gets all registered plugin names associate with {@link GeneratorPlugin}.
*
* @return A collection of registered generator plugin names.
*/
@NotNull
Collection<String> getGeneratorPluginNames();
/**
* Gets the default world generator string defined in 'bukkit.yml' for a given world.
*
* @param worldName The world to get default generator of.
* @return The generator string if present, else null.
*/
@Nullable
String getDefaultWorldGen(String worldName);
/**
* Gets all the world generator strings defined in 'bukkit.yml'.
*
* @return Map if world names and its respective default world generator strings.
*/
@NotNull
Map<String, String> getDefaultWorldGens();
/**
* Results from validating a generator.
*/
enum TestResult {
/**
* Successfully got {@link ChunkGenerator} from the world generator plugin.
*/
VALID,
/**
* Exceptions thrown while trying to get {@link ChunkGenerator} from the world generator plugin.
*/
ERRORS,
/**
* Plugin is present on the server, but doesnt look like a world generator.
*/
INVALID_GENERATOR,
/**
* Plugin not installed on the server.
*/
PLUGIN_DOES_NOT_EXIST
}
}
@@ -7,9 +7,9 @@
package com.onarandombox.MultiverseCore.api;
import com.onarandombox.MultiverseCore.generators.GeneratorManager;
import com.onarandombox.MultiverseCore.utils.PurgeWorlds;
import com.onarandombox.MultiverseCore.utils.SimpleWorldPurger;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldType;
@@ -65,30 +65,16 @@ public interface MVWorldManager {
*
* @param oldName Name of world to be copied
* @param newName Name of world to be created
* @param generator The Custom generator plugin to use. Ignored.
* @param generator The Custom generator plugin to use.
* @return True if the world is copied successfully, false if not.
* @deprecated Use {@link #cloneWorld(String, String)} instead.
*/
@Deprecated
boolean cloneWorld(String oldName, String newName, String generator);
/**
* Make a copy of a world.
* Remove the world from the Multiverse list, from the
* config and deletes the folder.
*
* @param oldName
* Name of world to be copied
* @param newName
* Name of world to be created
* @return True if the world is copied successfully, false if not.
*/
boolean cloneWorld(String oldName, String newName);
/**
* Remove the world from the Multiverse list, from the config and deletes
* the folder.
*
* @param name
* The name of the world to remove
* @param name The name of the world to remove
* @return True if success, false if failure.
*/
boolean deleteWorld(String name);
@@ -123,15 +109,6 @@ public interface MVWorldManager {
*/
boolean unloadWorld(String name);
/**
* Unload a world from Multiverse with option to prevent calling unloadWorld in Bukkit.
*
* @param name Name of the world to unload
* @param unloadBukkit True if Bukkit world should be unloaded
* @return True if the world was unloaded, false if not.
*/
boolean unloadWorld(String name, boolean unloadBukkit);
/**
* Loads the world. Only use this if the world has been
* unloaded with {@link #unloadWorld(String)}.
@@ -155,9 +132,7 @@ public interface MVWorldManager {
* @param generatorID The generator id.
* @param worldName The worldName to use as the default.
* @return A {@link ChunkGenerator} or null
* @deprecated Use {@link MVGeneratorManager#validateGenerator(String, String)}
*/
@Deprecated
ChunkGenerator getChunkGenerator(String generator, String generatorID, String worldName);
/**
@@ -202,7 +177,7 @@ public interface MVWorldManager {
boolean isMVWorld(World world);
/**
* Load the Worlds &amp; Settings from the configuration file.
* Load the Worlds & Settings from the configuration file.
*
* @param forceLoad If set to true, this will perform a total
* reset and not just load new worlds.
@@ -210,7 +185,7 @@ public interface MVWorldManager {
void loadWorlds(boolean forceLoad);
/**
* Loads the Worlds &amp; Settings for any worlds that bukkit loaded before us.
* Loads the Worlds & Settings for any worlds that bukkit loaded before us.
* <p>
* This way people will _always_ have some worlds in the list.
*/
@@ -252,9 +227,7 @@ public interface MVWorldManager {
/**
* This method populates an internal list and needs to be called after multiverse initialization.
* @deprecated This is now done by {@link GeneratorManager}.
*/
@Deprecated
void getDefaultWorldGenerators();
/**
@@ -305,18 +278,4 @@ public interface MVWorldManager {
* @return True if success, false if fail.
*/
boolean regenWorld(String name, boolean useNewSeed, boolean randomSeed, String seed);
boolean isKeepingSpawnInMemory(World world);
/**
* Checks whether Multiverse knows about a provided unloaded world. This
* method will check the parameter against the alias mappings.
*
* @param name The name of the unloaded world
* @param includeLoaded The value to return if the world is loaded
*
* @return True if the world exists and is unloaded. False if the world
* does not exist. {@code includeLoaded} if the world exists and is loaded.
*/
boolean hasUnloadedWorld(String name, boolean includeLoaded);
}
@@ -86,18 +86,6 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable {
*/
boolean getDisplayPermErrors();
/**
* Sets enableBuscript.
* @param enableBuscript The new value.
*/
void setEnableBuscript(boolean enableBuscript);
/**
* Gets enableBuscript.
* @return enableBuscript.
*/
boolean getEnableBuscript();
/**
* Sets firstSpawnOverride.
* @param firstSpawnOverride The new value.
@@ -133,18 +121,6 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable {
* @return prefixChat.
*/
boolean getPrefixChat();
/**
* Sets prefixChatFormat.
* @param prefixChatFormat The new value.
*/
void setPrefixChatFormat(String prefixChatFormat);
/**
* Gets prefixChatFormat.
* @return prefixChatFormat.
*/
String getPrefixChatFormat();
/**
* Sets enforceAccess.
@@ -211,32 +187,4 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable {
* @return The portal search radius.
*/
int getPortalSearchRadius();
/**
* Gets whether or not the automatic purge of entities is enabled.
*
* @return True if automatic purge is enabled.
*/
boolean isAutoPurgeEnabled();
/**
* Sets whether or not the automatic purge of entities is enabled.
*
* @param autopurge True if automatic purge should be enabled.
*/
void setAutoPurgeEnabled(boolean autopurge);
/**
* Gets whether or not the donation/patreon messages are shown.
*
* @return True if donation/patreon messages should be shown.
*/
boolean isShowingDonateMessage();
/**
* Sets whether or not the donation/patreon messages are shown.
*
* @param idonotwanttodonate True if donation/patreon messages should be shown.
*/
void setShowDonateMessage(boolean idonotwanttodonate);
}
@@ -13,12 +13,10 @@ import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.WorldType;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.jetbrains.annotations.Nullable;
import java.util.List;
@@ -155,6 +153,37 @@ public interface MultiverseWorld {
*/
boolean setPropertyValue(String property, String value) throws PropertyDoesNotExistException;
/**
* Gets the actual MVConfigProperty from this world.
* It will throw a PropertyDoesNotExistException if the property is not found.
*
* @param property The name of a world property to get.
* @param expected The type of the expected property. Use Object.class if this doesn't matter for you.
* @param <T> The type of the expected property.
*
* @return A valid MVWorldProperty.
*
* @throws PropertyDoesNotExistException Thrown if the property was not found in the world.
* @deprecated We don't use {@link com.onarandombox.MultiverseCore.configuration.MVConfigProperty} any longer!
*/
@Deprecated
<T> com.onarandombox.MultiverseCore.configuration.MVConfigProperty<T> getProperty(String property, Class<T> expected) throws PropertyDoesNotExistException;
// old config
/**
* Adds the property to the given value.
* It will throw a PropertyDoesNotExistException if the property is not found.
*
* @param property The name of a world property to set.
* @param value A value in string representation, it will be parsed to the correct type.
* @param sender The sender who wants this value to be set.
* @return True if the value was set, false if not.
* @throws PropertyDoesNotExistException Thrown if the property was not found in the world.
* @deprecated Use {@link #setPropertyValue(String, String)} instead.
*/
@Deprecated
boolean setProperty(String property, String value, CommandSender sender) throws PropertyDoesNotExistException;
/**
* Adds a value to the given property. The property must be a {@link com.onarandombox.MultiverseCore.enums.AddProperties}.
*
@@ -475,28 +504,26 @@ public interface MultiverseWorld {
/**
* Sets the price for entry to this world.
* You can think of this like an amount.
* The type can be set with {@link #setCurrency(Material)}
* The type can be set with {@link #setCurrency(int)}
*
* @param price The Amount of money/item to enter the world.
*/
void setPrice(double price);
/**
* Gets the type of currency that will be used when users enter this world. A value of null indicates a non-item
* based currency is used.
* Gets the Type of currency that will be used when users enter this world.
*
* @return The type of currency that will be used when users enter this world.
* @return The Type of currency that will be used when users enter this world.
*/
@Nullable
Material getCurrency();
int getCurrency();
/**
* Sets the type of item that will be required given the price is not 0.
* Use a value of null to specify a non-item based currency.
* Use -1 to use an AllPay economy, or any valid itemid
*
* @param item The Type of currency that will be used when users enter this world.
*/
void setCurrency(@Nullable Material item);
void setCurrency(int item);
/**
* Gets the world players will respawn in if they die in this one.
@@ -9,7 +9,7 @@ import com.onarandombox.MultiverseCore.enums.TeleportResult;
/**
* Used to safely teleport people.
*/
public interface SafeTTeleporter extends Teleporter {
public interface SafeTTeleporter {
/**
* Gets the next safe location around the given location.
@@ -1,10 +0,0 @@
package com.onarandombox.MultiverseCore.api;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.enums.TeleportResult;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public interface Teleporter {
TeleportResult teleport(CommandSender teleporter, Player teleportee, MVDestination destination);
}
@@ -17,7 +17,7 @@ public interface WorldPurger {
void purgeWorlds(List<MultiverseWorld> worlds);
/**
* Convenience method for {@link #purgeWorld(MultiverseWorld, java.util.List, boolean, boolean)} that takes the settings from the world-config.
* Convenience method for {@link #purgeWorld(CommandSender, MultiverseWorld, List, boolean, boolean)} that takes the settings from the world-config.
*
* @param world The {@link MultiverseWorld}.
*/
@@ -11,7 +11,6 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.destination.InvalidDestination;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import com.onarandombox.MultiverseCore.utils.PlayerFinder;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -38,7 +37,7 @@ public class CheckCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
Player p = PlayerFinder.get(args.get(0), sender);
Player p = this.plugin.getServer().getPlayer(args.get(0));
if (p == null) {
sender.sendMessage("Could not find player " + ChatColor.GREEN + args.get(0));
sender.sendMessage("Are they online?");
@@ -7,14 +7,15 @@
package com.onarandombox.MultiverseCore.commands;
import java.util.List;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import java.util.ArrayList;
import java.util.List;
/**
* Creates a clone of a world.
@@ -33,23 +34,27 @@ public class CloneCommand extends MultiverseCommand {
this.addKey("mv clone");
this.addCommandExample("/mv clone " + ChatColor.GOLD + "world" + ChatColor.GREEN + " world_backup");
this.addCommandExample("/mv clone " + ChatColor.GOLD + "skyblock_pristine" + ChatColor.GREEN + " skyblock");
this.addCommandExample("To clone a world that uses a generator:");
this.addCommandExample("/mv clone " + ChatColor.GOLD + "CleanRoom"
+ ChatColor.GREEN + " CleanRoomCopy" + ChatColor.DARK_AQUA + " -g CleanRoomGenerator");
this.setPermission("multiverse.core.clone", "Clones a world.", PermissionDefault.OP);
this.worldManager = this.plugin.getMVWorldManager();
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
String oldName = args.get(0);
if (!this.worldManager.hasUnloadedWorld(oldName, true)) {
Class<?>[] paramTypes = {String.class, String.class, String.class};
List<Object> objectArgs = new ArrayList<Object>();
objectArgs.add(args.get(0));
objectArgs.add(args.get(1));
objectArgs.add(CommandHandler.getFlag("-g", args));
if (!this.worldManager.isMVWorld(args.get(0))) {
// If no world was found, we can't clone.
sender.sendMessage("Sorry, Multiverse doesn't know about world " + oldName + ", so we can't clone it!");
sender.sendMessage("Sorry, Multiverse doesn't know about world " + args.get(0) + ", so we can't clone it!");
sender.sendMessage("Check the " + ChatColor.GREEN + "/mv list" + ChatColor.WHITE + " command to verify it is listed.");
return;
}
if (this.plugin.getMVWorldManager().cloneWorld(oldName, args.get(1))) {
sender.sendMessage(ChatColor.GREEN + "World cloned!");
} else {
sender.sendMessage(ChatColor.RED + "World could NOT be cloned!");
}
this.plugin.getCommandHandler().queueCommand(sender, "mvclone", "cloneWorld", objectArgs,
paramTypes, ChatColor.GREEN + "World Cloned!", ChatColor.RED + "World could NOT be cloned!");
}
}
@@ -62,7 +62,7 @@ public class CoordCommand extends MultiverseCommand {
df.setMaximumFractionDigits(2);
p.sendMessage(ChatColor.AQUA + "Coordinates: " + ChatColor.WHITE + plugin.getLocationManipulation().strCoords(p.getLocation()));
p.sendMessage(ChatColor.AQUA + "Direction: " + ChatColor.WHITE + plugin.getLocationManipulation().getDirection(p.getLocation()));
p.sendMessage(ChatColor.AQUA + "Block: " + ChatColor.WHITE + world.getBlockAt(p.getLocation()).getType());
p.sendMessage(ChatColor.AQUA + "Block: " + ChatColor.WHITE + Material.getMaterial(world.getBlockTypeIdAt(p.getLocation())));
} else {
sender.sendMessage("This command needs to be used from a Player.");
}
@@ -9,7 +9,6 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MVGeneratorManager;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.World.Environment;
@@ -19,6 +18,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
@@ -97,26 +98,14 @@ public class CreateCommand extends MultiverseCommand {
}
// Determine if the generator is valid. #918
if (generator != null) {
MVGeneratorManager.TestResult result = this.plugin.getMVGeneratorManager().validateGenerator(generator, worldName);
if (result != MVGeneratorManager.TestResult.VALID) {
List<String> genarray = new ArrayList<String>(Arrays.asList(generator.split(":")));
if (genarray.size() < 2) {
// If there was only one arg specified, pad with another empty one.
genarray.add("");
}
if (this.worldManager.getChunkGenerator(genarray.get(0), genarray.get(1), "test") == null) {
// We have an invalid generator.
switch (result) {
case ERRORS:
sender.sendMessage("An issue occurred while validating generator string '" + generator +
"'! This may indicate an issue with your generator plugin or an invalid generator id. Check console for errors!");
break;
case INVALID_GENERATOR:
sender.sendMessage("Invalid generator string '" + generator +
"'! The generator id you use is probably not supported by your generator plugin.");
break;
case PLUGIN_DOES_NOT_EXIST:
sender.sendMessage("That generator plugin is not installed on your server!");
break;
default:
sender.sendMessage("Invalid generator string '" + generator + "'!");
break;
}
sender.sendMessage(ChatColor.RED + "Aborting world creation...");
sender.sendMessage("Invalid generator! '" + generator + "'. " + ChatColor.RED + "Aborting world creation.");
return;
}
}
@@ -7,7 +7,6 @@
package com.onarandombox.MultiverseCore.commands;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@@ -61,7 +60,7 @@ public class DebugCommand extends MultiverseCommand {
sender.sendMessage("Multiverse Debug mode is " + ChatColor.RED + "OFF");
} else {
sender.sendMessage("Multiverse Debug mode is " + ChatColor.GREEN + debugLevel);
Logging.fine("Multiverse Debug ENABLED");
this.plugin.log(Level.FINE, "Multiverse Debug ENABLED");
}
}
}
@@ -27,19 +27,15 @@ public class DeleteCommand extends MultiverseCommand {
this.setArgRange(1, 1);
this.addKey("mvdelete");
this.addKey("mv delete");
this.addCommandExample("/mv delete " + ChatColor.GOLD + "MyWorld");
this.addCommandExample("/mv create " + ChatColor.GOLD + "MyWorld");
this.setPermission("multiverse.core.delete", "Deletes a world on your server. " + ChatColor.RED + "PERMANENTLY.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
String worldName = args.get(0);
Class<?>[] paramTypes = {String.class};
List<Object> objectArgs = new ArrayList<Object>(args);
this.plugin.getCommandHandler()
.queueCommand(sender, "mvdelete", "deleteWorld", objectArgs,
paramTypes, ChatColor.GREEN + "World '" + worldName + "' Deleted!",
ChatColor.RED + "World '" + worldName + "' could NOT be deleted!");
this.plugin.getCommandHandler().queueCommand(sender, "mvdelete", "deleteWorld", objectArgs,
paramTypes, ChatColor.GREEN + "World Deleted!", ChatColor.RED + "World could NOT be deleted!");
}
}
@@ -71,14 +71,12 @@ public class EnvironmentCommand extends MultiverseCommand {
*/
public static WorldType getWorldTypeFromString(String type) {
// Don't reference the enum directly as there aren't that many, and we can be more forgiving to users this way
if (type.equalsIgnoreCase("normal")) {
if (type.equalsIgnoreCase("normal"))
type = "NORMAL";
} else if (type.equalsIgnoreCase("flat")) {
if (type.equalsIgnoreCase("flat"))
type = "FLAT";
} else if (type.equalsIgnoreCase("largebiomes")) {
if (type.equalsIgnoreCase("largebiomes")) {
type = "LARGE_BIOMES";
} else if (type.equalsIgnoreCase("amplified")) {
type = "AMPLIFIED";
}
try {
// Now that we've converted a potentially unfriendly value
@@ -10,7 +10,6 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameRule;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -56,61 +55,21 @@ public class GameruleCommand extends MultiverseCommand {
return;
}
final GameRule gameRule = GameRule.getByName(args.get(0));
final String gameRule = args.get(0);
final String value = args.get(1);
final World world;
if (args.size() == 2) {
world = p.getWorld();
} else {
world = Bukkit.getWorld(args.get(2));
if (world == null) {
sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " World " + ChatColor.AQUA + args.get(2)
+ ChatColor.WHITE + " does not exist.");
return;
}
}
if (gameRule == null) {
sender.sendMessage(ChatColor.RED + "Failure! " + ChatColor.AQUA + args.get(0) + ChatColor.WHITE
+ " is not a valid gamerule.");
if (world.setGameRuleValue(gameRule, value)) {
sender.sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule
+ ChatColor.WHITE + " was set to " + ChatColor.GREEN + value);
} else {
if (gameRule.getType() == Boolean.class) {
boolean booleanValue;
if (value.equalsIgnoreCase("true")) {
booleanValue = true;
} else if (value.equalsIgnoreCase("false")) {
booleanValue = false;
} else {
sender.sendMessage(getErrorMessage(gameRule.getName(), value) + "it can only be set to true or false.");
return;
}
if (!world.setGameRule(gameRule, booleanValue)) {
sender.sendMessage(getErrorMessage(gameRule.getName(), value) + "something went wrong.");
return;
}
} else if (gameRule.getType() == Integer.class) {
try {
if (!world.setGameRule(gameRule, Integer.parseInt(value))) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
sender.sendMessage(getErrorMessage(gameRule.getName(), value) + "it can only be set to a positive integer.");
return;
}
} else {
sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule.getName()
+ ChatColor.WHITE + " isn't supported yet, please let us know about it.");
return;
}
sender.sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule.getName()
+ ChatColor.WHITE + " was set to " + ChatColor.GREEN + value + ChatColor.WHITE + ".");
sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule
+ ChatColor.WHITE + " cannot be set to " + ChatColor.RED + value);
}
}
private String getErrorMessage(String gameRule, String value) {
return ChatColor.RED + "Failure!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule
+ ChatColor.WHITE + " could not be set to " + ChatColor.RED + value + ChatColor.WHITE + ", ";
}
}
@@ -10,7 +10,6 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameRule;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -61,11 +60,6 @@ public class GamerulesCommand extends MultiverseCommand {
world = p.getWorld();
} else {
world = Bukkit.getWorld(args.get(0));
if (world == null) {
sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " World " + ChatColor.AQUA + args.get(0)
+ ChatColor.WHITE + " does not exist.");
return;
}
}
final StringBuilder gameRules = new StringBuilder();
@@ -74,7 +68,7 @@ public class GamerulesCommand extends MultiverseCommand {
gameRules.append(ChatColor.WHITE).append(", ");
}
gameRules.append(ChatColor.AQUA).append(gameRule).append(ChatColor.WHITE).append(": ");
gameRules.append(ChatColor.GREEN).append(world.getGameRuleValue(GameRule.getByName(gameRule)));
gameRules.append(ChatColor.GREEN).append(world.getGameRuleValue(gameRule));
}
sender.sendMessage("=== Gamerules for " + ChatColor.AQUA + world.getName() + ChatColor.WHITE + " ===");
sender.sendMessage(gameRules.toString());
@@ -9,19 +9,12 @@ package com.onarandombox.MultiverseCore.commands;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.GeneratorPlugin;
import com.onarandombox.MultiverseCore.generators.SimpleGeneratorPlugin;
import net.milkbowl.vault.chat.Chat;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
@@ -32,70 +25,36 @@ public class GeneratorCommand extends MultiverseCommand {
public GeneratorCommand(MultiverseCore plugin) {
super(plugin);
this.setName("World Information");
this.setCommandUsage("/mv generators [plugin]");
this.setArgRange(0, 1);
this.setCommandUsage("/mv generators");
this.setArgRange(0, 0);
this.addKey("mv generators");
this.addKey("mvgenerators");
this.addKey("mv gens");
this.addKey("mvgens");
this.addCommandExample("/mv generators");
this.addCommandExample("/mv generators VoidGenerator");
this.setPermission("multiverse.core.generator", "Returns info of Loaded Generator Plugins.", PermissionDefault.OP);
this.setPermission("multiverse.core.generator", "Returns a list of Loaded Generator Plugins.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
if (args.size() == 0) {
listKnownGenerators(sender);
return;
Logging.info("PLEASE IGNORE the 'Plugin X does not contain any generators' message below!");
Plugin[] plugins = this.plugin.getServer().getPluginManager().getPlugins();
List<String> generators = new ArrayList<String>();
for (Plugin p : plugins) {
if (p.isEnabled() && p.getDefaultWorldGenerator("world", "") != null) {
generators.add(p.getDescription().getName());
}
}
showGeneratorDetails(sender, args.get(0));
}
private void listKnownGenerators(CommandSender sender) {
sender.sendMessage(ChatColor.AQUA + "--- Loaded Generator Plugins ---");
StringBuilder loadedGens = new StringBuilder();
String loadedGens = "";
boolean altColor = false;
for (String s : this.plugin.getMVGeneratorManager().getGeneratorPluginNames()) {
loadedGens.append(altColor ? ChatColor.YELLOW : ChatColor.WHITE).append(s).append(' ');
for (String s : generators) {
loadedGens += (altColor ? ChatColor.YELLOW : ChatColor.WHITE) + s + " ";
altColor = !altColor;
}
if (loadedGens.length() == 0) {
loadedGens.append(ChatColor.RED).append("No Generator Plugins found.");
}
sender.sendMessage(loadedGens.toString());
}
private void showGeneratorDetails(CommandSender sender, String pluginName) {
Plugin genPlugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (genPlugin == null) {
sender.sendMessage(ChatColor.RED + "You do not have a plugin named '"+ pluginName + "' on your server.");
return;
}
GeneratorPlugin generatorPlugin = this.plugin.getMVGeneratorManager().getGeneratorPlugin(genPlugin);
if (generatorPlugin == null) {
sender.sendMessage(ChatColor.RED + "'" + pluginName + "' does not look like a generator plugin.");
return;
}
sender.sendMessage(ChatColor.AQUA + "--- Info on " + generatorPlugin.getPlugin().getName() + " ---");
boolean hasAddInfo = false;
Collection<String> exampleUsages = generatorPlugin.getExampleUsages();
if (exampleUsages != null && exampleUsages.size() > 0) {
hasAddInfo = true;
sender.sendMessage("Usages:");
exampleUsages.forEach(sender::sendMessage);
}
String infoLink = generatorPlugin.getInfoLink();
if (infoLink != null) {
hasAddInfo = true;
sender.sendMessage("More Info: " + infoLink);
}
if (!hasAddInfo) {
sender.sendMessage(ChatColor.RED + "'" + pluginName + "' did not provide additional info to Multiverse.");
loadedGens = ChatColor.RED + "No Generator Plugins found.";
}
sender.sendMessage(loadedGens);
}
}
@@ -10,7 +10,6 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.WorldNameChecker;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.World.Environment;
@@ -46,6 +45,28 @@ public class ImportCommand extends MultiverseCommand {
this.worldManager = this.plugin.getMVWorldManager();
}
/**
* A very basic check to see if a folder has a level.dat file.
* If it does, we can safely assume it's a world folder.
*
* @param worldFolder The File that may be a world.
* @return True if it looks like a world, false if not.
*/
private static boolean checkIfIsWorld(File worldFolder) {
if (worldFolder.isDirectory()) {
File[] files = worldFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String name) {
return name.equalsIgnoreCase("level.dat");
}
});
if (files != null && files.length > 0) {
return true;
}
}
return false;
}
private String getPotentialWorlds() {
File worldFolder = this.plugin.getServer().getWorldContainer();
if (worldFolder == null) {
@@ -63,7 +84,7 @@ public class ImportCommand extends MultiverseCommand {
}
ChatColor currColor = ChatColor.WHITE;
for (File file : files) {
if (file.isDirectory() && WorldNameChecker.isValidWorldFolder(file) && !worldStrings.contains(file.getName())) {
if (file.isDirectory() && checkIfIsWorld(file) && !worldStrings.contains(file.getName())) {
worldList += currColor + file.getName() + " ";
if (currColor == ChatColor.WHITE) {
currColor = ChatColor.YELLOW;
@@ -74,15 +95,10 @@ public class ImportCommand extends MultiverseCommand {
}
return worldList;
}
private String trimWorldName(String userInput) {
// Removes relative paths.
return userInput.replaceAll("^[./\\\\]+", "");
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
String worldName = trimWorldName(args.get(0));
String worldName = args.get(0);
if (worldName.toLowerCase().equals("--list") || worldName.toLowerCase().equals("-l")) {
String worldList = this.getPotentialWorlds();
@@ -96,7 +112,7 @@ public class ImportCommand extends MultiverseCommand {
}
// Since we made an exception for the list, we have to make sure they have at least 2 params:
// Note the exception is --list, which is covered above.
if (args.size() == 1 || worldName.length() < 1) {
if (args.size() == 1) {
this.showHelp(sender);
return;
}
@@ -126,25 +142,21 @@ public class ImportCommand extends MultiverseCommand {
return;
}
if (!worldFile.exists()) {
sender.sendMessage(ChatColor.RED + "FAILED.");
String worldList = this.getPotentialWorlds();
sender.sendMessage("That world folder does not exist. These look like worlds to me:");
sender.sendMessage(worldList);
} else if (!WorldNameChecker.isValidWorldFolder(worldFile)) {
sender.sendMessage(ChatColor.RED + "FAILED.");
sender.sendMessage(String.format("'%s' does not appear to be a world. It is lacking a .dat file.",
worldName));
} else if (env == null) {
sender.sendMessage(ChatColor.RED + "FAILED.");
sender.sendMessage("That world environment did not exist.");
sender.sendMessage("For a list of available world types, type: " + ChatColor.AQUA + "/mvenv");
} else {
if (worldFile.exists() && env != null) {
Command.broadcastCommandMessage(sender, String.format("Starting import of world '%s'...", worldName));
if (this.worldManager.addWorld(worldName, environment, null, null, null, generator, useSpawnAdjust))
Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Complete!");
else
Command.broadcastCommandMessage(sender, ChatColor.RED + "Failed!");
} else if (env == null) {
sender.sendMessage(ChatColor.RED + "FAILED.");
sender.sendMessage("That world environment did not exist.");
sender.sendMessage("For a list of available world types, type: " + ChatColor.AQUA + "/mvenv");
} else {
sender.sendMessage(ChatColor.RED + "FAILED.");
String worldList = this.getPotentialWorlds();
sender.sendMessage("That world folder does not exist. These look like worlds to me:");
sender.sendMessage(worldList);
}
}
}
@@ -115,7 +115,6 @@ public class InfoCommand extends MultiverseCommand {
FancyColorScheme colors = new FancyColorScheme(ChatColor.AQUA, ChatColor.AQUA, ChatColor.GOLD, ChatColor.WHITE);
message.add(new FancyHeader("General Info", colors));
message.add(new FancyMessage("World Name: ", world.getName(), colors));
message.add(new FancyMessage("World UID: ", world.getCBWorld().getUID().toString(), colors));
message.add(new FancyMessage("World Alias: ", world.getColoredWorldString(), colors));
message.add(new FancyMessage("Game Mode: ", world.getGameMode().toString(), colors));
message.add(new FancyMessage("Difficulty: ", world.getDifficulty().toString(), colors));
@@ -126,13 +125,13 @@ public class InfoCommand extends MultiverseCommand {
message.add(new FancyMessage("World Scale: ", String.valueOf(world.getScaling()), colors));
message.add(new FancyMessage("World Seed: ", String.valueOf(world.getSeed()), colors));
if (world.getPrice() > 0) {
message.add(new FancyMessage("Price to enter this world: ",
plugin.getEconomist().formatPrice(world.getPrice(), world.getCurrency()),
colors));
} else if (world.getPrice() < 0) {
message.add(new FancyMessage("Reward for entering this world: ",
plugin.getEconomist().formatPrice(-world.getPrice(), world.getCurrency()),
colors));
final String formattedAmount;
if (world.getCurrency() <= 0 && plugin.getVaultHandler().getEconomy() != null) {
formattedAmount = plugin.getVaultHandler().getEconomy().format(world.getPrice());
} else {
formattedAmount = this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency());
}
message.add(new FancyMessage("Price to enter this world: ", formattedAmount, colors));
} else {
message.add(new FancyMessage("Price to enter this world: ", ChatColor.GREEN + "FREE!", colors));
}
@@ -152,7 +151,6 @@ public class InfoCommand extends MultiverseCommand {
message = new ArrayList<FancyText>();
message.add(new FancyHeader("More World Settings", colors));
message.add(new FancyMessage("World Type: ", world.getWorldType().toString(), colors));
message.add(new FancyMessage("Generator: ", world.getGenerator(), colors));
message.add(new FancyMessage("Structures: ", world.getCBWorld().canGenerateStructures() + "", colors));
message.add(new FancyMessage("Weather: ", world.isWeatherEnabled() + "", colors));
message.add(new FancyMessage("Players will get hungry: ", world.getHunger() + "", colors));
@@ -183,8 +181,8 @@ public class InfoCommand extends MultiverseCommand {
message.add(new FancyHeader("Animal Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.canAnimalsSpawn() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowAnimals() + "", colors));
if (world.getAnimalList().size() > 0) {
if (world.canAnimalsSpawn()) {
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Animals that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getAnimalList()), colors));
} else {
@@ -26,7 +26,7 @@ public class ListCommand extends PaginatedCoreCommand<String> {
public ListCommand(MultiverseCore plugin) {
super(plugin);
this.setName("World Listing");
this.setCommandUsage("/mv list [page]");
this.setCommandUsage("/mv list");
this.setArgRange(0, 2);
this.addKey("mvlist");
this.addKey("mvl");
@@ -77,7 +77,7 @@ public class ModifyAddCommand extends MultiverseCommand {
if (!ModifyCommand.validateAction(Action.Add, property)) {
sender.sendMessage("Sorry, you can't ADD to " + property);
sender.sendMessage("Please visit our Github Wiki for more information: https://goo.gl/OMGwzx");
sender.sendMessage("Please visit our Github Wiki for more information: http://goo.gl/4W8cY");
return;
}
@@ -72,7 +72,7 @@ public class ModifyClearCommand extends MultiverseCommand {
if (!ModifyCommand.validateAction(Action.Clear, property)) {
sender.sendMessage("Sorry, you can't use CLEAR with " + property);
sender.sendMessage("Please visit our Github Wiki for more information: https://goo.gl/q1h01S");
sender.sendMessage("Please visit our Github Wiki for more information: http://goo.gl/cgB2B");
return;
}
// TODO fix this
@@ -78,7 +78,7 @@ public class ModifyRemoveCommand extends MultiverseCommand {
if (!ModifyCommand.validateAction(Action.Remove, property)) {
sender.sendMessage("Sorry, you can't REMOVE anything from" + property);
sender.sendMessage("Please visit our Github Wiki for more information: https://goo.gl/OMGwzx");
sender.sendMessage("Please visit our Github Wiki for more information: http://goo.gl/4W8cY");
return;
}
// TODO fix this
@@ -27,7 +27,6 @@ public class ReloadCommand extends MultiverseCommand {
this.setCommandUsage("/mv reload");
this.setArgRange(0, 0);
this.addKey("mvreload");
this.addKey("mvr");
this.addKey("mv reload");
this.addCommandExample("/mv reload");
this.setPermission("multiverse.core.reload", "Reloads worlds.yml and config.yml.", PermissionDefault.OP);
@@ -35,10 +35,6 @@ public class ScriptCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
if (plugin.getScriptAPI() == null) {
sender.sendMessage("Buscript failed to load while the server was starting. Scripts cannot be run.");
return;
}
File file = new File(plugin.getScriptAPI().getScriptFolder(), args.get(0));
if (!file.exists()) {
sender.sendMessage("That script file does not exist in the Multiverse-Core scripts directory!");
@@ -18,7 +18,6 @@ import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
import org.bukkit.Bukkit;
/**
* Sets the spawn for a world.
@@ -28,9 +27,8 @@ public class SetSpawnCommand extends MultiverseCommand {
super(plugin);
this.setName("Set World Spawn");
this.setCommandUsage("/mv setspawn");
this.setArgRange(0, 6);
this.setArgRange(0, 0);
this.addKey("mvsetspawn");
this.addKey("mvsets");
this.addKey("mvss");
this.addKey("mv set spawn");
this.addKey("mv setspawn");
@@ -39,110 +37,43 @@ public class SetSpawnCommand extends MultiverseCommand {
this.setPermission("multiverse.core.spawn.set", "Sets the spawn for the current world.", PermissionDefault.OP);
}
/**
* Dispatches the user's command depending on the number of parameters
* @param sender The player who executes the command, may be console as well.
* @param args Command line parameters
*/
@Override
public void runCommand(CommandSender sender, List<String> args) {
if (args.isEmpty()) {
setWorldSpawn(sender);
} else if (args.size() == 4) {
setWorldSpawn(sender, args.get(0), args.get(1), args.get(2), args.get(3));
} else if (args.size() == 6) {
setWorldSpawn(sender, args.get(0), args.get(1), args.get(2), args.get(3), args.get(4), args.get(5));
} else {
sender.sendMessage("Use no arguments for your current location, or world/x/y/z, or world/x/y/z/yaw/pitch!");
}
}
/**
* Set the world spawn when no parameters are given
* @param sender The {@link CommandSender} who executes the command.
* Everything not a {@link Player}, e.g. console, gets rejected, as we can't get coordinates from there.
*/
protected void setWorldSpawn(CommandSender sender) {
if (sender instanceof Player) {
Player p = (Player) sender;
Location l = p.getLocation();
World w = p.getWorld();
setWorldSpawn(sender, w, l);
} else {
sender.sendMessage("You need to give coordinates to use this command from the console!");
}
}
/**
* Set the world spawn when 4 parameters are given
* @param sender The {@link CommandSender} who executes the command
* @param world The world to set the spawn in
* @param x X-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double)
* @param y Y-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double)
* @param z Z-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double)
*/
protected void setWorldSpawn(CommandSender sender, String world, String x, String y, String z) {
setWorldSpawn(sender, world, x, y, z, "0", "0");
}
/**
* Set the world spawn when 6 parameters are given
* @param sender The {@link CommandSender} who executes the command
* @param world The world to set the spawn in
* @param x X-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double)
* @param y Y-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double)
* @param z Z-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double)
* @param yaw Yaw a newly spawned player should look at (as a {@link String} as it's from the command line, gets parsed into a float)
* @param pitch Pitch a newly spawned player should look at (as a {@link String} as it's from the command line, gets parsed into a float)
*/
protected void setWorldSpawn(CommandSender sender, String world, String x, String y, String z, String yaw, String pitch) {
double dx, dy, dz;
float fpitch, fyaw;
World bukkitWorld = Bukkit.getWorld(world);
if (bukkitWorld == null) {
sender.sendMessage("World " + world + " is unknown!");
return;
}
try {
dx = Double.parseDouble(x);
dy = Double.parseDouble(y);
dz = Double.parseDouble(z);
fpitch = Float.parseFloat(pitch);
fyaw = Float.parseFloat(yaw);
} catch (NumberFormatException ex) {
sender.sendMessage("All coordinates must be numeric");
return;
}
Location l = new Location(bukkitWorld, dx, dy, dz, fyaw, fpitch);
setWorldSpawn(sender, bukkitWorld, l);
setWorldSpawn(sender);
}
/**
* Does the actual spawn-setting-work.
*
* @param sender The {@link CommandSender} that's setting the spawn.
* @param w The {@link World} to set the spawn in
* @param l The {@link Location} to set the spawn to
*/
private void setWorldSpawn(CommandSender sender, World w, Location l) {
MultiverseWorld foundWorld = this.plugin.getMVWorldManager().getMVWorld(w.getName());
if (foundWorld != null) {
foundWorld.setSpawnLocation(l);
BlockSafety bs = this.plugin.getBlockSafety();
if (!bs.playerCanSpawnHereSafely(l) && foundWorld.getAdjustSpawn()) {
sender.sendMessage("It looks like that location would normally be unsafe. But I trust you.");
sender.sendMessage("I'm turning off the Safe-T-Teleporter for spawns to this world.");
sender.sendMessage("If you want this turned back on just do:");
sender.sendMessage(ChatColor.AQUA + "/mvm set adjustspawn true " + foundWorld.getAlias());
foundWorld.setAdjustSpawn(false);
}
sender.sendMessage("Spawn was set to: " + plugin.getLocationManipulation().strCoords(l));
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
protected void setWorldSpawn(CommandSender sender) {
if (sender instanceof Player) {
Player p = (Player) sender;
Location l = p.getLocation();
World w = p.getWorld();
MultiverseWorld foundWorld = this.plugin.getMVWorldManager().getMVWorld(w.getName());
if (foundWorld != null) {
foundWorld.setSpawnLocation(p.getLocation());
BlockSafety bs = this.plugin.getBlockSafety();
if (!bs.playerCanSpawnHereSafely(p.getLocation()) && foundWorld.getAdjustSpawn()) {
sender.sendMessage("It looks like that location would normally be unsafe. But I trust you.");
sender.sendMessage("I'm turning off the Safe-T-Teleporter for spawns to this world.");
sender.sendMessage("If you want this turned back on just do:");
sender.sendMessage(ChatColor.AQUA + "/mvm set adjustspawn true " + foundWorld.getAlias());
foundWorld.setAdjustSpawn(false);
}
sender.sendMessage("Spawn was set to: " + plugin.getLocationManipulation().strCoords(p.getLocation()));
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
w.setSpawnLocation(l.getBlockX(), l.getBlockY(), l.getBlockZ());
sender.sendMessage("Multiverse does not know about this world, only X,Y and Z set. Please import it to set the spawn fully (Pitch/Yaws).");
}
} else {
w.setSpawnLocation(l.getBlockX(), l.getBlockY(), l.getBlockZ());
sender.sendMessage("Multiverse does not know about this world, only X,Y and Z set. Please import it to set the spawn fully (Pitch/Yaws).");
sender.sendMessage("You cannot use this command from the console.");
}
}
}
@@ -9,7 +9,6 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.PlayerFinder;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
@@ -51,7 +50,7 @@ public class SpawnCommand extends MultiverseCommand {
sender.sendMessage("You don't have permission to teleport another player to spawn. (multiverse.core.spawn.other)");
return;
}
Player target = PlayerFinder.get(args.get(0), sender);
Player target = this.plugin.getServer().getPlayer(args.get(0));
if (target != null) {
target.sendMessage("Teleporting to this world's spawn...");
spawnAccurately(target);
@@ -0,0 +1,66 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
/*
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import org.getspout.spoutapi.gui.GenericButton;
import org.getspout.spoutapi.gui.GenericPopup;
import org.getspout.spoutapi.gui.PopupScreen;
import org.getspout.spoutapi.player.SpoutPlayer;
import java.util.List;
/**
* Edit a world with spout.
* /
public class SpoutCommand extends MultiverseCommand {
public SpoutCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Edit World with Spout");
this.setCommandUsage("/mv spout");
this.setArgRange(0, 0);
this.addKey("mv spout");
this.setPermission("multiverse.core.spout", "Edit a world with spout.", PermissionDefault.OP);
this.addCommandExample("/mv spout");
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command must be run as a player!");
return;
}
if (plugin.getSpout() == null) {
sender.sendMessage(ChatColor.RED + "You need spout installed on this server to use it with Multiverse!");
return;
}
SpoutPlayer p = (SpoutPlayer) sender;
if (!p.isSpoutCraftEnabled()) {
sender.sendMessage(ChatColor.RED + p.getName() + "You need to be using the Spoutcraft client to run this command!");
return;
}
PopupScreen pop = new GenericPopup();
GenericButton button = new GenericButton("Fish");
// TO-DO maybe use constants for these
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
button.setX(50);
button.setY(50);
button.setWidth(100);
button.setHeight(40);
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
pop.attachWidget(this.plugin, button);
sender.sendMessage(ChatColor.GREEN + "YAY!");
p.getMainScreen().attachPopupScreen(pop);
}
}
*/
@@ -7,18 +7,14 @@
package com.onarandombox.MultiverseCore.commands;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.Teleporter;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.destination.CustomTeleporterDestination;
import com.onarandombox.MultiverseCore.destination.DestinationFactory;
import com.onarandombox.MultiverseCore.destination.InvalidDestination;
import com.onarandombox.MultiverseCore.destination.WorldDestination;
import com.onarandombox.MultiverseCore.enums.TeleportResult;
import com.onarandombox.MultiverseCore.event.MVTeleportEvent;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.utils.PlayerFinder;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
@@ -29,6 +25,7 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Used to teleport players.
@@ -41,7 +38,7 @@ public class TeleportCommand extends MultiverseCommand {
Permission menu = new Permission("multiverse.teleport.*", "Allows you to display the teleport menu.", PermissionDefault.OP);
this.setName("Teleport");
this.setCommandUsage("/mv tp " + ChatColor.GOLD + "[PLAYER]" + ChatColor.GREEN + " {DESTINATION}");
this.setCommandUsage("/mv tp " + ChatColor.GOLD + "[PLAYER]" + ChatColor.GREEN + " {WORLD}");
this.setArgRange(1, 2);
this.addKey("mvtp");
this.addKey("mv tp");
@@ -59,7 +56,7 @@ public class TeleportCommand extends MultiverseCommand {
String destinationName;
if (args.size() == 2) {
teleportee = PlayerFinder.get(args.get(0), sender);
teleportee = this.plugin.getServer().getPlayer(args.get(0));
if (teleportee == null) {
this.messaging.sendMessage(sender, String.format("Sorry, I couldn't find player: %s%s",
ChatColor.GOLD, args.get(0)), false);
@@ -75,14 +72,27 @@ public class TeleportCommand extends MultiverseCommand {
}
teleportee = (Player) sender;
}
// Special case for cannons:
if (destinationName.matches("(?i)cannon-[\\d]+(\\.[\\d]+)?")) {
String[] cannonSpeed = destinationName.split("-");
try {
double speed = Double.parseDouble(cannonSpeed[1]);
destinationName = "ca:" + teleportee.getWorld().getName() + ":" + teleportee.getLocation().getX()
+ "," + teleportee.getLocation().getY() + "," + teleportee.getLocation().getZ() + ":"
+ teleportee.getLocation().getPitch() + ":" + teleportee.getLocation().getYaw() + ":" + speed;
} catch (Exception e) {
destinationName = "i:invalid";
}
}
DestinationFactory df = this.plugin.getDestFactory();
MVDestination d = df.getPlayerAwareDestination(teleportee, destinationName);
MVDestination d = df.getDestination(destinationName);
MVTeleportEvent teleportEvent = new MVTeleportEvent(d, teleportee, teleporter, true);
this.plugin.getServer().getPluginManager().callEvent(teleportEvent);
if (teleportEvent.isCancelled()) {
Logging.fine("Someone else cancelled the MVTeleport Event!!!");
this.plugin.log(Level.FINE, "Someone else cancelled the MVTeleport Event!!!");
return;
}
@@ -146,13 +156,11 @@ public class TeleportCommand extends MultiverseCommand {
this.messaging.sendMessage(teleporter, "Sorry Boss, I tried everything, but just couldn't teleport ya there!", false);
return;
}
Teleporter teleportObject = (d instanceof CustomTeleporterDestination) ?
((CustomTeleporterDestination)d).getTeleporter() : this.playerTeleporter;
TeleportResult result = teleportObject.teleport(teleporter, teleportee, d);
TeleportResult result = this.playerTeleporter.safelyTeleport(teleporter, teleportee, d);
if (result == TeleportResult.FAIL_UNSAFE) {
Logging.fine("Could not teleport " + teleportee.getName()
this.plugin.log(Level.FINE, "Could not teleport " + teleportee.getName()
+ " to " + plugin.getLocationManipulation().strCoordsRaw(d.getLocation(teleportee)));
Logging.fine("Queueing Command");
this.plugin.log(Level.FINE, "Queueing Command");
Class<?>[] paramTypes = { CommandSender.class, Player.class, Location.class };
List<Object> items = new ArrayList<Object>();
items.add(teleporter);
@@ -162,7 +170,7 @@ public class TeleportCommand extends MultiverseCommand {
if (!teleportee.equals(teleporter)) {
player = teleportee.getName();
}
String message = String.format("%sMultiverse %sdid not teleport %s%s %sto %s%s %sbecause it was unsafe.",
String message = String.format("%sMultiverse %sdid not teleport %s%s%sto %s%s%sbecause it was unsafe.",
ChatColor.GREEN, ChatColor.WHITE, ChatColor.AQUA, player, ChatColor.WHITE, ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE);
this.plugin.getCommandHandler().queueCommand(sender, "mvteleport", "teleportPlayer", items,
paramTypes, message, "Would you like to try anyway?", "", "", UNSAFE_TELEPORT_EXPIRE_DELAY);
@@ -10,116 +10,35 @@ package com.onarandombox.MultiverseCore.commands;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
import com.onarandombox.MultiverseCore.utils.webpaste.BitlyURLShortener;
import com.onarandombox.MultiverseCore.utils.webpaste.PasteFailedException;
import com.onarandombox.MultiverseCore.utils.webpaste.PasteService;
import com.onarandombox.MultiverseCore.utils.webpaste.PasteServiceFactory;
import com.onarandombox.MultiverseCore.utils.webpaste.PasteServiceType;
import com.onarandombox.MultiverseCore.utils.webpaste.URLShortener;
import com.onarandombox.MultiverseCore.utils.webpaste.URLShortenerFactory;
import com.onarandombox.MultiverseCore.utils.webpaste.URLShortenerType;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.util.List;
import java.util.Map;
/**
* Dumps version info to the console.
*/
public class VersionCommand extends MultiverseCommand {
private static final URLShortener SHORTENER = URLShortenerFactory.getService(URLShortenerType.BITLY);
private static final URLShortener SHORTENER = new BitlyURLShortener();
public VersionCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Multiverse Version");
this.setCommandUsage("/mv version " + ChatColor.GOLD + "[-b|-h|-p] [--include-plugin-list]");
this.setArgRange(0, 2);
this.setCommandUsage("/mv version " + ChatColor.GOLD + "-[pb]");
this.setArgRange(0, 1);
this.addKey("mv version");
this.addKey("mvver");
this.addKey("mvv");
this.addKey("mvversion");
this.setPermission("multiverse.core.version",
"Dumps version info to the console, optionally to pastebin.com with -b, to hastebin.com using -h, or to paste.gg with -p.", PermissionDefault.TRUE);
}
private String getLegacyString() {
return "[Multiverse-Core] Multiverse-Core Version: " + this.plugin.getDescription().getVersion() + '\n'
+ "[Multiverse-Core] Bukkit Version: " + this.plugin.getServer().getVersion() + '\n'
+ "[Multiverse-Core] Loaded Worlds: " + this.plugin.getMVWorldManager().getMVWorlds() + '\n'
+ "[Multiverse-Core] Multiverse Plugins Loaded: " + this.plugin.getPluginCount() + '\n'
+"[Multiverse-Core] Economy being used: " + plugin.getEconomist().getEconomyName() + '\n'
+ "[Multiverse-Core] Permissions Plugin: " + this.plugin.getMVPerms().getType() + '\n'
+ "[Multiverse-Core] Dumping Config Values: (version " + this.plugin.getMVConfig().getVersion() + ")" + '\n'
+ "[Multiverse-Core] enforceaccess: " + plugin.getMVConfig().getEnforceAccess() + '\n'
+ "[Multiverse-Core] prefixchat: " + plugin.getMVConfig().getPrefixChat() + '\n'
+ "[Multiverse-Core] prefixchatformat: " + plugin.getMVConfig().getPrefixChatFormat() + '\n'
+ "[Multiverse-Core] useasyncchat: " + plugin.getMVConfig().getUseAsyncChat() + '\n'
+ "[Multiverse-Core] teleportintercept: " + plugin.getMVConfig().getTeleportIntercept() + '\n'
+ "[Multiverse-Core] firstspawnoverride: " + plugin.getMVConfig().getFirstSpawnOverride() + '\n'
+ "[Multiverse-Core] displaypermerrors: " + plugin.getMVConfig().getDisplayPermErrors() + '\n'
+ "[Multiverse-Core] enablebuscript: " + plugin.getMVConfig().getEnableBuscript() + '\n'
+ "[Multiverse-Core] globaldebug: " + plugin.getMVConfig().getGlobalDebug() + '\n'
+ "[Multiverse-Core] silentstart: " + plugin.getMVConfig().getSilentStart() + '\n'
+ "[Multiverse-Core] messagecooldown: " + plugin.getMessaging().getCooldown() + '\n'
+ "[Multiverse-Core] version: " + plugin.getMVConfig().getVersion() + '\n'
+ "[Multiverse-Core] firstspawnworld: " + plugin.getMVConfig().getFirstSpawnWorld() + '\n'
+ "[Multiverse-Core] teleportcooldown: " + plugin.getMVConfig().getTeleportCooldown() + '\n'
+ "[Multiverse-Core] defaultportalsearch: " + plugin.getMVConfig().isUsingDefaultPortalSearch() + '\n'
+ "[Multiverse-Core] portalsearchradius: " + plugin.getMVConfig().getPortalSearchRadius() + '\n'
+ "[Multiverse-Core] autopurge: " + plugin.getMVConfig().isAutoPurgeEnabled() + '\n'
+ "[Multiverse-Core] Special Code: FRN002" + '\n';
}
private String getMarkdownString() {
return "# Multiverse-Core" + '\n'
+ "## Overview" + '\n'
+ "| Name | Value |" + '\n'
+ "| --- | --- |" + '\n'
+ "| Multiverse-Core Version | `" + this.plugin.getDescription().getVersion() + "` |" + '\n'
+ "| Bukkit Version | `" + this.plugin.getServer().getVersion() + "` |" + '\n'
+ "| Loaded Worlds | `" + this.plugin.getMVWorldManager().getMVWorlds() + "` |" + '\n'
+ "| Multiverse Plugins Loaded | `" + this.plugin.getPluginCount() + "` |" + '\n'
+ "| Economy being used | `" + plugin.getEconomist().getEconomyName() + "` |" + '\n'
+ "| Permissions Plugin | `" + this.plugin.getMVPerms().getType() + "` |" + '\n'
+ "## Parsed Config" + '\n'
+ "These are what Multiverse thought the in-memory values of the config were." + "\n\n"
+ "| Config Key | Value |" + '\n'
+ "| --- | --- |" + '\n'
+ "| version | `" + this.plugin.getMVConfig().getVersion() + "` |" + '\n'
+ "| messagecooldown | `" + plugin.getMessaging().getCooldown() + "` |" + '\n'
+ "| teleportcooldown | `" + plugin.getMVConfig().getTeleportCooldown() + "` |" + '\n'
+ "| worldnameprefix | `" + plugin.getMVConfig().getPrefixChat() + "` |" + '\n'
+ "| worldnameprefixFormat | `" + plugin.getMVConfig().getPrefixChatFormat() + "` |" + '\n'
+ "| enforceaccess | `" + plugin.getMVConfig().getEnforceAccess() + "` |" + '\n'
+ "| displaypermerrors | `" + plugin.getMVConfig().getDisplayPermErrors() + "` |" + '\n'
+ "| teleportintercept | `" + plugin.getMVConfig().getTeleportIntercept() + "` |" + '\n'
+ "| firstspawnoverride | `" + plugin.getMVConfig().getFirstSpawnOverride() + "` |" + '\n'
+ "| firstspawnworld | `" + plugin.getMVConfig().getFirstSpawnWorld() + "` |" + '\n'
+ "| debug | `" + plugin.getMVConfig().getGlobalDebug() + "` |" + '\n';
}
private void addVersionInfoToEvent(MVVersionEvent event) {
// add the legacy version info
event.appendVersionInfo(this.getLegacyString());
// add the legacy file, but as markdown so it's readable
// TODO Readd this in 5.0.0
// event.putDetailedVersionInfo("version.md", this.getMarkdownString());
// add config.yml
File configFile = new File(this.plugin.getDataFolder(), "config.yml");
event.putDetailedVersionInfo("multiverse-core/config.yml", configFile);
// add worlds.yml
File worldsFile = new File(this.plugin.getDataFolder(), "worlds.yml");
event.putDetailedVersionInfo("multiverse-core/worlds.yml", worldsFile);
"Dumps version info to the console, optionally to pastie.org with -p or pastebin.com with a -b.", PermissionDefault.TRUE);
}
@Override
@@ -129,94 +48,76 @@ public class VersionCommand extends MultiverseCommand {
sender.sendMessage("Version info dumped to console. Please check your server logs.");
}
MVVersionEvent versionEvent = new MVVersionEvent();
StringBuilder buffer = new StringBuilder();
buffer.append("[Multiverse-Core] Multiverse-Core Version: ").append(this.plugin.getDescription().getVersion()).append('\n');
buffer.append("[Multiverse-Core] Bukkit Version: ").append(this.plugin.getServer().getVersion()).append('\n');
buffer.append("[Multiverse-Core] Loaded Worlds: ").append(this.plugin.getMVWorldManager().getMVWorlds()).append('\n');
buffer.append("[Multiverse-Core] Multiverse Plugins Loaded: ").append(this.plugin.getPluginCount()).append('\n');
final boolean usingVault = plugin.getVaultHandler().getEconomy() != null;
buffer.append("[Multiverse-Core] Using Vault: ").append(usingVault).append('\n');
if (usingVault) {
buffer.append("[Multiverse-Core] Economy being used: ").append(plugin.getVaultHandler().getEconomy().getName()).append('\n');
} else {
buffer.append("[Multiverse-Core] Economy being used: ").append(this.plugin.getBank().getEconUsed()).append('\n');
}
buffer.append("[Multiverse-Core] Permissions Plugin: ").append(this.plugin.getMVPerms().getType()).append('\n');
buffer.append("[Multiverse-Core] Dumping Config Values: (version ")
.append(this.plugin.getMVConfig().getVersion()).append(")").append('\n');
buffer.append("[Multiverse-Core] messagecooldown: ").append(plugin.getMessaging().getCooldown()).append('\n');
buffer.append("[Multiverse-Core] teleportcooldown: ").append(plugin.getMVConfig().getTeleportCooldown()).append('\n');
buffer.append("[Multiverse-Core] worldnameprefix: ").append(plugin.getMVConfig().getPrefixChat()).append('\n');
buffer.append("[Multiverse-Core] enforceaccess: ").append(plugin.getMVConfig().getEnforceAccess()).append('\n');
buffer.append("[Multiverse-Core] displaypermerrors: ").append(plugin.getMVConfig().getDisplayPermErrors()).append('\n');
buffer.append("[Multiverse-Core] teleportintercept: ").append(plugin.getMVConfig().getTeleportIntercept()).append('\n');
buffer.append("[Multiverse-Core] firstspawnoverride: ").append(plugin.getMVConfig().getFirstSpawnOverride()).append('\n');
buffer.append("[Multiverse-Core] firstspawnworld: ").append(plugin.getMVConfig().getFirstSpawnWorld()).append('\n');
buffer.append("[Multiverse-Core] debug: ").append(plugin.getMVConfig().getGlobalDebug()).append('\n');
buffer.append("[Multiverse-Core] Special Code: FRN002").append('\n');
this.addVersionInfoToEvent(versionEvent);
MVVersionEvent versionEvent = new MVVersionEvent(buffer.toString());
this.plugin.getServer().getPluginManager().callEvent(versionEvent);
if (CommandHandler.hasFlag("--include-plugin-list", args)) {
versionEvent.appendVersionInfo('\n' + "Plugins: " + getPluginList());
versionEvent.putDetailedVersionInfo("plugins.txt", "Plugins: " + getPluginList());
}
final String versionInfo = versionEvent.getVersionInfo();
versionEvent.putDetailedVersionInfo("version.txt", versionInfo);
final Map<String, String> files = versionEvent.getDetailedVersionInfo();
// log to console
String[] lines = versionInfo.split("\\r?\\n");
final String data = versionEvent.getVersionInfo();
String[] lines = data.split("\n");
for (String line : lines) {
if (!line.isEmpty()) {
this.plugin.getServer().getLogger().info(line);
}
Logging.info(line);
}
BukkitRunnable logPoster = new BukkitRunnable() {
this.plugin.getServer().getScheduler().scheduleAsyncDelayedTask(this.plugin, new Runnable() {
@Override
public void run() {
if (args.size() > 0) {
if (args.size() == 1) {
String pasteUrl;
if (CommandHandler.hasFlag("-b", args)) {
// private post to pastebin
pasteUrl = postToService(PasteServiceType.PASTEBIN, true, versionInfo, files);
} else if (CommandHandler.hasFlag("-g", args)) {
// private post to github
pasteUrl = postToService(PasteServiceType.GITHUB, true, versionInfo, files);
} else if (CommandHandler.hasFlag("-h", args)) {
// private post to hastebin
pasteUrl = postToService(PasteServiceType.HASTEBIN, true, versionInfo, files);
} else if (CommandHandler.hasFlag("-p", args)) {
// private post to paste.gg
pasteUrl = postToService(PasteServiceType.PASTEGG, true, versionInfo, files);
if (args.get(0).equalsIgnoreCase("-p")) {
pasteUrl = postToService(PasteServiceType.PASTIE, true, data); // private post to pastie
} else if (args.get(0).equalsIgnoreCase("-b")) {
pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data); // private post to pastie
} else {
return;
}
if (!(sender instanceof ConsoleCommandSender)) {
sender.sendMessage("Version info dumped here: " + ChatColor.GREEN + pasteUrl);
}
sender.sendMessage("Version info dumped here: " + ChatColor.GREEN + pasteUrl);
Logging.info("Version info dumped here: %s", pasteUrl);
}
}
};
// Run the log posting operation asynchronously, since we don't know how long it will take.
logPoster.runTaskAsynchronously(this.plugin);
});
}
/**
* Send the current contents of this.pasteBinBuffer to a web service.
*
* @param type Service type to send paste data to.
* @param isPrivate Should the paste be marked as private.
* @param pasteData Legacy string only data to post to a service.
* @param pasteFiles Map of filenames/contents of debug info.
* @param type Service type to send to
* @param isPrivate Should the paste be marked as private.
* @return URL of visible paste
*/
private static String postToService(PasteServiceType type, boolean isPrivate, String pasteData, Map<String, String> pasteFiles) {
private static String postToService(PasteServiceType type, boolean isPrivate, String pasteData) {
PasteService ps = PasteServiceFactory.getService(type, isPrivate);
try {
String result;
if (ps.supportsMultiFile()) {
result = ps.postData(pasteFiles);
} else {
result = ps.postData(pasteData);
}
if (SHORTENER != null) return SHORTENER.shorten(result);
return result;
return SHORTENER.shorten(ps.postData(ps.encodeData(pasteData), ps.getPostURL()));
} catch (PasteFailedException e) {
e.printStackTrace();
return "Error posting to service.";
} catch (NullPointerException e) {
e.printStackTrace();
return "That service isn't supported yet.";
System.out.print(e);
return "Error posting to service";
}
}
private String getPluginList() {
return StringUtils.join(plugin.getServer().getPluginManager().getPlugins(), ", ");
}
}
@@ -52,11 +52,11 @@ public class WhoCommand extends MultiverseCommand {
showAll = false;
}
final Collection onlinePlayers = plugin.getServer().getOnlinePlayers();
final Collection<Player> visiblePlayers = new HashSet<Player>(onlinePlayers.size());
for (final Object player : onlinePlayers) {
if (player instanceof Player && (p == null || p.canSee((Player) player))) {
visiblePlayers.add((Player) player);
final Player[] onlinePlayers = plugin.getServer().getOnlinePlayers();
final Collection<Player> visiblePlayers = new HashSet<Player>(onlinePlayers.length);
for (final Player player : onlinePlayers) {
if (p == null || p.canSee(player)) {
visiblePlayers.add(player);
}
}
@@ -2,14 +2,10 @@ package com.onarandombox.MultiverseCore.configuration;
import java.util.Map;
import com.onarandombox.MultiverseCore.utils.MaterialConverter;
import me.main__.util.SerializationConfig.Property;
import me.main__.util.SerializationConfig.SerializationConfig;
import me.main__.util.SerializationConfig.Serializor;
import org.bukkit.Material;
import org.bukkit.configuration.serialization.SerializableAs;
import org.jetbrains.annotations.Nullable;
/**
* Entryfee-settings.
@@ -18,11 +14,8 @@ import org.jetbrains.annotations.Nullable;
public class EntryFee extends SerializationConfig {
@Property
private double amount;
@Property(serializor = EntryFeeCurrencySerializor.class)
@Nullable
private Material currency;
private final Material DISABLED_MATERIAL = Material.AIR;
@Property
private int currency;
public EntryFee() {
super();
@@ -38,7 +31,7 @@ public class EntryFee extends SerializationConfig {
@Override
protected void setDefaults() {
amount = 0D;
currency = null;
currency = -1;
}
/**
@@ -51,11 +44,7 @@ public class EntryFee extends SerializationConfig {
/**
* @return the currency
*/
@Nullable
public Material getCurrency() {
if (currency == null || currency.equals(DISABLED_MATERIAL)) {
return null;
}
public int getCurrency() {
return currency;
}
@@ -71,19 +60,7 @@ public class EntryFee extends SerializationConfig {
* Sets the currency.
* @param currency The new value.
*/
public void setCurrency(@Nullable Material currency) {
public void setCurrency(int currency) {
this.currency = currency;
}
public static final class EntryFeeCurrencySerializor implements Serializor<Material, Object> {
@Override
public String serialize(Material material) {
return material.toString();
}
@Override
public Material deserialize(Object o, Class<Material> aClass) {
return MaterialConverter.convertTypeString(o.toString());
}
}
}
@@ -0,0 +1,37 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2012. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.configuration;
/**
* An "active" {@link MVConfigProperty} that uses the specified method to be "actually" set.
* @param <T> The type of the config-property.
* @deprecated This is deprecated.
* @see MVConfigProperty
*/
@Deprecated
public interface MVActiveConfigProperty<T> extends MVConfigProperty<T> {
/**
* Gets the method that will be executed.
*
* @return The name of the method in MVWorld to be called.
*/
String getMethod();
/**
* Sets the method that will be executed.
*
* @param methodName The name of the method in MVWorld to be called.
*/
void setMethod(String methodName);
/**
* Returns the class of the object we're looking at.
* @return the class of the object we're looking at.
*/
Class<?> getPropertyClass();
}
@@ -0,0 +1,69 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.configuration;
/**
* A generic config-property.
*
* @param <T> The type of the config-property.
* @deprecated This is deprecated.
*/
@Deprecated
public interface MVConfigProperty<T> {
/**
* Gets the name of this property.
*
* @return The name of this property.
*/
String getName();
/**
* Gets the value of this property.
*
* @return The value of this property.
*/
T getValue();
/**
* Gets the string representation of this value.
*
* @return The value of this property as a string.
*/
String toString();
/**
* Gets the help string for this.
*
* @return The value of this property as a string.
*/
String getHelp();
/**
* Sets the value of this property.
*
* @param value The T representation of this value.
* @return True the value was successfully set.
*/
boolean setValue(T value);
/**
* This parseValue should be used with strings.
*
* @param value The string representation of the value to set.
*
* @return True if the value was set, false if not.
*/
boolean parseValue(String value);
/**
* Gets the name of the config-node that this {@link MVConfigProperty} is saved as.
*
* @return The name of the config-node that this {@link MVConfigProperty} is saved as.
*/
String getConfigNode();
}
@@ -9,11 +9,8 @@ package com.onarandombox.MultiverseCore.destination;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
@@ -23,8 +20,7 @@ import org.bukkit.util.Vector;
* A bed-{@link MVDestination}.
*/
public class BedDestination implements MVDestination {
public static final String OWN_BED_STRING = "playerbed";
private String playername = "";
private boolean isValid;
private Location knownBedLoc;
private MultiverseCore plugin;
@@ -43,15 +39,7 @@ public class BedDestination implements MVDestination {
@Override
public boolean isThisType(JavaPlugin plugin, String destination) {
String[] split = destination.split(":");
boolean validFormat = split.length >= 1 && split.length <= 2 && split[0].equals(this.getIdentifier());
OfflinePlayer p = Bukkit.getOfflinePlayer(split[1]);
boolean validPlayer = p.getName() != null && !p.getName().equals(OWN_BED_STRING);
if (validFormat && validPlayer) this.playername = p.getName();
this.isValid = destination.equals("b:" + OWN_BED_STRING) || (validFormat && validPlayer);
this.isValid = split.length >= 1 && split.length <= 2 && split[0].equals(this.getIdentifier());
return this.isValid;
}
@@ -61,13 +49,9 @@ public class BedDestination implements MVDestination {
@Override
public Location getLocation(Entity entity) {
if (entity instanceof Player) {
if (this.playername.isEmpty())
this.knownBedLoc = this.plugin.getBlockSafety().getSafeBedSpawn(((Player) entity).getBedSpawnLocation());
else
this.knownBedLoc = this.plugin.getBlockSafety().getSafeBedSpawn(Bukkit.getOfflinePlayer(this.playername).getBedSpawnLocation());
this.knownBedLoc = this.plugin.getBlockSafety().getSafeBedSpawn(((Player) entity).getBedSpawnLocation());
if (this.knownBedLoc == null) {
((Player) entity).sendMessage("The bed was " + ChatColor.RED + "invalid or blocked" + ChatColor.RESET + ". Sorry.");
((Player) entity).sendMessage("Your bed was " + ChatColor.RED + "invalid or blocked" + ChatColor.RESET + ". Sorry.");
}
return this.knownBedLoc;
}
@@ -136,6 +120,6 @@ public class BedDestination implements MVDestination {
@Override
public String toString() {
return "b:" + (playername.isEmpty() ? OWN_BED_STRING : playername);
return "b:playerbed";
}
}
@@ -1,29 +0,0 @@
package com.onarandombox.MultiverseCore.destination;
import com.onarandombox.MultiverseCore.api.Teleporter;
import com.onarandombox.MultiverseCore.api.MVDestination;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.util.Vector;
public abstract class CustomTeleporterDestination implements MVDestination {
@Override
public final Location getLocation(final Entity entity) {
throw new UnsupportedOperationException();
}
@Override
public final Vector getVelocity() {
throw new UnsupportedOperationException();
}
@Override
public final boolean useSafeTeleporter() {
throw new UnsupportedOperationException();
}
@Override
public abstract String toString();
public abstract Teleporter getTeleporter();
}
@@ -11,26 +11,16 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.commands.TeleportCommand;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import com.onarandombox.MultiverseCore.utils.PlayerFinder;
import com.pneumaticraft.commandhandler.Command;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/** A factory class that will create destinations from specific strings. */
public class DestinationFactory {
private static final Pattern CANNON_PATTERN = Pattern.compile("(?i)cannon-[\\d]+(\\.[\\d]+)?");
private MultiverseCore plugin;
private Map<String, Class<? extends MVDestination>> destList;
private Command teleportCommand;
@@ -46,59 +36,6 @@ public class DestinationFactory {
}
}
/**
* Parse a destination that has relation to sender, such as a cannon or player destination.
*
* @param teleportee The player that is going to be teleported.
* @param destinationName The destination to parse.
* @return A non-null MVDestination
*/
@NotNull
public MVDestination getPlayerAwareDestination(@NotNull Player teleportee,
@NotNull String destinationName) {
// Prioritise world, in the event that a world is named after a player online.
if (Bukkit.getWorld(destinationName) != null) {
return getDestination(destinationName);
}
Player targetPlayer = PlayerFinder.get(destinationName, teleportee);
if (targetPlayer != null) {
return getDestination("pl:" + targetPlayer.getName());
}
if (CANNON_PATTERN.matcher(destinationName).matches()) {
return getDestination(parseCannonDest(teleportee, destinationName));
}
return getDestination(destinationName);
}
/**
* Parses a cannon destination.
*
* @param teleportee The player that is going to be teleported.
* @param destinationName The destination to parse.
* @return A destination string.
*/
@NotNull
private String parseCannonDest(@NotNull Player teleportee,
@NotNull String destinationName) {
String[] cannonSpeed = destinationName.split("-");
try {
double speed = Double.parseDouble(cannonSpeed[1]);
destinationName = "ca:" + teleportee.getWorld().getName() + ":" + teleportee.getLocation().getX()
+ "," + teleportee.getLocation().getY() + "," + teleportee.getLocation().getZ() + ":"
+ teleportee.getLocation().getPitch() + ":" + teleportee.getLocation().getYaw() + ":" + speed;
}
catch (Exception e) {
destinationName = "i:invalid";
}
return destinationName;
}
/**
* Gets a new destination from a string.
* Returns a new InvalidDestination if the string could not be parsed.
@@ -21,10 +21,9 @@ import java.util.List;
* An exact {@link MVDestination}.
*/
public class ExactDestination implements MVDestination {
private final String coordRegex = "(-?[\\d]+\\.?[\\d]*|~-?[\\d]+\\.?[\\d]*|~),(-?[\\d]+\\.?[\\d]*|~-?[\\d]+\\.?[\\d]*|~),(-?[\\d]+\\.?[\\d]*|~-?[\\d]+\\.?[\\d]*|~)";
private final String coordRegex = "(-?[\\d]+\\.?[\\d]*),(-?[\\d]+\\.?[\\d]*),(-?[\\d]+\\.?[\\d]*)";
private boolean isValid;
private Location location;
private boolean relativeX, relativeY, relativeZ;
/**
* {@inheritDoc}
@@ -89,20 +88,7 @@ public class ExactDestination implements MVDestination {
*/
@Override
public Location getLocation(Entity e) {
Location loc = this.location.clone();
if (relativeX || relativeY || relativeZ) {
Location eLoc = e.getLocation();
loc.add(relativeX ? eLoc.getX() : 0, relativeY ? eLoc.getY() : 0, relativeZ ? eLoc.getZ() : 0);
// Since the location is relative, it makes sense to use the entity's pitch and yaw unless those were
// specified in the destination.
if (loc.getPitch() == 0) {
loc.setPitch(eLoc.getPitch());
}
if (loc.getYaw() == 0) {
loc.setYaw(eLoc.getYaw());
}
}
return loc;
return this.location;
}
/**
@@ -148,42 +134,11 @@ public class ExactDestination implements MVDestination {
double[] coords = new double[3];
String[] coordString = parsed.get(2).split(",");
for (int i = 0; i < 3; i++) {
String[] relSplit = coordString[i].split("~");
boolean relative = false;
if (relSplit.length == 0) {
// coord is "~" form
relative = true;
coords[i] = 0;
} else if (relSplit.length == 1) {
// coord is "123" form
try {
coords[i] = Double.parseDouble(relSplit[0]);
} catch (NumberFormatException e) {
this.isValid = false;
return;
}
} else {
// coord is "~123" form
relative = true;
try {
coords[i] = Double.parseDouble(relSplit[1]);
} catch (NumberFormatException e) {
this.isValid = false;
return;
}
}
if (relative) {
switch (i) {
case 0:
relativeX = true;
break;
case 1:
relativeY = true;
break;
case 2:
relativeZ = true;
break;
}
try {
coords[i] = Double.parseDouble(coordString[i]);
} catch (NumberFormatException e) {
this.isValid = false;
return;
}
}
this.location.setX(coords[0]);
@@ -229,7 +184,11 @@ public class ExactDestination implements MVDestination {
* @param location The {@link Location}.
*/
public void setDestination(Location location) {
this.isValid = (this.location = location) != null;
if (location != null) {
this.location = location;
this.isValid = true;
}
this.isValid = false;
}
/**
@@ -50,7 +50,7 @@ public class PlayerDestination implements MVDestination {
*/
@Override
public Location getLocation(Entity e) {
Player p = plugin.getServer().getPlayerExact(this.player);
Player p = plugin.getServer().getPlayer(this.player);
Player plLoc = null;
if (e instanceof Player) {
plLoc = (Player) e;
@@ -43,8 +43,4 @@ public enum AllowedPortalType {
public PortalType getActualPortalType() {
return this.type;
}
public boolean isPortalAllowed(PortalType portalType) {
return this != NONE && (getActualPortalType() == portalType || this == ALL);
}
}
@@ -1,7 +0,0 @@
package com.onarandombox.MultiverseCore.enums;
public enum RespawnType {
BED,
ANCHOR,
OTHER
}
@@ -1,43 +0,0 @@
package com.onarandombox.MultiverseCore.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Called when Core's debug level is changed.
*/
public class MVDebugModeEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList();
private final int level;
public MVDebugModeEvent(int level) {
this.level = level;
}
/**
* {@inheritDoc}
*/
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
/**
* Gets the handler list. This is required by the event system.
* @return A list of HANDLERS.
*/
public static HandlerList getHandlerList() {
return HANDLERS;
}
/**
* Returns the current debug level of Core.
*
* @return the current debug level of Core.
*/
public int getLevel() {
return level;
}
}
@@ -1,29 +1,17 @@
package com.onarandombox.MultiverseCore.event;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Called when somebody requests version information about Multiverse.
*/
public class MVVersionEvent extends Event {
private final StringBuilder versionInfoBuilder;
private final Map<String, String> detailedVersionInfo;
public MVVersionEvent() {
versionInfoBuilder = new StringBuilder();
detailedVersionInfo = new HashMap<>();
public MVVersionEvent(String versionInfo) {
this.versionInfoBuilder = new StringBuilder(versionInfo);
}
private static final HandlerList HANDLERS = new HandlerList();
@@ -52,21 +40,6 @@ public class MVVersionEvent extends Event {
return this.versionInfoBuilder.toString();
}
/**
* Gets the key/value pair of the detailed version info.
*
* This information is used for advanced paste services that would prefer
* to get the information as several files. Examples include config.yml or
* portals.yml. Note that the map returned is immutable.
*
* The keys are filenames, the values are the contents of the files.
*
* @return The immutable key value mapping of files and the contents of those files.
*/
public Map<String, String> getDetailedVersionInfo() {
return Collections.unmodifiableMap(this.detailedVersionInfo);
}
/**
* Appends more version-info to the version-info currently saved in this event.
* @param moreVersionInfo The version-info to add. Should end with '\n'.
@@ -74,46 +47,4 @@ public class MVVersionEvent extends Event {
public void appendVersionInfo(String moreVersionInfo) {
this.versionInfoBuilder.append(moreVersionInfo);
}
private String readFile(final String filename) {
StringBuilder result;
try {
FileReader reader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
result = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
result.append(line).append("\n");
}
} catch (FileNotFoundException e) {
Logging.severe("Unable to find %s. Here's the traceback: %s", filename, e.getMessage());
e.printStackTrace();
result = new StringBuilder(String.format("ERROR: Could not load: %s", filename));
} catch (IOException e) {
Logging.severe("Something bad happend when reading %s. Here's the traceback: %s", filename, e.getMessage());
e.printStackTrace();
result = new StringBuilder(String.format("ERROR: Could not load: %s", filename));
}
return result.toString();
}
/**
* Adds a file to to the detailed version-info currently saved in this event.
* @param fileName The name of the file.
* @param contents The contents of the file.
*/
public void putDetailedVersionInfo(String fileName, String contents) {
this.detailedVersionInfo.put(fileName, contents);
}
/**
* Adds a file to to the detailed version-info currently saved in this event.
* @param filename The name of the file.
* @param file The file.
*/
public void putDetailedVersionInfo(String filename, File file) {
this.putDetailedVersionInfo(filename, readFile(file.getAbsolutePath()));
}
}
@@ -1,311 +0,0 @@
package com.onarandombox.MultiverseCore.generators;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.GeneratorPlugin;
import com.onarandombox.MultiverseCore.api.MVGeneratorManager;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
/**
* Default implementation of {@link MVGeneratorManager} to facilitate the detection and management of generator
* plugins installed on user's server.
*/
public class GeneratorManager implements MVGeneratorManager {
private final MultiverseCore plugin;
private final Map<String, String> defaultGens;
private Map<String, GeneratorPlugin> generatorPluginMap;
public GeneratorManager(MultiverseCore plugin) {
this.plugin = plugin;
this.defaultGens = new HashMap<>();
loadDefaultWorldGenerators();
findAndRegisterAllGeneratorPlugins();
Bukkit.getPluginManager().registerEvents(new GeneratorListener(), this.plugin);
}
/**
* Loads default generator strings defined in 'bukkit.yml'.
*/
private void loadDefaultWorldGenerators() {
this.generatorPluginMap = new HashMap<>();
File[] files = this.plugin.getServerFolder().listFiles((file, s) -> s.equalsIgnoreCase("bukkit.yml"));
if (files == null || files.length != 1) {
Logging.fine("Could not read 'bukkit.yml'. Any Default worldgenerators will not be loaded!");
return;
}
FileConfiguration bukkitConfig = YamlConfiguration.loadConfiguration(files[0]);
if (!bukkitConfig.isConfigurationSection("worlds")) {
Logging.fine("'bukkit.yml' missing worlds config section. No default generators found!");
return;
}
Set<String> keys = bukkitConfig.getConfigurationSection("worlds").getKeys(false);
for (String key : keys) {
this.defaultGens.put(key, bukkitConfig.getString("worlds." + key + ".generator", ""));
}
this.generatorPluginMap = Collections.unmodifiableMap(this.generatorPluginMap);
}
/**
* Register all generator plugins detected.
*/
private void findAndRegisterAllGeneratorPlugins() {
Arrays.stream(Bukkit.getPluginManager().getPlugins()).forEach(this::register);
}
/**
* Attempts to register a plugin as {@link SimpleGeneratorPlugin}.
*
* @param genPlugin The plugin to register.
* @return True if registered successfully, else false.
*/
private boolean register(@NotNull Plugin genPlugin) {
return this.register(genPlugin, SimpleGeneratorPlugin.DEFAULT_TEST_ID);
}
/**
* Attempts to register a plugin as {@link SimpleGeneratorPlugin}.
*
* @param genPlugin The plugin to register.
* @param id Generator Id to test for valid chunk generator.
* @return True if registered successfully, else false.
*/
private boolean register(@NotNull Plugin genPlugin, String id) {
Logging.finer("Attempting to register %s as a generator...", genPlugin.getName());
if (this.isGeneratorPlugin(genPlugin)) {
return false;
}
if (!simpleTestGen(genPlugin, id)) {
Logging.finer("%s is probably not a generator plugin!", genPlugin.getName());
return false;
}
this.generatorPluginMap.put(genPlugin.getName(), new SimpleGeneratorPlugin(genPlugin));
Logging.finer("Registered %s as a simple generator plugin.", genPlugin.getName());
return true;
}
/**
* Basic test to see if plugin is a valid generator.
*
* @param generator The potential generator plugin.
* @param id Generator Id to test for valid chunk generator.
* @return True if plugin is a valid generator, else false.
*/
private boolean simpleTestGen(@Nullable Plugin generator, String id) {
if (generator == null) {
return false;
}
// Since we are unsure if the plugin is even suppose to be a generator, we assume any error means its
// not a generator plugin.
try {
return generator.getDefaultWorldGenerator(SimpleGeneratorPlugin.TEST_WORLDNAME, id) != null;
} catch (Exception ignore) {
return false;
}
}
/**
* Unregisters a plugin.
*
* @param genPlugin The plugin to unregister.
* @return True if the plugin was present and now unregistered, else false.
*/
private boolean unregister(@NotNull Plugin genPlugin) {
return this.generatorPluginMap.remove(genPlugin.getName()) != null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean register(@NotNull GeneratorPlugin generatorPlugin) {
Plugin genPlugin = generatorPlugin.getPlugin();
// Make sure not registered before.
GeneratorPlugin registeredGeneratorPlugin = this.getGeneratorPlugin(genPlugin);
if (registeredGeneratorPlugin != null) {
if (!(registeredGeneratorPlugin instanceof SimpleGeneratorPlugin)) {
throw new IllegalStateException("You cannot register plugin for '" + genPlugin.getName() + "' twice!");
}
// If it's auto registration by MV, we can remove in favour of the custom one.
this.unregister(genPlugin);
}
if (this.safelyTestGenerator(genPlugin, generatorPlugin::getDefaultChunkGenerator) != TestResult.VALID) {
return false;
}
this.generatorPluginMap.put(genPlugin.getName(), generatorPlugin);
Logging.fine("Registered %s as a simple generator plugin.", genPlugin.getName());
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValidGenerator(@NotNull String genString, @NotNull String worldName) {
return validateGenerator(genString, worldName) == TestResult.VALID;
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public TestResult validateGenerator(@NotNull String genString, @NotNull String worldName) {
String[] genArray = genString.split(":", 2);
String pluginName = genArray[0];
String id = (genArray.length == 1) ? "" : genArray[1];
Plugin genPlugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (genPlugin == null) {
return TestResult.PLUGIN_DOES_NOT_EXIST;
}
if (!this.isGeneratorPlugin(genPlugin)) {
// Tries to register again with specific Id defined.
if (!this.register(genPlugin, id)) {
return TestResult.INVALID_GENERATOR;
}
}
GeneratorPlugin generatorPlugin = this.getGeneratorPlugin(genPlugin);
if (generatorPlugin == null) {
return TestResult.INVALID_GENERATOR;
}
TestResult testResult = safelyTestGenerator(generatorPlugin.getPlugin(), () -> generatorPlugin.getChunkGenerator(id, worldName));
if (testResult == TestResult.VALID && generatorPlugin instanceof SimpleGeneratorPlugin) {
((SimpleGeneratorPlugin) generatorPlugin).addKnownWorkingId(id);
}
return testResult;
}
/**
* Tries to get chunk generator with wrapper to catch any exceptions that may occur.
*
* @param genPlugin The generator plugin.
* @param genGetter Logic to get the chunk generator.
* @return VALID if successfully got a not-null chunk generator, INVALID_GENERATOR if null,
* ERRORS if exception is thrown.
*/
@NotNull
private TestResult safelyTestGenerator(Plugin genPlugin, Callable<ChunkGenerator> genGetter) {
TestResult result = this.plugin.getUnsafeCallWrapper().wrap(
() -> genGetter.call() == null ? TestResult.INVALID_GENERATOR : TestResult.VALID,
genPlugin.getName(),
"Failed to get the chunk generator: %s"
);
return (result == null) ? TestResult.ERRORS : result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isGeneratorPlugin(@NotNull Plugin genPlugin) {
return this.isGeneratorPlugin(genPlugin.getName());
}
/**
* {@inheritDoc}
*/
@Override
public boolean isGeneratorPlugin(@NotNull String pluginName) {
return this.generatorPluginMap.containsKey(pluginName);
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public GeneratorPlugin getGeneratorPlugin(@NotNull Plugin genPlugin) {
return this.getGeneratorPlugin(genPlugin.getName());
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public GeneratorPlugin getGeneratorPlugin(@NotNull String pluginName) {
return this.generatorPluginMap.get(pluginName);
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public Collection<GeneratorPlugin> getGeneratorPlugins() {
return this.generatorPluginMap.values();
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public Collection<String> getGeneratorPluginNames() {
return this.generatorPluginMap.keySet();
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public String getDefaultWorldGen(String worldName) {
return this.defaultGens.get(worldName);
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public Map<String, String> getDefaultWorldGens() {
return this.defaultGens;
}
/**
* Listen to when a plugin enables/disable to register and unregister accordingly.
*/
private class GeneratorListener implements Listener {
@EventHandler
public void onEnable(PluginEnableEvent event) {
register(event.getPlugin());
}
@EventHandler
public void onDisable(PluginDisableEvent event) {
unregister(event.getPlugin());
}
}
}
@@ -1,94 +0,0 @@
package com.onarandombox.MultiverseCore.generators;
import com.onarandombox.MultiverseCore.api.GeneratorPlugin;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* A default implementation of {@link GeneratorPlugin} for those generator plugins that do not provide their own
* custom {@link GeneratorPlugin} implementation to Multiverse.
*/
public class SimpleGeneratorPlugin implements GeneratorPlugin {
public static String TEST_WORLDNAME = "test";
public static String DEFAULT_TEST_ID = "";
private final Plugin plugin;
private final List<String> workingIds;
SimpleGeneratorPlugin(Plugin plugin) {
this(plugin, DEFAULT_TEST_ID);
}
SimpleGeneratorPlugin(Plugin plugin, String testedId) {
this.plugin = plugin;
this.workingIds = new ArrayList<>();
this.workingIds.add(testedId);
}
/**
* Adds a known generator id that was tested to be working.
*
* @param id The known working generator id.
*/
void addKnownWorkingId(String id) {
if (!this.workingIds.contains(id)) {
this.workingIds.add(id);
}
}
/**
* {@inheritDoc}
*/
@Override
public @NotNull Collection<String> suggestIds(@Nullable String currentIdInput) {
return this.workingIds;
}
/**
* {@inheritDoc}
*/
@Override
public @Nullable ChunkGenerator getDefaultChunkGenerator() throws Exception {
return this.plugin.getDefaultWorldGenerator(TEST_WORLDNAME, this.workingIds.get(0));
}
/**
* {@inheritDoc}
*/
@Override
public @Nullable ChunkGenerator getChunkGenerator(String id, String worldName) throws Exception {
return this.plugin.getDefaultWorldGenerator(worldName, id);
}
/**
* {@inheritDoc}
*/
@Override
public @Nullable Collection<String> getExampleUsages() {
return null;
}
/**
* {@inheritDoc}
* @return
*/
@Override
public @Nullable String getInfoLink() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public @NotNull Plugin getPlugin() {
return this.plugin;
}
}
@@ -9,7 +9,6 @@ package com.onarandombox.MultiverseCore.listeners;
import java.util.logging.Level;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerChatEvent;
@@ -21,7 +20,7 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
public class MVAsyncPlayerChatListener extends MVChatListener {
public MVAsyncPlayerChatListener(MultiverseCore plugin, MVPlayerListener playerListener) {
super(plugin, playerListener);
Logging.fine("Created AsyncPlayerChatEvent listener.");
plugin.log(Level.FINE, "Created AsyncPlayerChatEvent listener.");
}
/**
@@ -3,8 +3,6 @@ package com.onarandombox.MultiverseCore.listeners;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import org.bukkit.ChatColor;
import org.bukkit.event.Listener;
/**
@@ -47,13 +45,8 @@ public abstract class MVChatListener implements Listener {
return;
}
prefix = mvworld.getColoredWorldString();
String chat = event.getFormat();
String prefixChatFormat = plugin.getMVConfig().getPrefixChatFormat();
prefixChatFormat = prefixChatFormat.replace("%world%", prefix).replace("%chat%", chat);
prefixChatFormat = ChatColor.translateAlternateColorCodes('&', prefixChatFormat);
event.setFormat(prefixChatFormat);
String format = event.getFormat();
event.setFormat("[" + prefix + "]" + format);
}
}
}
@@ -7,7 +7,6 @@
package com.onarandombox.MultiverseCore.listeners;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
@@ -99,7 +98,7 @@ public class MVEntityListener implements Listener {
* Handle people with non-standard animals: ie a patched craftbukkit.
*/
if (type == null || type.getName() == null) {
Logging.finer("Found a null typed creature.");
this.plugin.log(Level.FINER, "Found a null typed creature.");
return;
}
@@ -29,7 +29,7 @@ public class MVMapListener implements Listener {
public void mapInitialize(final MapInitializeEvent event) {
for (final Player player : Bukkit.getOnlinePlayers()) {
if ((player.getItemInHand().getType() == Material.MAP
|| player.getItemInHand().getType() == Material.FILLED_MAP)
|| player.getItemInHand().getType() == Material.EMPTY_MAP)
&& player.getItemInHand().getDurability() == event.getMap().getId()) {
final Location playerLoc = player.getLocation();
final MapView map = event.getMap();
@@ -9,7 +9,6 @@ package com.onarandombox.MultiverseCore.listeners;
import java.util.logging.Level;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerChatEvent;
@@ -22,7 +21,7 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
public class MVPlayerChatListener extends MVChatListener {
public MVPlayerChatListener(MultiverseCore plugin, MVPlayerListener playerListener) {
super(plugin, playerListener);
Logging.fine("Registered PlayerChatEvent listener.");
plugin.log(Level.FINE, "Registered PlayerChatEvent listener.");
}
/**
@@ -7,17 +7,11 @@
package com.onarandombox.MultiverseCore.listeners;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.enums.RespawnType;
import com.onarandombox.MultiverseCore.event.MVRespawnEvent;
import com.onarandombox.MultiverseCore.utils.CompatibilityLayer;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import org.bukkit.GameMode;
import org.bukkit.Location;
@@ -35,6 +29,10 @@ import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
/**
* Multiverse's {@link Listener} for players.
*/
@@ -71,16 +69,9 @@ public class MVPlayerListener implements Listener {
return;
}
RespawnType respawnType = RespawnType.OTHER;
if (event.isBedSpawn()) {
respawnType = RespawnType.BED;
}
if (CompatibilityLayer.isAnchorSpawn(event)) {
respawnType = RespawnType.ANCHOR;
}
if (mvWorld.getBedRespawn() && (respawnType == RespawnType.BED || respawnType == RespawnType.ANCHOR)) {
Logging.fine("Spawning %s at their %s", event.getPlayer().getName(), respawnType);
if (mvWorld.getBedRespawn() && event.isBedSpawn()) {
this.plugin.log(Level.FINE, "Spawning " + event.getPlayer().getName() + " at their bed");
return;
}
@@ -119,15 +110,15 @@ public class MVPlayerListener implements Listener {
public void playerJoin(PlayerJoinEvent event) {
Player p = event.getPlayer();
if (!p.hasPlayedBefore()) {
Logging.finer("Player joined for the FIRST time!");
this.plugin.log(Level.FINER, "Player joined for the FIRST time!");
if (plugin.getMVConfig().getFirstSpawnOverride()) {
Logging.fine("Moving NEW player to(firstspawnoverride): "
this.plugin.log(Level.FINE, "Moving NEW player to(firstspawnoverride): "
+ worldManager.getFirstSpawnWorld().getSpawnLocation());
this.sendPlayerToDefaultWorld(p);
}
return;
} else {
Logging.finer("Player joined AGAIN!");
this.plugin.log(Level.FINER, "Player joined AGAIN!");
if (this.plugin.getMVConfig().getEnforceAccess() // check this only if we're enforcing access!
&& !this.plugin.getMVPerms().hasPermission(p, "multiverse.access." + p.getWorld().getName(), false)) {
p.sendMessage("[MV] - Sorry you can't be in this world anymore!");
@@ -165,7 +156,7 @@ public class MVPlayerListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void playerTeleport(PlayerTeleportEvent event) {
Logging.finer("Got teleport event for player '"
this.plugin.log(Level.FINER, "Got teleport event for player '"
+ event.getPlayer().getName() + "' with cause '" + event.getCause() + "'");
if (event.isCancelled()) {
return;
@@ -175,25 +166,21 @@ public class MVPlayerListener implements Listener {
String teleporterName = MultiverseCore.getPlayerTeleporter(teleportee.getName());
if (teleporterName != null) {
if (teleporterName.equals("CONSOLE")) {
Logging.finer("We know the teleporter is the console! Magical!");
this.plugin.log(Level.FINER, "We know the teleporter is the console! Magical!");
teleporter = this.plugin.getServer().getConsoleSender();
} else {
teleporter = this.plugin.getServer().getPlayerExact(teleporterName);
teleporter = this.plugin.getServer().getPlayer(teleporterName);
}
}
Logging.finer("Inferred sender '" + teleporter + "' from name '"
this.plugin.log(Level.FINER, "Inferred sender '" + teleporter + "' from name '"
+ teleporterName + "', fetched from name '" + teleportee.getName() + "'");
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (toWorld == null) {
Logging.fine("Player '" + teleportee.getName() + "' is teleporting to world '"
+ event.getTo().getWorld().getName() + "' which is not managed by Multiverse-Core. No further "
+ "actions will be taken by Multiverse-Core.");
if (fromWorld == null || toWorld == null)
return;
}
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Teleporting to the same world.
Logging.finer("Player '" + teleportee.getName() + "' is teleporting to the same world.");
this.plugin.log(Level.FINER, "Player '" + teleportee.getName() + "' is teleporting to the same world.");
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
return;
}
@@ -201,7 +188,7 @@ public class MVPlayerListener implements Listener {
// Charge the teleporter
event.setCancelled(!pt.playerHasMoneyToEnter(fromWorld, toWorld, teleporter, teleportee, true));
if (event.isCancelled() && teleporter != null) {
Logging.fine("Player '" + teleportee.getName()
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have the FUNDS required to enter it.");
@@ -212,14 +199,14 @@ public class MVPlayerListener implements Listener {
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, teleporter, teleportee));
if (event.isCancelled() && teleporter != null) {
Logging.fine("Player '" + teleportee.getName()
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have: multiverse.access." + event.getTo().getWorld().getName());
return;
}
} else {
Logging.fine("Player '" + teleportee.getName()
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was allowed to go to '" + toWorld.getAlias() + "' because enforceaccess is off.");
}
@@ -229,7 +216,7 @@ public class MVPlayerListener implements Listener {
if (toWorld.getCBWorld().getPlayers().size() >= toWorld.getPlayerLimit()) {
// Ouch the world is full, lets see if the player can bypass that limitation
if (!pt.playerCanBypassPlayerLimit(toWorld, teleporter, teleportee)) {
Logging.fine("Player '" + teleportee.getName()
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because the world is full and '" + teleporter.getName()
+ "' doesn't have: mv.bypass.playerlimit." + event.getTo().getWorld().getName());
@@ -244,7 +231,7 @@ public class MVPlayerListener implements Listener {
}
private void stateSuccess(String playerName, String worldName) {
Logging.fine("MV-Core is allowing Player '" + playerName
this.plugin.log(Level.FINE, "MV-Core is allowing Player '" + playerName
+ "' to go to '" + worldName + "'.");
}
@@ -261,7 +248,7 @@ public class MVPlayerListener implements Listener {
// REMEMBER! getTo MAY be NULL HERE!!!
// If the player was actually outside of the portal, adjust the from location
if (event.getFrom().getWorld().getBlockAt(event.getFrom()).getType() != Material.NETHER_PORTAL) {
if (event.getFrom().getWorld().getBlockAt(event.getFrom()).getType() != Material.PORTAL) {
Location newloc = this.plugin.getSafeTTeleporter().findPortalBlockNextTo(event.getFrom());
// TODO: Fix this. Currently, we only check for PORTAL blocks. I'll have to figure out what
// TODO: we want to do here.
@@ -291,12 +278,12 @@ public class MVPlayerListener implements Listener {
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Portaling to the same world.
Logging.finer("Player '" + event.getPlayer().getName() + "' is portaling to the same world.");
this.plugin.log(Level.FINER, "Player '" + event.getPlayer().getName() + "' is portaling to the same world.");
return;
}
event.setCancelled(!pt.playerHasMoneyToEnter(fromWorld, toWorld, event.getPlayer(), event.getPlayer(), true));
if (event.isCancelled()) {
Logging.fine("Player '" + event.getPlayer().getName()
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName()
+ "' was DENIED ACCESS to '" + event.getTo().getWorld().getName()
+ "' because they don't have the FUNDS required to enter.");
return;
@@ -304,25 +291,17 @@ public class MVPlayerListener implements Listener {
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, event.getPlayer(), event.getPlayer()));
if (event.isCancelled()) {
Logging.fine("Player '" + event.getPlayer().getName()
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName()
+ "' was DENIED ACCESS to '" + event.getTo().getWorld().getName()
+ "' because they don't have: multiverse.access." + event.getTo().getWorld().getName());
}
} else {
Logging.fine("Player '" + event.getPlayer().getName()
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName()
+ "' was allowed to go to '" + event.getTo().getWorld().getName()
+ "' because enforceaccess is off.");
}
if (!plugin.getMVConfig().isUsingDefaultPortalSearch()) {
try {
Class.forName("org.bukkit.TravelAgent");
if (event.getPortalTravelAgent() != null) {
event.getPortalTravelAgent().setSearchRadius(plugin.getMVConfig().getPortalSearchRadius());
}
} catch (ClassNotFoundException ignore) {
Logging.fine("TravelAgent not available for PlayerPortalEvent for " + event.getPlayer().getName());
}
if (!plugin.getMVConfig().isUsingDefaultPortalSearch() && event.getPortalTravelAgent() != null) {
event.getPortalTravelAgent().setSearchRadius(plugin.getMVConfig().getPortalSearchRadius());
}
}
@@ -344,7 +323,7 @@ public class MVPlayerListener implements Listener {
if (mvWorld != null) {
this.handleGameModeAndFlight(player, mvWorld);
} else {
Logging.finer("Not handling gamemode and flight for world '" + world.getName()
this.plugin.log(Level.FINER, "Not handling gamemode and flight for world '" + world.getName()
+ "' not managed by Multiverse.");
}
}
@@ -385,7 +364,7 @@ public class MVPlayerListener implements Listener {
player.getName(), player.getWorld().getName(), world.getName());
}
} else {
Logging.fine("Player: " + player.getName() + " is IMMUNE to gamemode changes!");
MVPlayerListener.this.plugin.log(Level.FINE, "Player: " + player.getName() + " is IMMUNE to gamemode changes!");
}
}
}, 1L);
@@ -0,0 +1,63 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.listeners;
import com.fernferret.allpay.AllPay;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import java.util.Arrays;
/**
* Multiverse's Plugin {@link Listener}.
*/
public class MVPluginListener implements Listener {
private MultiverseCore plugin;
public MVPluginListener(MultiverseCore plugin) {
this.plugin = plugin;
}
/**
* Keep an eye out for Plugins which we can utilize.
* @param event The event.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void pluginEnable(PluginEnableEvent event) {
if (plugin.getVaultHandler().getEconomy() != null) {
// Don't hook 2 economy plugins.
return;
}
// Let AllPay handle all econ plugin loadings, only go for econ plugins we support
if (Arrays.asList(AllPay.getValidEconPlugins()).contains(event.getPlugin().getDescription().getName())) {
this.plugin.setBank(this.plugin.getBanker().loadEconPlugin());
}
/*
if (event.getPlugin().getDescription().getName().equals("Spout")) {
this.plugin.setSpout();
this.plugin.log(Level.INFO, "Spout integration enabled.");
}
*/
}
/**
* We'll check if any of the plugins we rely on decide to Disable themselves.
* @param event The event.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void pluginDisable(PluginDisableEvent event) {
// TODO: Disable econ when it disables.
}
}
@@ -7,20 +7,17 @@
package com.onarandombox.MultiverseCore.listeners;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.enums.AllowedPortalType;
import org.bukkit.Material;
import org.bukkit.PortalType;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityCreatePortalEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.PortalCreateEvent;
import java.util.logging.Level;
/**
* A custom listener for portal related events.
*/
@@ -42,9 +39,9 @@ public class MVPortalListener implements Listener {
if (event.isCancelled() || event.getBlocks().size() == 0) {
return;
}
MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(event.getEntity().getWorld());
MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(event.getBlocks().get(0).getWorld());
// We have to do it like this due to a bug in 1.1-R3
if (world != null && !world.getAllowedPortals().isPortalAllowed(event.getPortalType())) {
if (cancelPortalEvent(world, event.getPortalType())) {
event.setCancelled(true);
}
}
@@ -53,35 +50,36 @@ public class MVPortalListener implements Listener {
* This is called when a portal is created as the result of another world being linked.
* @param event The event where a portal was formed due to a world link
*/
@EventHandler(ignoreCancelled = true)
@EventHandler
public void portalForm(PortalCreateEvent event) {
MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(event.getWorld());
if (world != null && !world.getAllowedPortals().isPortalAllowed(PortalType.NETHER)) {
Logging.fine("Cancelling creation of nether portal because portalForm disallows.");
if (event.isCancelled() || event.getBlocks().size() == 0) {
return;
}
// There's no type attribute (as of 1.1-R1), so we have to iterate.
for (Block b : event.getBlocks()) {
if (b.getType() == Material.PORTAL) {
MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(b.getWorld());
if (cancelPortalEvent(world, PortalType.NETHER)) {
event.setCancelled(true);
return;
}
}
}
// If We're here, then the Portal was an Ender type:
MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(event.getBlocks().get(0).getWorld());
if (cancelPortalEvent(world, PortalType.ENDER)) {
event.setCancelled(true);
}
}
/**
* This method will prevent ender portals from being created in worlds where they are not allowed due to portalForm.
*
* @param event The player interact event.
*/
@EventHandler(ignoreCancelled = true)
public void portalForm(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
if (event.getClickedBlock().getType() != Material.END_PORTAL_FRAME) {
return;
}
if (event.getItem() == null || event.getItem().getType() != Material.ENDER_EYE) {
return;
}
MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(event.getPlayer().getWorld());
if (world != null && !world.getAllowedPortals().isPortalAllowed(PortalType.ENDER)) {
Logging.fine("Cancelling creation of ender portal because portalForm disallows.");
event.setCancelled(true);
private static boolean cancelPortalEvent(MultiverseWorld world, PortalType type) {
if (world.getAllowedPortals() == AllowedPortalType.NONE) {
return true;
} else if (world.getAllowedPortals() != AllowedPortalType.ALL) {
if (type != world.getAllowedPortals().getActualPortalType()) {
return true;
}
}
return false;
}
}
@@ -1,29 +0,0 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.listeners;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent;
public class MVWorldInitListener implements Listener {
MultiverseCore plugin;
public MVWorldInitListener(MultiverseCore plugin) {
this.plugin = plugin;
}
@EventHandler
public void initWorld(WorldInitEvent event) {
if (!plugin.getMVWorldManager().isKeepingSpawnInMemory(event.getWorld())) {
event.getWorld().setKeepSpawnInMemory(false);
}
}
}
@@ -1,67 +0,0 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.listeners;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
/**
* Multiverse's World {@link Listener}.
*/
public class MVWorldListener implements Listener {
private MultiverseCore plugin;
private MVWorldManager worldManager;
public MVWorldListener(MultiverseCore plugin) {
this.plugin = plugin;
this.worldManager = plugin.getMVWorldManager();
}
/**
* This method is called when Bukkit fires off a WorldUnloadEvent.
* @param event The Event that was fired.
*/
@EventHandler
public void unloadWorld(WorldUnloadEvent event) {
if (event.isCancelled()) {
return;
}
if (event.getWorld() instanceof World) {
World world = (World) event.getWorld();
if (world != null) {
this.plugin.getMVWorldManager().unloadWorld(world.getName(), false);
}
}
}
/**
* This method is called when Bukkit fires off a WorldLoadEvent.
* @param event The Event that was fired.
*/
@EventHandler
public void loadWorld(WorldLoadEvent event) {
World world = event.getWorld();
if (world != null) {
if (this.plugin.getMVWorldManager().getUnloadedWorlds().contains(world.getName())) {
this.plugin.getMVWorldManager().loadWorld(world.getName());
}
MultiverseWorld mvWorld = plugin.getMVWorldManager().getMVWorld(world);
if (mvWorld != null) {
// This is where we can temporarily fix those pesky property issues!
world.setPVP(mvWorld.isPVPEnabled());
world.setDifficulty(mvWorld.getDifficulty());
}
}
}
}
@@ -0,0 +1,52 @@
package com.onarandombox.MultiverseCore.permissions;
import org.bukkit.Bukkit;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.PermissionDefault;
/**
* Provides improved parent-child relationships for permissions. This is the standard implementation of {@link PermissionNode}.
* <p>
* Apparently parents override their children in Bukkit:
* Let {@code permissionA} be a parent permission of {@code permissionB}, setting {@code permissionB} to {@code true}.
* Now a player has {@code permissionA=true} and {@code permissionB=false}. Result: Both are {@code true}.
* Another player has {@code permissionA=false} and {@code permissionB=true}. Result: Both are {@code false}.
* <p>
* This is completely useless for things like MV's world access permissions where you could for example want to deny
* access to all worlds by default, with a few exceptions.
* <p>
* This class takes over all the permission hierarchy checks and provides a way that makes sense. In the
* above examples, the effective permissions would be equal to the permissions that were set.
*/
public class HierarchyPermission implements PermissionNode {
private final PermissionNode parent;
private final Permission permission;
public HierarchyPermission(final PermissionNode parent, final String permission, final String description) {
this.parent = parent;
Permission p = Bukkit.getServer().getPluginManager().getPermission(permission);
if (p == null)
p = new Permission(permission, description, PermissionDefault.FALSE);
else {
p.getChildren().clear();
//p.recalculatePermissibles(); // Not necessary because it's done automatically after setting the default
p.setDefault(PermissionDefault.FALSE);
}
this.permission = p;
}
/**
* Checks whether a given {@link Permissible} has this {@link HierarchyPermission}.
*
* @param permissible The {@link Permissible} that might have the permission.
* @return Whether it has the permission.
*/
public boolean has(Permissible permissible) {
if (permissible.isPermissionSet(permission))
return permissible.hasPermission(permission);
// ask the guy over there
return parent.has(permissible);
}
}
@@ -0,0 +1,38 @@
package com.onarandombox.MultiverseCore.permissions;
import org.bukkit.permissions.Permissible;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a permission node with dynamically created children.
*/
public class PermissionCollection {
private final PermissionNode root;
private final Map<String, PermissionNode> elements;
private final String prefix;
private final String description;
public PermissionCollection(PermissionNode parent, String prefix, String description) {
if (!prefix.endsWith("."))
throw new IllegalArgumentException("The prefix must end with a dot!");
this.root = new HierarchyPermission(parent, prefix + "*", description);
this.elements = new HashMap<String, PermissionNode>();
this.prefix = prefix;
this.description = description;
}
/**
* Checks whether a given {@link Permissible} has a specified element permission.
*
* @param p The {@link Permissible}.
* @param element The element.
* @return Whether the {@link Permissible} has the permission.
*/
public boolean has(Permissible p, String element) {
if (!this.elements.containsKey(element))
this.elements.put(element, new HierarchyPermission(root, prefix + element, description));
return this.elements.get(element).has(p);
}
}
@@ -0,0 +1,30 @@
package com.onarandombox.MultiverseCore.permissions;
import org.bukkit.permissions.Permissible;
/**
* A node in a permissions hierarchy.
*
* @see HierarchyPermission
*/
public interface PermissionNode {
static final class OperatorDefault implements PermissionNode {
@Override
public boolean has(final Permissible permissible) {
return permissible.isOp();
}
}
/**
* This {@link HierarchyPermission} depends on the operator state. Ops have it, non-ops don't.
*/
PermissionNode OP_DEFAULT = new OperatorDefault();
/**
* Checks whether a given {@link Permissible} has this node.
*
* @param permissible The {@link Permissible} that might have the permission.
* @return Whether it has the permission.
*/
boolean has(Permissible permissible);
}
@@ -0,0 +1,21 @@
package com.onarandombox.MultiverseCore.permissions;
/**
* Permission nodes.
*/
public class Permissions {
protected Permissions() {
throw new UnsupportedOperationException();
}
/**
* The {@code multiverse.*} permission.
*/
public static final HierarchyPermission MV_ROOT = new HierarchyPermission(PermissionNode.OP_DEFAULT,
"multiverse.*", "Provides access to all Multiverse features.");
/**
* The {@code multiverse.access.*} family of permissions.
*/
public static final PermissionCollection ACCESS = new PermissionCollection(MV_ROOT, "multiverse.access.", "World access");
}
@@ -0,0 +1,4 @@
/**
* Contains permissions utility classes.
*/
package com.onarandombox.MultiverseCore.permissions;
@@ -74,7 +74,7 @@ public class AnchorManager {
this.anchorConfig.save(new File(this.plugin.getDataFolder(), "anchors.yml"));
return true;
} catch (IOException e) {
Logging.severe("Failed to save anchors.yml. Please check your file permissions.");
this.plugin.log(Level.SEVERE, "Failed to save anchors.yml. Please check your file permissions.");
return false;
}
}
@@ -140,17 +140,8 @@ public class AnchorManager {
if (ancLoc == null) {
continue;
}
String worldPerm = "multiverse.access." + ancLoc.getWorld().getName();
// Add to the list if we're not enforcing access
// OR
// We are enforcing access and the user has the permission.
if (!this.plugin.getMVConfig().getEnforceAccess() ||
(this.plugin.getMVConfig().getEnforceAccess() && p.hasPermission(worldPerm))) {
if (p.hasPermission("multiverse.access." + ancLoc.getWorld().getName())) {
myAnchors.add(anchor);
} else {
Logging.finer(String.format("Not adding anchor %s to the list, user %s doesn't have the %s " +
"permission and 'enforceaccess' is enabled!",
anchor, p.getName(), worldPerm));
}
}
return Collections.unmodifiableSet(myAnchors);
@@ -0,0 +1,281 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Vehicle;
/**
* Used to determine block/location-related facts.
*
* @deprecated Use instead: {@link com.onarandombox.MultiverseCore.api.BlockSafety} and {@link SimpleBlockSafety}.
*/
@Deprecated
public class BlockSafety {
/**
* This function checks whether the block at the given coordinates are above air or not.
* @param l The {@link Location} of the block.
* @return True if the block at that {@link Location} is above air.
*/
public boolean isBlockAboveAir(Location l) {
Location downOne = l.clone();
downOne.setY(downOne.getY() - 1);
return (downOne.getBlock().getType() == Material.AIR);
}
// TODO maybe remove this?
private boolean blockIsNotSafe(World world, double x, double y, double z) {
return !playerCanSpawnHereSafely(world, x, y, z);
}
/**
* Checks if a player can spawn safely at the given coordinates.
* @param world The {@link World}.
* @param x The x-coordinate.
* @param y The y-coordinate.
* @param z The z-coordinate.
* @return True if a player can spawn safely at the given coordinates.
*/
public boolean playerCanSpawnHereSafely(World world, double x, double y, double z) {
Location l = new Location(world, x, y, z);
return playerCanSpawnHereSafely(l);
}
/**
* This function checks whether the block at the coordinates given is safe or not by checking for Lava/Fire/Air
* etc. This also ensures there is enough space for a player to spawn!
*
* @param l The {@link Location}
* @return Whether the player can spawn safely at the given {@link Location}
*/
public boolean playerCanSpawnHereSafely(Location l) {
if (l == null) {
// Can't safely spawn at a null location!
return false;
}
World world = l.getWorld();
Location actual = l.clone();
Location upOne = l.clone();
Location downOne = l.clone();
upOne.setY(upOne.getY() + 1);
downOne.setY(downOne.getY() - 1);
if (this.isSolidBlock(world.getBlockAt(actual).getType())
|| this.isSolidBlock(upOne.getBlock().getType())) {
Logging.finest("Error Here (Actual)? (%s)[%s]", actual.getBlock().getType(),
this.isSolidBlock(actual.getBlock().getType()));
Logging.finest("Error Here (upOne)? (%s)[%s]", upOne.getBlock().getType(),
this.isSolidBlock(upOne.getBlock().getType()));
return false;
}
if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) {
Logging.finest("Error Here (downOne)? (%s)[%s]", downOne.getBlock().getType(),
this.isSolidBlock(downOne.getBlock().getType()));
return false;
}
if (downOne.getBlock().getType() == Material.FIRE) {
Logging.finest("There's fire below! (%s)[%s]", actual.getBlock().getType(),
this.isSolidBlock(actual.getBlock().getType()));
return false;
}
if (isBlockAboveAir(actual)) {
Logging.finest("Is block above air [%s]", isBlockAboveAir(actual));
Logging.finest("Has 2 blocks of water below [%s]", this.hasTwoBlocksofWaterBelow(actual));
return this.hasTwoBlocksofWaterBelow(actual);
}
return true;
}
/**
* Gets the location of the top block at the specified {@link Location}.
* @param l Any {@link Location}.
* @return The {@link Location} of the top-block.
*/
public Location getTopBlock(Location l) {
Location check = l.clone();
check.setY(127); // SUPPRESS CHECKSTYLE: MagicNumberCheck
while (check.getY() > 0) {
if (this.playerCanSpawnHereSafely(check)) {
return check;
}
check.setY(check.getY() - 1);
}
return null;
}
/**
* Gets the location of the top block at the specified {@link Location}.
* @param l Any {@link Location}.
* @return The {@link Location} of the top-block.
*/
public Location getBottomBlock(Location l) {
Location check = l.clone();
check.setY(0);
while (check.getY() < 127) { // SUPPRESS CHECKSTYLE: MagicNumberCheck
if (this.playerCanSpawnHereSafely(check)) {
return check;
}
check.setY(check.getY() + 1);
}
return null;
}
/*
* If someone has a better way of this... Please either tell us, or submit a pull request!
*/
private boolean isSolidBlock(Material type) {
switch (type) {
case AIR:
return false;
case SNOW:
return false;
case TRAP_DOOR:
return false;
case TORCH:
return false;
case YELLOW_FLOWER:
return false;
case RED_ROSE:
return false;
case RED_MUSHROOM:
return false;
case BROWN_MUSHROOM:
return false;
case REDSTONE:
return false;
case REDSTONE_WIRE:
return false;
case RAILS:
return false;
case POWERED_RAIL:
return false;
case REDSTONE_TORCH_ON:
return false;
case REDSTONE_TORCH_OFF:
return false;
case DEAD_BUSH:
return false;
case SAPLING:
return false;
case STONE_BUTTON:
return false;
case LEVER:
return false;
case LONG_GRASS:
return false;
case PORTAL:
return false;
case STONE_PLATE:
return false;
case WOOD_PLATE:
return false;
case SEEDS:
return false;
case SUGAR_CANE_BLOCK:
return false;
case WALL_SIGN:
return false;
case SIGN_POST:
return false;
case WOODEN_DOOR:
return false;
case STATIONARY_WATER:
return false;
case WATER:
return false;
default:
return true;
}
}
/**
* Checks if an entity would be on track at the specified {@link Location}.
* @param l The {@link Location}.
* @return True if an entity would be on tracks at the specified {@link Location}.
*/
public boolean isEntitiyOnTrack(Location l) {
Material currentBlock = l.getBlock().getType();
return (currentBlock == Material.POWERED_RAIL || currentBlock == Material.DETECTOR_RAIL || currentBlock == Material.RAILS);
}
// TODO maybe remove this?
private void showDangers(Location l) {
Location actual = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ());
Location upOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ());
Location downOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ());
upOne.setY(upOne.getY() + 1);
downOne.setY(downOne.getY() - 1);
System.out.print("Location Up: " + upOne.getBlock().getType());
System.out.print(" " + upOne);
System.out.print("Location: " + actual.getBlock().getType());
System.out.print(" " + actual);
System.out.print("Location Down: " + downOne.getBlock().getType());
System.out.print(" " + downOne);
}
/**
* Checks recursively below a {@link Location} for 2 blocks of water.
*
* @param l The {@link Location}
* @return Whether there are 2 blocks of water
*/
private boolean hasTwoBlocksofWaterBelow(Location l) {
if (l.getBlockY() < 0) {
return false;
}
Location oneBelow = l.clone();
oneBelow.subtract(0, 1, 0);
if (oneBelow.getBlock().getType() == Material.WATER || oneBelow.getBlock().getType() == Material.STATIONARY_WATER) {
Location twoBelow = oneBelow.clone();
twoBelow.subtract(0, 1, 0);
return (oneBelow.getBlock().getType() == Material.WATER || oneBelow.getBlock().getType() == Material.STATIONARY_WATER);
}
if (oneBelow.getBlock().getType() != Material.AIR) {
return false;
}
return hasTwoBlocksofWaterBelow(oneBelow);
}
/**
* Checks if the specified {@link Minecart} can spawn safely.
* @param cart The {@link Minecart}.
* @return True if the minecart can spawn safely.
*/
public boolean canSpawnCartSafely(Minecart cart) {
if (this.isBlockAboveAir(cart.getLocation())) {
return true;
}
if (this.isEntitiyOnTrack(LocationManipulation.getNextBlock(cart))) {
return true;
}
return false;
}
/**
* Checks if the specified {@link Vehicle} can spawn safely.
* @param vehicle The {@link Vehicle}.
* @return True if the vehicle can spawn safely.
*/
public boolean canSpawnVehicleSafely(Vehicle vehicle) {
if (this.isBlockAboveAir(vehicle.getLocation())) {
return true;
}
return false;
}
}
@@ -1,111 +0,0 @@
package com.onarandombox.MultiverseCore.utils;
import java.util.logging.Level;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.destination.CannonDestination;
import org.bukkit.Location;
import org.bukkit.TravelAgent;
import org.bukkit.event.player.PlayerPortalEvent;
public class BukkitTravelAgent implements TravelAgent {
private final MVTravelAgent agent;
public BukkitTravelAgent(MVTravelAgent agent) {
this.agent = agent;
}
/**
* {@inheritDoc}
*/
@Override
public BukkitTravelAgent setSearchRadius(int radius) {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public int getSearchRadius() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public BukkitTravelAgent setCreationRadius(int radius) {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public int getCreationRadius() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getCanCreatePortal() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void setCanCreatePortal(boolean create) {
}
/**
* {@inheritDoc}
*/
@Override
public Location findOrCreate(Location location) {
return this.getSafeLocation();
}
/**
* {@inheritDoc}
*/
@Override
public Location findPortal(Location location) {
return this.getSafeLocation();
}
/**
* {@inheritDoc}
*/
@Override
public boolean createPortal(Location location) {
return false;
}
private Location getSafeLocation() {
// At this time, these can never use the velocity.
if (agent.destination instanceof CannonDestination) {
Logging.fine("Using Stock TP method. This cannon will have 0 velocity");
}
SafeTTeleporter teleporter = agent.core.getSafeTTeleporter();
Location newLoc = agent.destination.getLocation(agent.player);
if (agent.destination.useSafeTeleporter()) {
newLoc = teleporter.getSafeLocation(agent.player, agent.destination);
}
if (newLoc == null) {
return agent.player.getLocation();
}
return newLoc;
}
public void setPortalEventTravelAgent(PlayerPortalEvent event) {
event.setPortalTravelAgent(this);
event.useTravelAgent(true);
}
}
@@ -1,46 +0,0 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.Bukkit;
import org.bukkit.event.player.PlayerRespawnEvent;
import java.lang.reflect.Method;
/**
* A utility class to enable version specific minecraft features.
*/
public class CompatibilityLayer {
private static Method checkAnchorSpawn;
/**
* Initialise the reflection methods.
*/
public static void init() {
try {
checkAnchorSpawn = PlayerRespawnEvent.class.getDeclaredMethod("isAnchorSpawn");
} catch (NoSuchMethodException e) {
Logging.fine("%s does not support respawn anchors.", Bukkit.getVersion());
}
}
/**
* Check if the respawn point is of respawn anchor type.
* Introduced in minecraft 1.16
*
* @param event A player respawn event.
* @return If the respawn location is an anchor point.
*/
public static boolean isAnchorSpawn(PlayerRespawnEvent event) {
if (checkAnchorSpawn == null) {
return false;
}
try {
return (boolean) checkAnchorSpawn.invoke(event);
} catch (Exception e) {
Logging.warning("Error checking for: %s", checkAnchorSpawn);
e.printStackTrace();
}
return false;
}
}
@@ -22,9 +22,9 @@ public class FancyMessage implements FancyText {
* Allows easy creation of an alternating colored list.
* TODO: Documentation! Why does CheckStyle just ignore this?
*
* @param title The title.
* @param message The body of the message.
* @param scheme The color scheme to use for easy styling.
* @param title
* @param message
* @param scheme
*/
public FancyMessage(String title, String message, FancyColorScheme scheme) {
this.title = title;
@@ -7,23 +7,11 @@
package com.onarandombox.MultiverseCore.utils;
import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
import com.dumptruckman.minecraft.util.Logging;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import com.dumptruckman.minecraft.util.Logging;
/**
* File-utilities.
@@ -40,8 +28,8 @@ public class FileUtils {
* @return true if the folder was successfully deleted.
*/
public static boolean deleteFolder(File file) {
try (Stream<Path> files = Files.walk(file.toPath())) {
files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
try {
org.apache.commons.io.FileUtils.deleteDirectory(file);
return true;
} catch (IOException e) {
Logging.warning(e.getMessage());
@@ -56,11 +44,8 @@ public class FileUtils {
* @return true if the contents were successfully deleted
*/
public static boolean deleteFolderContents(File file) {
try (Stream<Path> files = Files.walk(file.toPath())){
files.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.filter(f -> !f.equals(file))
.forEach(File::delete);
try {
org.apache.commons.io.FileUtils.cleanDirectory(file);
return true;
} catch (IOException e) {
Logging.warning(e.getMessage());
@@ -68,68 +53,23 @@ public class FileUtils {
}
}
/**
* Helper method to copy the world-folder.
* @param source Source-File
* @param target Target-File
*
* @return true if it had success
*/
public static boolean copyFolder(File source, File target) {
return copyFolder(source, target, null);
}
private static final int COPY_BLOCK_SIZE = 1024;
/**
* Helper method to copy the world-folder.
* @param source Source-File
* @param target Target-File
* @param excludeFiles files to ignore and not copy over to Target-File
* @param log A logger that logs the operation
*
* @return true if it had success
* @return if it had success
*/
public static boolean copyFolder(File source, File target, List<String> excludeFiles) {
Path sourceDir = source.toPath();
Path targetDir = target.toPath();
public static boolean copyFolder(File source, File target, Logger log) {
try {
Files.walkFileTree(sourceDir, new CopyDirFileVisitor(sourceDir, targetDir, excludeFiles));
org.apache.commons.io.FileUtils.copyDirectory(source, target);
return true;
} catch (IOException e) {
Logging.warning("Unable to copy directory", e);
log.warning(e.getMessage());
return false;
}
}
private static class CopyDirFileVisitor extends SimpleFileVisitor<Path> {
private final Path sourceDir;
private final Path targetDir;
private final List<String> excludeFiles;
private CopyDirFileVisitor(Path sourceDir, Path targetDir, List<String> excludeFiles) {
this.sourceDir = sourceDir;
this.targetDir = targetDir;
this.excludeFiles = excludeFiles;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path newDir = targetDir.resolve(sourceDir.relativize(dir));
if (!Files.isDirectory(newDir)) {
Files.createDirectory(newDir);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// Pass files that are set to ignore
if (excludeFiles != null && excludeFiles.contains(file.getFileName().toString()))
return FileVisitResult.CONTINUE;
// Copy the files
Path targetFile = targetDir.resolve(sourceDir.relativize(file));
Files.copy(file, targetFile, COPY_ATTRIBUTES);
return FileVisitResult.CONTINUE;
}
}
}
}
@@ -1,285 +0,0 @@
package com.onarandombox.MultiverseCore.utils;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
/**
* Multiverse's Friendly Economist. This is used to deal with external economies and also item costs for stuff in MV.
*/
public class MVEconomist {
private final VaultHandler vaultHandler;
public MVEconomist(Plugin plugin) {
vaultHandler = new VaultHandler(plugin);
}
private boolean isUsingVault(Material currency) {
return !isItemCurrency(currency) && getVaultHandler().hasEconomy();
}
/**
* Checks if an economy plugin is in use.
*
* @return true if an economy plugin is detected by Vault.
*/
public boolean isUsingEconomyPlugin() {
return getVaultHandler().hasEconomy();
}
/**
* Formats the amount to a human readable currency string.
*
* @param amount the amount of currency.
* @param currency the type of currency. Null indicates a non-item currency is used.
* @return the human readable currency string.
*/
public String formatPrice(double amount, @Nullable Material currency) {
if (isUsingVault(currency)) {
return getVaultHandler().getEconomy().format(amount);
} else {
return ItemEconomy.getFormattedPrice(amount, currency);
}
}
/**
* Returns the name of the economy in use.
*
* @return the name of the economy in use.
*/
public String getEconomyName() {
if (getVaultHandler().hasEconomy()) {
return getVaultHandler().getEconomy().getName();
} else {
return ItemEconomy.getName();
}
}
/**
* Determines if a player has enough of a given currency.
*
* @param player the player to check for currency.
* @param amount the amount of currency.
* @param currency the type of currency. Null indicates non-item currency is used.
* @return true if the player has enough of the given currency or the amount is 0 or less.
*/
public boolean isPlayerWealthyEnough(Player player, double amount, Material currency) {
if (amount <= 0D) {
return true;
} else if (isUsingVault(currency)) {
return getVaultHandler().getEconomy().has(player, amount);
} else {
return ItemEconomy.hasEnough(player, amount, currency);
}
}
/**
* Formats a message for a player indicating they don't have enough currency.
*
* @param currency the type of currency. Null indicates a non-item currency is used.
* @param message The more specific message to append to the generic message of not having enough.
* @return the formatted insufficient funds message.
*/
public String getNSFMessage(Material currency, String message) {
return "Sorry, you don't have enough " + (isItemCurrency(currency) ? "items" : "funds") + ". " + message;
}
/**
* Deposits a given amount of currency either into the player's economy account or inventory if the currency
* is not null.
*
* @param player the player to give currency to.
* @param amount the amount to give.
* @param currency the type of currency.
*/
public void deposit(Player player, double amount, @Nullable Material currency) {
if (isUsingVault(currency)) {
getVaultHandler().getEconomy().depositPlayer(player, amount);
} else {
ItemEconomy.deposit(player, amount, currency);
}
}
/**
* Withdraws a given amount of currency either from the player's economy account or inventory if the currency
* is not null.
*
* @param player the player to take currency from.
* @param amount the amount to take.
* @param currency the type of currency.
*/
public void withdraw(Player player, double amount, @Nullable Material currency) {
if (isUsingVault(currency)) {
getVaultHandler().getEconomy().withdrawPlayer(player, amount);
} else {
ItemEconomy.withdraw(player, amount, currency);
}
}
/**
* Returns the economy balance of the given player.
*
* @param player the player to get the balance for.
* @return the economy balance of the given player.
* @throws IllegalStateException thrown if this is used when no economy plugin is available.
*/
public double getBalance(Player player) throws IllegalStateException {
return getBalance(player, null);
}
/**
* Returns the economy balance of the given player in the given world. If the economy plugin does not have world
* specific balances then the global balance will be returned.
*
* @param player the player to get the balance for.
* @param world the world to get the balance for.
* @return the economy balance of the given player in the given world.
* @throws IllegalStateException thrown if this is used when no economy plugin is available.
*/
public double getBalance(Player player, World world) throws IllegalStateException {
if (!isUsingEconomyPlugin()) {
throw new IllegalStateException("getBalance is only available when using an economy plugin with Vault");
}
if (world != null) {
return getVaultHandler().getEconomy().getBalance(player, world.getName());
} else {
return getVaultHandler().getEconomy().getBalance(player);
}
}
/**
* Sets the economy balance for the given player.
*
* @param player the player to set the balance for.
* @param amount the amount to set the player's balance to.
* @throws IllegalStateException thrown if this is used when no economy plugin is available.
*/
public void setBalance(Player player, double amount) throws IllegalStateException {
setBalance(player, null, amount);
}
/**
* Sets the economy balance for the given player in the given world. If the economy plugin does not have world
* specific balances then the global balance will be set.
*
* @param player the player to set the balance for.
* @param world the world to get the balance for.
* @param amount the amount to set the player's balance to.
* @throws IllegalStateException thrown if this is used when no economy plugin is available.
*/
public void setBalance(Player player, World world, double amount) throws IllegalStateException {
if (!isUsingEconomyPlugin()) {
throw new IllegalStateException("getBalance is only available when using an economy plugin with Vault");
}
if (world != null) {
getVaultHandler().getEconomy().withdrawPlayer(player, world.getName(), getBalance(player, world));
getVaultHandler().getEconomy().depositPlayer(player, world.getName(), amount);
} else {
getVaultHandler().getEconomy().withdrawPlayer(player, getBalance(player));
getVaultHandler().getEconomy().depositPlayer(player, amount);
}
}
/**
* This method is public for backwards compatibility.
*
* @return the old VaultHandler.
* @deprecated just use the other methods in this class for economy stuff.
*/
// TODO make private
@Deprecated
public VaultHandler getVaultHandler() {
return vaultHandler;
}
/**
* Determines if the currency type string given represents an item currency.
*
* @param currency the type of currency.
* @return true if currency string matches a valid material.
*/
public static boolean isItemCurrency(Material currency) {
return currency != null;
}
private static class ItemEconomy {
private static final String ECONOMY_NAME = "Simple Item Economy";
private static String getFormattedPrice(double amount, Material currency) {
if (isItemCurrency(currency)) {
return amount + " " + currency.toString();
} else {
return "";
}
}
private static String getName() {
return ECONOMY_NAME;
}
private static boolean hasEnough(Player player, double amount, Material currency) {
if (currency != null) {
return player.getInventory().contains(currency, (int) amount);
} else {
return true;
}
}
private static void deposit(Player player, double amount, Material currency) {
if (isItemCurrency(currency)) {
giveItem(player, amount, currency);
}
}
private static void withdraw(Player player, double amount, Material currency) {
if (isItemCurrency(currency)) {
takeItem(player, amount, currency);
}
}
private static void giveItem(Player player, double amount, Material type) {
ItemStack item = new ItemStack(type, (int) amount);
player.getInventory().addItem(item);
showReceipt(player, (amount * -1), type);
}
private static void takeItem(Player player, double amount, Material type) {
int removed = 0;
HashMap<Integer, ItemStack> items = (HashMap<Integer, ItemStack>) player.getInventory().all(type);
for (int i : items.keySet()) {
if (removed >= amount) {
break;
}
int diff = (int) (amount - removed);
int amt = player.getInventory().getItem(i).getAmount();
if (amt - diff > 0) {
player.getInventory().getItem(i).setAmount(amt - diff);
break;
} else {
removed += amt;
player.getInventory().clear(i);
}
}
showReceipt(player, amount, type);
}
private static void showReceipt(Player player, double price, Material item) {
if (price > 0D) {
player.sendMessage(String.format("%s%s%s %s",
ChatColor.WHITE, "You have been charged", ChatColor.GREEN, getFormattedPrice(price, item)));
} else if (price < 0D) {
player.sendMessage(String.format("%s%s%s %s",
ChatColor.DARK_GREEN, getFormattedPrice((price * -1), item),
ChatColor.WHITE, "has been added to your inventory."));
}
}
}
}
@@ -7,11 +7,11 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.permissions.Permissions;
import com.pneumaticraft.commandhandler.PermissionsInterface;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@@ -101,21 +101,18 @@ public class MVPermissions implements PermissionsInterface {
public boolean canEnterWorld(Player p, MultiverseWorld w) {
// If we're not enforcing access, anyone can enter.
if (!plugin.getMVConfig().getEnforceAccess()) {
Logging.finest("EnforceAccess is OFF. Player was allowed in " + w.getAlias());
this.plugin.log(Level.FINEST, "EnforceAccess is OFF. Player was allowed in " + w.getAlias());
return true;
}
return this.hasPermission(p, "multiverse.access." + w.getName(), false);
return Permissions.ACCESS.has(p, w.getName());
}
private boolean canEnterLocation(Player p, Location l) {
if (l == null) {
if (l == null)
return false;
}
String worldName = l.getWorld().getName();
if (!this.plugin.getMVWorldManager().isMVWorld(worldName)) {
return false;
}
return this.hasPermission(p, "multiverse.access." + worldName, false);
return this.plugin.getMVWorldManager().isMVWorld(worldName) && Permissions.ACCESS.has(p, worldName);
}
/**
@@ -231,7 +228,7 @@ public class MVPermissions implements PermissionsInterface {
*
* @param sender Who is requesting the permission.
* @param node The permission node in string format; multiverse.core.list.worlds for example.
* @param isOpRequired deprecated This is not used for anything anymore.
* @param isOpRequired @Deprecated. This is not used for anything anymore.
* @return True if they have that permission or any parent.
*/
@Override
@@ -258,14 +255,14 @@ public class MVPermissions implements PermissionsInterface {
boolean hasPermission = sender.hasPermission(node);
if (!sender.isPermissionSet(node)) {
Logging.finer(String.format("The node [%s%s%s] was %sNOT%s set for [%s%s%s].",
this.plugin.log(Level.FINER, String.format("The node [%s%s%s] was %sNOT%s set for [%s%s%s].",
ChatColor.RED, node, ChatColor.WHITE, ChatColor.RED, ChatColor.WHITE, ChatColor.AQUA,
player.getDisplayName(), ChatColor.WHITE));
}
if (hasPermission) {
Logging.finer("Checking to see if player [" + player.getName() + "] has permission [" + node + "]... YES");
this.plugin.log(Level.FINER, "Checking to see if player [" + player.getName() + "] has permission [" + node + "]... YES");
} else {
Logging.finer("Checking to see if player [" + player.getName() + "] has permission [" + node + "]... NO");
this.plugin.log(Level.FINER, "Checking to see if player [" + player.getName() + "] has permission [" + node + "]... NO");
}
return hasPermission;
}
@@ -9,19 +9,114 @@ package com.onarandombox.MultiverseCore.utils;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.destination.CannonDestination;
import org.bukkit.Location;
import org.bukkit.TravelAgent;
import org.bukkit.entity.Player;
import java.util.logging.Level;
/**
* The Multiverse TravelAgent.
* The Multiverse-{@link TravelAgent}.
*/
public class MVTravelAgent {
protected MVDestination destination;
protected MultiverseCore core;
protected Player player;
public class MVTravelAgent implements TravelAgent {
private MVDestination destination;
private MultiverseCore core;
private Player player;
public MVTravelAgent(MultiverseCore multiverseCore, MVDestination d, Player p) {
this.destination = d;
this.core = multiverseCore;
this.player = p;
}
/**
* {@inheritDoc}
*/
@Override
public TravelAgent setSearchRadius(int radius) {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public int getSearchRadius() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public TravelAgent setCreationRadius(int radius) {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public int getCreationRadius() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getCanCreatePortal() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void setCanCreatePortal(boolean create) {
}
/**
* {@inheritDoc}
*/
@Override
public Location findOrCreate(Location location) {
return this.getSafeLocation();
}
/**
* {@inheritDoc}
*/
@Override
public Location findPortal(Location location) {
return this.getSafeLocation();
}
/**
* {@inheritDoc}
*/
@Override
public boolean createPortal(Location location) {
return false;
}
private Location getSafeLocation() {
// At this time, these can never use the velocity.
if (this.destination instanceof CannonDestination) {
this.core.log(Level.FINE, "Using Stock TP method. This cannon will have 0 velocity");
}
SafeTTeleporter teleporter = this.core.getSafeTTeleporter();
Location newLoc = this.destination.getLocation(this.player);
if (this.destination.useSafeTeleporter()) {
newLoc = teleporter.getSafeLocation(this.player, this.destination);
}
if (newLoc == null) {
return this.player.getLocation();
}
return newLoc;
}
}
@@ -1,42 +0,0 @@
package com.onarandombox.MultiverseCore.utils;
import de.themoep.idconverter.IdMappings;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A tool for converting values which may be an old type ID to a Material.
*/
public class MaterialConverter {
/**
* Converts the value in the given config at the given path from a numeric id or flattened material name to a
* Material.
*
* @param config The config with the value to convert.
* @param path The path of the value in the config.
* @return The converted Material type or null if no matching type.
*/
@Nullable
public static Material convertConfigType(@NotNull ConfigurationSection config, @NotNull String path) {
return convertTypeString(config.getString(path));
}
/**
* Converts a string representing a numeric id or flattened material name to a Material.
*
* @param value The value to convert.
* @return The converted Material type or null if no matching type.
*/
@Nullable
public static Material convertTypeString(@Nullable String value) {
IdMappings.Mapping mapping = IdMappings.getById(value != null ? value : "");
if (mapping != null) {
return Material.matchMaterial(mapping.getFlatteningType());
} else {
return Material.matchMaterial(value != null ? value : "");
}
}
}
@@ -7,10 +7,9 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.fernferret.allpay.commons.GenericBank;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
@@ -136,52 +135,53 @@ public class PermissionTools {
// Only check payments if it's a different world:
if (!toWorld.equals(fromWorld)) {
final double price = toWorld.getPrice();
// Don't bother checking economy stuff if it doesn't even cost to enter.
if (price == 0D) {
if (toWorld.getPrice() == 0D) {
return true;
}
// If the player does not have to pay, return now.
if (this.plugin.getMVPerms().hasPermission(teleporter, toWorld.getExemptPermission().getName(), true)) {
return true;
}
final MVEconomist economist = plugin.getEconomist();
final Material currency = toWorld.getCurrency();
final String formattedAmount = economist.formatPrice(price, currency);
if (economist.isPlayerWealthyEnough(teleporterPlayer, price, currency)) {
if (pay) {
if (price < 0D) {
economist.deposit(teleporterPlayer, -price, currency);
final boolean usingVault;
final String formattedAmount;
if (toWorld.getCurrency() <= 0 && plugin.getVaultHandler().getEconomy() != null) {
usingVault = true;
formattedAmount = plugin.getVaultHandler().getEconomy().format(toWorld.getPrice());
} else {
usingVault = false;
formattedAmount = this.plugin.getBank().getFormattedAmount(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency());
}
String errString = "You need " + formattedAmount + " to send " + teleportee + " to " + toWorld.getColoredWorldString();
if (teleportee.equals(teleporter)) {
errString = "You need " + formattedAmount + " to enter " + toWorld.getColoredWorldString();
}
if (usingVault) {
if (!plugin.getVaultHandler().getEconomy().has(teleporterPlayer.getName(), toWorld.getPrice())) {
return false;
} else if (pay) {
if (toWorld.getPrice() < 0D) {
plugin.getVaultHandler().getEconomy().depositPlayer(teleporterPlayer.getName(), toWorld.getPrice() * -1D);
} else {
economist.withdraw(teleporterPlayer, price, currency);
plugin.getVaultHandler().getEconomy().withdrawPlayer(teleporterPlayer.getName(), toWorld.getPrice());
}
sendTeleportPaymentMessage(economist, teleporterPlayer, teleportee, toWorld.getColoredWorldString(), price, currency);
}
} else {
if (teleportee.equals(teleporter)) {
teleporterPlayer.sendMessage(economist.getNSFMessage(currency,
"You need " + formattedAmount + " to enter " + toWorld.getColoredWorldString()));
} else {
teleporterPlayer.sendMessage(economist.getNSFMessage(currency,
"You need " + formattedAmount + " to send " + teleportee.getName() + " to " + toWorld.getColoredWorldString()));
GenericBank bank = plugin.getBank();
if (!bank.hasEnough(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency(), errString)) {
return false;
} else if (pay) {
if (toWorld.getPrice() < 0D) {
bank.give(teleporterPlayer, toWorld.getPrice() * -1D, toWorld.getCurrency());
} else {
bank.take(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency());
}
}
return false;
}
}
return true;
}
private void sendTeleportPaymentMessage (MVEconomist economist, Player teleporterPlayer, Player teleportee, String toWorld, double price, Material currency) {
price = Math.abs(price);
if (teleporterPlayer.equals(teleportee)) {
teleporterPlayer.sendMessage("You were " + (price > 0D ? "charged " : "given ") + economist.formatPrice(price, currency) + " for teleporting to " + toWorld);
} else {
teleporterPlayer.sendMessage("You were " + (price > 0D ? "charged " : "given ") + economist.formatPrice(price, currency) + " for teleporting " + teleportee.getName() + " to " + toWorld);
}
}
/**
* Checks to see if player can go to a world given their current status.
@@ -196,7 +196,7 @@ public class PermissionTools {
* @return True if they can't go to the world, False if they can.
*/
public boolean playerCanGoFromTo(MultiverseWorld fromWorld, MultiverseWorld toWorld, CommandSender teleporter, Player teleportee) {
Logging.finest("Checking '" + teleporter + "' can send '" + teleportee + "' somewhere");
this.plugin.log(Level.FINEST, "Checking '" + teleporter + "' can send '" + teleportee + "' somewhere");
Player teleporterPlayer;
if (plugin.getMVConfig().getTeleportIntercept()) {
@@ -1,176 +0,0 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Helper class to get {@link Player} from name, UUID or Selectors.
*/
public class PlayerFinder {
private static final Pattern UUID_REGEX = Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[34][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}");
private static final Pattern COMMA_SPLIT = Pattern.compile(",");
/**
* Get a {@link Player} based on an identifier of name UUID or selector.
*
* @param playerIdentifier An identifier of name UUID or selector.
* @param sender Target sender for selector.
* @return The player if found, else null.
*/
@Nullable
public static Player get(@NotNull String playerIdentifier,
@NotNull CommandSender sender) {
Player targetPlayer = getByName(playerIdentifier);
if (targetPlayer != null) {
return targetPlayer;
}
targetPlayer = getByUuid(playerIdentifier);
if (targetPlayer != null) {
return targetPlayer;
}
return getBySelector(playerIdentifier, sender);
}
/**
* Get multiple {@link Player} based on many identifiers of name UUID or selector.
*
* @param playerIdentifiers An identifier of multiple names, UUIDs or selectors, separated by comma.
* @param sender Target sender for selector.
* @return A list of all the {@link Player} found.
*/
@Nullable
public static List<Player> getMulti(@NotNull String playerIdentifiers,
@NotNull CommandSender sender) {
String[] playerIdentifierArray = COMMA_SPLIT.split(playerIdentifiers);
if (playerIdentifierArray == null || playerIdentifierArray.length == 0) {
return null;
}
List<Player> playerResults = new ArrayList<>();
for (String playerIdentifier : playerIdentifierArray) {
Player targetPlayer = getByName(playerIdentifier);
if (targetPlayer != null) {
playerResults.add(targetPlayer);
continue;
}
targetPlayer = getByUuid(playerIdentifier);
if (targetPlayer != null) {
playerResults.add(targetPlayer);
continue;
}
List<Player> targetPlayers = getMultiBySelector(playerIdentifier, sender);
if (targetPlayers != null) {
playerResults.addAll(targetPlayers);
}
}
return playerResults;
}
/**
* Get a {@link Player} based on player name.
*
* @param playerName Name of a {@link Player}.
* @return The player if found, else null.
*/
@Nullable
public static Player getByName(@NotNull String playerName) {
return Bukkit.getPlayerExact(playerName);
}
/**
* Get a {@link Player} based on player UUID.
*
* @param playerUuid UUID of a player.
* @return The player if found, else null.
*/
@Nullable
public static Player getByUuid(@NotNull String playerUuid) {
if (!UUID_REGEX.matcher(playerUuid).matches()) {
return null;
}
UUID uuid;
try {
uuid = UUID.fromString(playerUuid);
} catch (Exception e) {
return null;
}
return getByUuid(uuid);
}
/**
* Get a {@link Player} based on playerUUID.
*
* @param playerUuid UUID of a player.
* @return The player if found, else null.
*/
@Nullable
public static Player getByUuid(@NotNull UUID playerUuid) {
return Bukkit.getPlayer(playerUuid);
}
/**
* Get a {@link Player} based on vanilla selectors.
* https://minecraft.gamepedia.com/Commands#Target_selectors
*
* @param playerSelector A target selector, usually starts with an '@'.
* @param sender Target sender for selector.
* @return The player if only one found, else null.
*/
@Nullable
public static Player getBySelector(@NotNull String playerSelector,
@NotNull CommandSender sender) {
List<Player> matchedPlayers = getMultiBySelector(playerSelector, sender);
if (matchedPlayers == null || matchedPlayers.isEmpty()) {
Logging.warning("No player found with selector '%s' for %s.", playerSelector, sender.getName());
return null;
}
if (matchedPlayers.size() > 1) {
Logging.warning("Ambiguous selector result '%s' for %s (more than one player matched) - %s",
playerSelector, sender.getName(), matchedPlayers.toString());
return null;
}
return matchedPlayers.get(0);
}
/**
* Get multiple {@link Player} based on selector.
* https://minecraft.gamepedia.com/Commands#Target_selectors
*
* @param playerSelector A target selector, usually starts with an '@'.
* @param sender Target sender for selector.
* @return A list of all the {@link Player} found.
*/
@Nullable
public static List<Player> getMultiBySelector(@NotNull String playerSelector,
@NotNull CommandSender sender) {
if (playerSelector.charAt(0) != '@') {
return null;
}
try {
return Bukkit.selectEntities(sender, playerSelector).stream()
.filter(e -> e instanceof Player)
.map(e -> ((Player) e))
.collect(Collectors.toList());
} catch (IllegalArgumentException e) {
Logging.warning("An error occurred while parsing selector '%s' for %s. Is it is the correct format?",
playerSelector, sender.getName());
e.printStackTrace();
return null;
}
}
}
@@ -7,7 +7,6 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
@@ -28,7 +27,7 @@ import java.util.logging.Level;
/**
* Utility class that removes animals from worlds that don't belong there.
*
* @deprecated Use instead: {@link com.onarandombox.MultiverseCore.api.WorldPurger} and {@link SimpleWorldPurger}.
* @deprecated Use instead: {@link WorldPurger} and {@link SimpleWorldPurger}.
*/
@Deprecated
public class PurgeWorlds {
@@ -87,7 +86,7 @@ public class PurgeWorlds {
}
int entitiesKilled = 0;
for (Entity e : world.getEntities()) {
Logging.finest("Entity list (aval for purge) from WORLD < " + mvworld.getName() + " >: " + e.toString());
this.plugin.log(Level.FINEST, "Entity list (aval for purge) from WORLD < " + mvworld.getName() + " >: " + e.toString());
// Check against Monsters
if (killMonster(mvworld, e, thingsToKill, negateMonsters)) {
@@ -134,16 +133,16 @@ public class PurgeWorlds {
entityName = e.toString().replaceAll("Craft", "").toUpperCase();
}
if (e instanceof Slime || e instanceof Monster || e instanceof Ghast || e instanceof EnderDragon) {
Logging.finest("Looking at a monster: " + e);
this.plugin.log(Level.FINEST, "Looking at a monster: " + e);
if (creaturesToKill.contains(entityName) || creaturesToKill.contains("ALL") || creaturesToKill.contains("MONSTERS")) {
if (!negate) {
Logging.finest("Removing a monster: " + e);
this.plugin.log(Level.FINEST, "Removing a monster: " + e);
e.remove();
return true;
}
} else {
if (negate) {
Logging.finest("Removing a monster: " + e);
this.plugin.log(Level.FINEST, "Removing a monster: " + e);
e.remove();
return true;
}
@@ -1,140 +0,0 @@
package com.onarandombox.MultiverseCore.utils;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Utility class used to help in doing various reflection actions.
*/
public class ReflectHelper {
/**
* Try to get the {@link Class} based on its classpath.
*
* @param classPath The target classpath.
* @return A {@link Class} if found, else null.
*/
@Nullable
public static Class<?> getClass(String classPath) {
try {
return Class.forName(classPath);
} catch (ClassNotFoundException e) {
return null;
}
}
/**
* Check if the {@link Class} for a give classpath is present/valid.
*
* @param classPath Target classpath.
* @return True if class path is a valid class, else false.
*/
public static boolean hasClass(String classPath) {
return getClass(classPath) != null;
}
/**
* Try to get a {@link Method} from a given class.
*
* @param clazz The class to search the method on.
* @param methodName Name of the method to get.
* @param parameterTypes Parameters present for that method.
* @param <C> The class type.
* @return A {@link Method} if found, else null.
*/
@Nullable
public static <C> Method getMethod(Class<C> clazz, String methodName, Class<?>... parameterTypes) {
try {
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* Try to get a {@link Method} from a given class.
*
* @param classInstance Instance of the class to search the method on.
* @param methodName Name of the method to get.
* @param parameterTypes Parameters present for that method.
* @param <C> The class type.
* @return A {@link Method} if found, else null.
*/
@Nullable
public static <C> Method getMethod(C classInstance, String methodName, Class<?>... parameterTypes) {
return getMethod(classInstance.getClass(), methodName, parameterTypes);
}
/**
* Calls a {@link Method}.
*
* @param classInstance Instance of the class responsible for the method.
* @param method The method to call.
* @param parameters Parameters needed when calling the method.
* @param <C> The class type.
* @param <R> The return type.
* @return Return value of the method call if any, else null.
*/
@Nullable
public static <C, R> R invokeMethod(C classInstance, Method method, Object...parameters) {
try {
return (R) method.invoke(classInstance, parameters);
} catch (Exception e) {
return null;
}
}
/**
* Try to get a {@link Field} from a given class.
*
* @param clazz The class to search the field on.
* @param fieldName Name of the field to get.
* @param <C> The class type.
* @return A {@link Field} if found, else null.
*/
@Nullable
public static <C> Field getField(Class<C> clazz, String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
return null;
}
}
/**
* Try to get a {@link Field} from a given class.
*
* @param classInstance Instance of the class to search the field on.
* @param fieldName Name of the field to get.
* @param <C> The class type.
* @return A {@link Field} if found, else null.
*/
@Nullable
public static <C> Field getField(C classInstance, String fieldName) {
return getField(classInstance.getClass(), fieldName);
}
/**
* Gets the value of an {@link Field} from an instance of the class responsible.
*
* @param classInstance Instance of the class to get the field value from.
* @param field The field to get value from.
* @param <C> The class type.
* @param <V> The field value type.
* @return The field value if any, else null.
*/
@Nullable
public static <C, V> V getFieldValue(C classInstance, Field field) {
try {
return (V) field.get(classInstance);
} catch (IllegalAccessException e) {
return null;
}
}
}
@@ -0,0 +1,358 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.utils;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.BlockSafety;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.destination.InvalidDestination;
import com.onarandombox.MultiverseCore.enums.TeleportResult;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.util.Vector;
import java.util.logging.Level;
/**
* The {@link SafeTTeleporter}.
*
* @deprecated Use instead: {@link com.onarandombox.MultiverseCore.api.SafeTTeleporter} and {@link SimpleSafeTTeleporter}.
*/
@Deprecated
public class SafeTTeleporter {
private MultiverseCore plugin;
private BlockSafety bs;
public SafeTTeleporter(MultiverseCore plugin) {
this.plugin = plugin;
this.bs = plugin.getBlockSafety();
}
private static final int DEFAULT_TOLERANCE = 6;
private static final int DEFAULT_RADIUS = 9;
/**
* Gets the next safe location around the given location.
* @param l A {@link Location}.
* @return A safe {@link Location}.
*/
public Location getSafeLocation(Location l) {
return this.getSafeLocation(l, DEFAULT_TOLERANCE, DEFAULT_RADIUS);
}
/**
* Gets the next safe location around the given location.
* @param l A {@link Location}.
* @param tolerance The tolerance.
* @param radius The radius.
* @return A safe {@link Location}.
*/
public Location getSafeLocation(Location l, int tolerance, int radius) {
// Check around the player first in a configurable radius:
Location safe = checkAboveAndBelowLocation(l, tolerance, radius);
if (safe != null) {
safe.setX(safe.getBlockX() + .5); // SUPPRESS CHECKSTYLE: MagicNumberCheck
safe.setZ(safe.getBlockZ() + .5); // SUPPRESS CHECKSTYLE: MagicNumberCheck
this.plugin.log(Level.FINE, "Hey! I found one: " + plugin.getLocationManipulation().strCoordsRaw(safe));
} else {
this.plugin.log(Level.FINE, "Uh oh! No safe place found!");
}
return safe;
}
private Location checkAboveAndBelowLocation(Location l, int tolerance, int radius) {
// Tolerance must be an even number:
if (tolerance % 2 != 0) {
tolerance += 1;
}
// We want half of it, so we can go up and down
tolerance /= 2;
this.plugin.log(Level.FINER, "Given Location of: " + plugin.getLocationManipulation().strCoordsRaw(l));
this.plugin.log(Level.FINER, "Checking +-" + tolerance + " with a radius of " + radius);
// For now this will just do a straight up block.
Location locToCheck = l.clone();
// Check the main level
Location safe = this.checkAroundLocation(locToCheck, radius);
if (safe != null) {
return safe;
}
// We've already checked zero right above this.
int currentLevel = 1;
while (currentLevel <= tolerance) {
// Check above
locToCheck = l.clone();
locToCheck.add(0, currentLevel, 0);
safe = this.checkAroundLocation(locToCheck, radius);
if (safe != null) {
return safe;
}
// Check below
locToCheck = l.clone();
locToCheck.subtract(0, currentLevel, 0);
safe = this.checkAroundLocation(locToCheck, radius);
if (safe != null) {
return safe;
}
currentLevel++;
}
return null;
}
/*
* For my crappy algorithm, radius MUST be odd.
*/
private Location checkAroundLocation(Location l, int diameter) {
if (diameter % 2 == 0) {
diameter += 1;
}
Location checkLoc = l.clone();
// Start at 3, the min diameter around a block
int loopcounter = 3;
while (loopcounter <= diameter) {
boolean foundSafeArea = checkAroundSpecificDiameter(checkLoc, loopcounter);
// If a safe area was found:
if (foundSafeArea) {
// Return the checkLoc, it is the safe location.
return checkLoc;
}
// Otherwise, let's reset our location
checkLoc = l.clone();
// And increment the radius
loopcounter += 2;
}
return null;
}
private boolean checkAroundSpecificDiameter(Location checkLoc, int circle) {
// Adjust the circle to get how many blocks to step out.
// A radius of 3 makes the block step 1
// A radius of 5 makes the block step 2
// A radius of 7 makes the block step 3
// ...
int adjustedCircle = ((circle - 1) / 2);
checkLoc.add(adjustedCircle, 0, 0);
if (this.bs.playerCanSpawnHereSafely(checkLoc)) {
return true;
}
// Now we go to the right that adjustedCircle many
for (int i = 0; i < adjustedCircle; i++) {
checkLoc.add(0, 0, 1);
if (this.bs.playerCanSpawnHereSafely(checkLoc)) {
return true;
}
}
// Then down adjustedCircle *2
for (int i = 0; i < adjustedCircle * 2; i++) {
checkLoc.add(-1, 0, 0);
if (this.bs.playerCanSpawnHereSafely(checkLoc)) {
return true;
}
}
// Then left adjustedCircle *2
for (int i = 0; i < adjustedCircle * 2; i++) {
checkLoc.add(0, 0, -1);
if (this.bs.playerCanSpawnHereSafely(checkLoc)) {
return true;
}
}
// Then up Then left adjustedCircle *2
for (int i = 0; i < adjustedCircle * 2; i++) {
checkLoc.add(1, 0, 0);
if (this.bs.playerCanSpawnHereSafely(checkLoc)) {
return true;
}
}
// Then finish up by doing adjustedCircle - 1
for (int i = 0; i < adjustedCircle - 1; i++) {
checkLoc.add(0, 0, 1);
if (this.bs.playerCanSpawnHereSafely(checkLoc)) {
return true;
}
}
return false;
}
/**
* Safely teleport the entity to the MVDestination. This will perform checks to see if the place is safe, and if
* it's not, will adjust the final destination accordingly.
*
* @param teleporter Person who performed the teleport command.
* @param teleportee Entity to teleport
* @param d Destination to teleport them to
* @return true for success, false for failure
*/
public TeleportResult safelyTeleport(CommandSender teleporter, Entity teleportee, MVDestination d) {
if (d instanceof InvalidDestination) {
this.plugin.log(Level.FINER, "Entity tried to teleport to an invalid destination");
return TeleportResult.FAIL_INVALID;
}
Player teleporteePlayer = null;
if (teleportee instanceof Player) {
teleporteePlayer = ((Player) teleportee);
} else if (teleportee.getPassenger() instanceof Player) {
teleporteePlayer = ((Player) teleportee.getPassenger());
}
if (teleporteePlayer == null) {
return TeleportResult.FAIL_INVALID;
}
MultiverseCore.addPlayerToTeleportQueue(teleporter.getName(), teleporteePlayer.getName());
Location safeLoc = d.getLocation(teleportee);
if (d.useSafeTeleporter()) {
safeLoc = this.getSafeLocation(teleportee, d);
}
if (safeLoc != null) {
if (teleportee.teleport(safeLoc)) {
if (!d.getVelocity().equals(new Vector(0, 0, 0))) {
teleportee.setVelocity(d.getVelocity());
}
return TeleportResult.SUCCESS;
}
return TeleportResult.FAIL_OTHER;
}
return TeleportResult.FAIL_UNSAFE;
}
/**
* Safely teleport the entity to the Location. This may perform checks to
* see if the place is safe, and if
* it's not, will adjust the final destination accordingly.
*
* @param teleporter Person who issued the teleport command.
* @param teleportee Entity to teleport.
* @param location Location to teleport them to.
* @param safely Should the destination be checked for safety before teleport?
* @return true for success, false for failure.
*/
public TeleportResult safelyTeleport(CommandSender teleporter, Entity teleportee, Location location, boolean safely) {
if (safely) {
location = this.getSafeLocation(location);
}
if (location != null) {
if (teleportee.teleport(location)) {
return TeleportResult.SUCCESS;
}
return TeleportResult.FAIL_OTHER;
}
return TeleportResult.FAIL_UNSAFE;
}
/**
* Returns a safe location for the entity to spawn at.
*
* @param e The entity to spawn
* @param d The MVDestination to take the entity to.
* @return A new location to spawn the entity at.
*/
public Location getSafeLocation(Entity e, MVDestination d) {
Location l = d.getLocation(e);
if (this.bs.playerCanSpawnHereSafely(l)) {
plugin.log(Level.FINE, "The first location you gave me was safe.");
return l;
}
if (e instanceof Minecart) {
Minecart m = (Minecart) e;
if (!this.bs.canSpawnCartSafely(m)) {
return null;
}
} else if (e instanceof Vehicle) {
Vehicle v = (Vehicle) e;
if (!this.bs.canSpawnVehicleSafely(v)) {
return null;
}
}
Location safeLocation = this.getSafeLocation(l);
if (safeLocation != null) {
// Add offset to account for a vehicle on dry land!
if (e instanceof Minecart && !this.bs.isEntitiyOnTrack(safeLocation)) {
safeLocation.setY(safeLocation.getBlockY() + .5);
this.plugin.log(Level.FINER, "Player was inside a minecart. Offsetting Y location.");
}
this.plugin.log(Level.FINE, "Had to look for a bit, but I found a safe place for ya!");
return safeLocation;
}
if (e instanceof Player) {
Player p = (Player) e;
this.plugin.getMessaging().sendMessage(p, "No safe locations found!", false);
this.plugin.log(Level.FINER, "No safe location found for " + p.getName());
} else if (e.getPassenger() instanceof Player) {
Player p = (Player) e.getPassenger();
this.plugin.getMessaging().sendMessage(p, "No safe locations found!", false);
this.plugin.log(Level.FINER, "No safe location found for " + p.getName());
}
this.plugin.log(Level.FINE, "Sorry champ, you're basically trying to teleport into a minefield. I should just kill you now.");
return null;
}
/**
* Finds a portal-block next to the specified {@link Location}.
* @param l The {@link Location}
* @return The next portal-block's {@link Location}.
*/
public static Location findPortalBlockNextTo(Location l) {
Block b = l.getWorld().getBlockAt(l);
Location foundLocation = null;
if (b.getType() == Material.PORTAL) {
return l;
}
if (b.getRelative(BlockFace.NORTH).getType() == Material.PORTAL) {
foundLocation = getCloserBlock(l, b.getRelative(BlockFace.NORTH).getLocation(), foundLocation);
}
if (b.getRelative(BlockFace.SOUTH).getType() == Material.PORTAL) {
foundLocation = getCloserBlock(l, b.getRelative(BlockFace.SOUTH).getLocation(), foundLocation);
}
if (b.getRelative(BlockFace.EAST).getType() == Material.PORTAL) {
foundLocation = getCloserBlock(l, b.getRelative(BlockFace.EAST).getLocation(), foundLocation);
}
if (b.getRelative(BlockFace.WEST).getType() == Material.PORTAL) {
foundLocation = getCloserBlock(l, b.getRelative(BlockFace.WEST).getLocation(), foundLocation);
}
return foundLocation;
}
private static Location getCloserBlock(Location source, Location blockA, Location blockB) {
// If B wasn't given, return a.
if (blockB == null) {
return blockA;
}
// Center our calculations
blockA.add(.5, 0, .5);
blockB.add(.5, 0, .5);
// Retrieve the distance to the normalized blocks
double testA = source.distance(blockA);
double testB = source.distance(blockB);
// Compare and return
if (testA <= testB) {
return blockA;
}
return blockB;
}
}
@@ -14,10 +14,9 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Bed;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Vehicle;
import org.bukkit.material.Bed;
import java.util.EnumSet;
import java.util.Iterator;
@@ -90,7 +89,7 @@ public class SimpleBlockSafety implements BlockSafety {
return false;
}
if (downOne.getBlock().getType() == Material.LAVA) {
if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) {
Logging.finer("Error Here (downOne)? (%s)[%s]", downOne.getBlock().getType(), isSolidBlock(downOne.getBlock().getType()));
return false;
}
@@ -152,13 +151,12 @@ public class SimpleBlockSafety implements BlockSafety {
* @return The location of the other bed piece, or null if it was a jacked up bed.
*/
private Location findOtherBedPiece(Location checkLoc) {
BlockData data = checkLoc.getBlock().getBlockData();
if (!(data instanceof Bed)) {
if (checkLoc.getBlock().getType() != Material.BED_BLOCK) {
return null;
}
Bed b = (Bed) data;
if (b.getPart() == Bed.Part.HEAD) {
// Construct a bed object at this location
final Bed b = new Bed(Material.BED_BLOCK, checkLoc.getBlock().getData());
if (b.isHeadOfBed()) {
return checkLoc.getBlock().getRelative(b.getFacing().getOppositeFace()).getLocation();
}
// We shouldn't ever be looking at the foot, but here's the code for it.
@@ -201,8 +199,69 @@ public class SimpleBlockSafety implements BlockSafety {
/*
* If someone has a better way of this... Please either tell us, or submit a pull request!
*/
public static boolean isSolidBlock(Material type) {
return type.isSolid();
private static boolean isSolidBlock(Material type) {
switch (type) {
case AIR:
return false;
case SNOW:
return false;
case TRAP_DOOR:
return false;
case TORCH:
return false;
case YELLOW_FLOWER:
return false;
case RED_ROSE:
return false;
case RED_MUSHROOM:
return false;
case BROWN_MUSHROOM:
return false;
case REDSTONE:
return false;
case REDSTONE_WIRE:
return false;
case RAILS:
return false;
case POWERED_RAIL:
return false;
case REDSTONE_TORCH_ON:
return false;
case REDSTONE_TORCH_OFF:
return false;
case DEAD_BUSH:
return false;
case SAPLING:
return false;
case STONE_BUTTON:
return false;
case LEVER:
return false;
case LONG_GRASS:
return false;
case PORTAL:
return false;
case STONE_PLATE:
return false;
case WOOD_PLATE:
return false;
case SEEDS:
return false;
case SUGAR_CANE_BLOCK:
return false;
case WALL_SIGN:
return false;
case SIGN_POST:
return false;
case WOODEN_DOOR:
return false;
case STATIONARY_WATER:
return false;
case WATER:
return false;
default:
return true;
}
}
/**
@@ -211,10 +270,7 @@ public class SimpleBlockSafety implements BlockSafety {
@Override
public boolean isEntitiyOnTrack(Location l) {
Material currentBlock = l.getBlock().getType();
return (currentBlock == Material.POWERED_RAIL
|| currentBlock == Material.DETECTOR_RAIL
|| currentBlock == Material.RAIL
|| currentBlock == Material.ACTIVATOR_RAIL);
return (currentBlock == Material.POWERED_RAIL || currentBlock == Material.DETECTOR_RAIL || currentBlock == Material.RAILS);
}
/**
@@ -229,10 +285,10 @@ public class SimpleBlockSafety implements BlockSafety {
}
Location oneBelow = l.clone();
oneBelow.subtract(0, 1, 0);
if (oneBelow.getBlock().getType() == Material.WATER) {
if (oneBelow.getBlock().getType() == Material.WATER || oneBelow.getBlock().getType() == Material.STATIONARY_WATER) {
Location twoBelow = oneBelow.clone();
twoBelow.subtract(0, 1, 0);
return (oneBelow.getBlock().getType() == Material.WATER);
return (oneBelow.getBlock().getType() == Material.WATER || oneBelow.getBlock().getType() == Material.STATIONARY_WATER);
}
if (oneBelow.getBlock().getType() != Material.AIR) {
return false;
@@ -19,7 +19,6 @@ import com.onarandombox.MultiverseCore.api.LocationManipulation;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
@@ -40,15 +39,6 @@ public class SimpleLocationManipulation implements LocationManipulation {
orientationInts.put("w", 90);
orientationInts.put("nw", 135);
orientationInts.put("north", 180);
orientationInts.put("northeast", 225);
orientationInts.put("east", 270);
orientationInts.put("southeast", 315);
orientationInts.put("south", 0);
orientationInts.put("southwest", 45);
orientationInts.put("west", 90);
orientationInts.put("northwest", 135);
// "freeze" the map:
ORIENTATION_INTS = Collections.unmodifiableMap(orientationInts);
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
@@ -62,7 +52,7 @@ public class SimpleLocationManipulation implements LocationManipulation {
if (location == null) {
return "";
}
return String.format(Locale.ENGLISH, "%s:%.2f,%.2f,%.2f:%.2f:%.2f", location.getWorld().getName(),
return String.format("%s:%.2f,%.2f,%.2f:%.2f:%.2f", location.getWorld().getName(),
location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
}
@@ -7,7 +7,6 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.api.MVDestination;
@@ -31,6 +30,7 @@ import java.util.logging.Level;
* The default-implementation of {@link SafeTTeleporter}.
*/
public class SimpleSafeTTeleporter implements SafeTTeleporter {
private MultiverseCore plugin;
public SimpleSafeTTeleporter(MultiverseCore plugin) {
@@ -59,9 +59,9 @@ public class SimpleSafeTTeleporter implements SafeTTeleporter {
if (safe != null) {
safe.setX(safe.getBlockX() + .5); // SUPPRESS CHECKSTYLE: MagicNumberCheck
safe.setZ(safe.getBlockZ() + .5); // SUPPRESS CHECKSTYLE: MagicNumberCheck
Logging.fine("Hey! I found one: " + plugin.getLocationManipulation().strCoordsRaw(safe));
this.plugin.log(Level.FINE, "Hey! I found one: " + plugin.getLocationManipulation().strCoordsRaw(safe));
} else {
Logging.fine("Uh oh! No safe place found!");
this.plugin.log(Level.FINE, "Uh oh! No safe place found!");
}
return safe;
}
@@ -73,8 +73,8 @@ public class SimpleSafeTTeleporter implements SafeTTeleporter {
}
// We want half of it, so we can go up and down
tolerance /= 2;
Logging.finer("Given Location of: " + plugin.getLocationManipulation().strCoordsRaw(l));
Logging.finer("Checking +-" + tolerance + " with a radius of " + radius);
this.plugin.log(Level.FINER, "Given Location of: " + plugin.getLocationManipulation().strCoordsRaw(l));
this.plugin.log(Level.FINER, "Checking +-" + tolerance + " with a radius of " + radius);
// For now this will just do a straight up block.
Location locToCheck = l.clone();
@@ -192,7 +192,7 @@ public class SimpleSafeTTeleporter implements SafeTTeleporter {
@Override
public TeleportResult safelyTeleport(CommandSender teleporter, Entity teleportee, MVDestination d) {
if (d instanceof InvalidDestination) {
Logging.finer("Entity tried to teleport to an invalid destination");
this.plugin.log(Level.FINER, "Entity tried to teleport to an invalid destination");
return TeleportResult.FAIL_INVALID;
}
Player teleporteePlayer = null;
@@ -249,7 +249,7 @@ public class SimpleSafeTTeleporter implements SafeTTeleporter {
public Location getSafeLocation(Entity e, MVDestination d) {
Location l = d.getLocation(e);
if (plugin.getBlockSafety().playerCanSpawnHereSafely(l)) {
Logging.fine("The first location you gave me was safe.");
plugin.log(Level.FINE, "The first location you gave me was safe.");
return l;
}
if (e instanceof Minecart) {
@@ -268,21 +268,21 @@ public class SimpleSafeTTeleporter implements SafeTTeleporter {
// Add offset to account for a vehicle on dry land!
if (e instanceof Minecart && !plugin.getBlockSafety().isEntitiyOnTrack(safeLocation)) {
safeLocation.setY(safeLocation.getBlockY() + .5);
Logging.finer("Player was inside a minecart. Offsetting Y location.");
this.plugin.log(Level.FINER, "Player was inside a minecart. Offsetting Y location.");
}
Logging.finer("Had to look for a bit, but I found a safe place for ya!");
this.plugin.log(Level.FINE, "Had to look for a bit, but I found a safe place for ya!");
return safeLocation;
}
if (e instanceof Player) {
Player p = (Player) e;
this.plugin.getMessaging().sendMessage(p, "No safe locations found!", false);
Logging.finer("No safe location found for " + p.getName());
this.plugin.log(Level.FINER, "No safe location found for " + p.getName());
} else if (e.getPassenger() instanceof Player) {
Player p = (Player) e.getPassenger();
this.plugin.getMessaging().sendMessage(p, "No safe locations found!", false);
Logging.finer("No safe location found for " + p.getName());
this.plugin.log(Level.FINER, "No safe location found for " + p.getName());
}
Logging.fine("Sorry champ, you're basically trying to teleport into a minefield. I should just kill you now.");
this.plugin.log(Level.FINE, "Sorry champ, you're basically trying to teleport into a minefield. I should just kill you now.");
return null;
}
@@ -293,19 +293,19 @@ public class SimpleSafeTTeleporter implements SafeTTeleporter {
public Location findPortalBlockNextTo(Location l) {
Block b = l.getWorld().getBlockAt(l);
Location foundLocation = null;
if (b.getType() == Material.NETHER_PORTAL) {
if (b.getType() == Material.PORTAL) {
return l;
}
if (b.getRelative(BlockFace.NORTH).getType() == Material.NETHER_PORTAL) {
if (b.getRelative(BlockFace.NORTH).getType() == Material.PORTAL) {
foundLocation = getCloserBlock(l, b.getRelative(BlockFace.NORTH).getLocation(), foundLocation);
}
if (b.getRelative(BlockFace.SOUTH).getType() == Material.NETHER_PORTAL) {
if (b.getRelative(BlockFace.SOUTH).getType() == Material.PORTAL) {
foundLocation = getCloserBlock(l, b.getRelative(BlockFace.SOUTH).getLocation(), foundLocation);
}
if (b.getRelative(BlockFace.EAST).getType() == Material.NETHER_PORTAL) {
if (b.getRelative(BlockFace.EAST).getType() == Material.PORTAL) {
foundLocation = getCloserBlock(l, b.getRelative(BlockFace.EAST).getLocation(), foundLocation);
}
if (b.getRelative(BlockFace.WEST).getType() == Material.NETHER_PORTAL) {
if (b.getRelative(BlockFace.WEST).getType() == Material.PORTAL) {
foundLocation = getCloserBlock(l, b.getRelative(BlockFace.WEST).getLocation(), foundLocation);
}
return foundLocation;
@@ -331,8 +331,4 @@ public class SimpleSafeTTeleporter implements SafeTTeleporter {
return blockB;
}
@Override
public TeleportResult teleport(final CommandSender teleporter, final Player teleportee, final MVDestination destination) {
return this.safelyTeleport(teleporter, teleportee, destination);
}
}
@@ -20,7 +20,6 @@ import org.bukkit.entity.Ghast;
import org.bukkit.entity.Golem;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Phantom;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Squid;
@@ -149,7 +148,7 @@ public class SimpleWorldPurger implements WorldPurger {
if (specifiedAnimals)
specified = true;
negate = negateAnimals;
} else if (e instanceof Monster || e instanceof Ghast || e instanceof Slime || e instanceof Phantom) {
} else if (e instanceof Monster || e instanceof Ghast || e instanceof Slime) {
// it's a monster
if (specifiedMonsters && !negateMonsters) {
Logging.finest("Removing an entity because I was told to remove all monsters in world %s: %s", e.getWorld().getName(), e);
@@ -0,0 +1,30 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
/*
package com.onarandombox.MultiverseCore.utils;
import org.getspout.spoutapi.SpoutManager;
/**
* A helper-class holding the {@link SpoutManager}.
* /
public class SpoutInterface {
private SpoutManager spoutManager;
public SpoutInterface() {
this.spoutManager = SpoutManager.getInstance();
}
/**
* Gets the {@link SpoutManager}.
* @return The {@link SpoutManager}.
* /
public SpoutManager getManager() {
return this.spoutManager;
}
}
*/
@@ -1,18 +0,0 @@
package com.onarandombox.MultiverseCore.utils;
/**
* A utility class that enables automated tests to flag Multiverse for testing. This allows Multiverse to not perform
* certain behaviors such as enabled stats uploads.
*/
public class TestingMode {
private static boolean enabled = false;
public static void enable() {
enabled = true;
}
public static boolean isDisabled() {
return !enabled;
}
}
@@ -0,0 +1,130 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/*
* Apparently this isn't used and I don't know if we'll ever use this,
* so I'm just going to deprecate it for now and suppress the warnings.
*
* BEGIN CHECKSTYLE-SUPPRESSION: ALL
*/
/**
* @deprecated Currently unused.
*/
@Deprecated
public class UpdateChecker {
public static final Logger log = Logger.getLogger("Minecraft");
private Timer timer = new Timer(); // Create a new Timer.
private String name; // Hold the Plugins Name.
private String cversion; // Hold the Plugins Current Version.
public UpdateChecker(String name, String version) {
this.name = name;
this.cversion = version;
int delay = 0; // No Delay, fire the first check instantly.
int period = 1800; // Delay 30 Minutes
this.timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
checkUpdate();
}
}, delay * 1000, period * 1000);
}
public void checkUpdate() {
BufferedReader rd = null;
try {
URL url = new URL("http://bukkit.onarandombox.com/multiverse/version.php?n=" + URLEncoder.encode(this.name, "UTF-8") + "&v=" + this.cversion);
URLConnection conn = url.openConnection();
conn.setReadTimeout(2000); // 2000 = 2 Seconds.
int code = ((HttpURLConnection) conn).getResponseCode();
if (code != 200) {
return;
}
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String version = null;
while ((line = rd.readLine()) != null) {
if (version == null) {
version = line;
}
}
if (version == null) {
return;
}
String v1 = normalisedVersion(version);
String v2 = normalisedVersion(this.cversion);
int compare = v1.compareTo(v2);
if (compare > 0) {
Logging.info("[%s] - Update Available (%s)", this.name, version);
}
rd.close();
} catch (Exception e) {
// No need to alert the user of any error here... it's not important.
} finally {
if (rd != null) {
try {
rd.close();
} catch (IOException ignore) { }
}
}
}
/**
* Convert the given Version String to a Normalized Version String so we can compare it.
*
* @param version The version string
* @return The normalized version string
*/
public static String normalisedVersion(String version) {
return normalisedVersion(version, ".", 4);
}
public static String normalisedVersion(String version, String sep, int maxWidth) {
String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
StringBuilder sb = new StringBuilder();
for (String s : split) {
sb.append(String.format("%" + maxWidth + 's', s));
}
return sb.toString();
}
}
/*
* END CHECKSTYLE-SUPPRESSION: ALL
*/
@@ -56,20 +56,11 @@ public class VaultHandler implements Listener {
private void vaultDisabled(PluginDisableEvent event) {
if (event.getPlugin() != null && event.getPlugin().getName().equals("Vault")) {
Logging.fine("Vault economy disabled");
economy = null;
setupVaultEconomy();
}
}
}
/**
* Checks whether Vault is in use and has an economy system enabled.
*
* @return true if vault is in use and has an economy system enabled.
*/
public boolean hasEconomy() {
return economy != null;
}
/**
* Returns the Vault economy system if Vault is present and has an economy system enabled.
*
@@ -10,14 +10,13 @@ package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MVWorld;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.MultiverseCoreConfiguration;
import com.onarandombox.MultiverseCore.WorldProperties;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.api.WorldPurger;
import com.onarandombox.MultiverseCore.event.MVWorldDeleteEvent;
import org.bukkit.Bukkit;
import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
@@ -43,19 +42,16 @@ import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.logging.Logger;
/**
* Public facing API to add/remove Multiverse worlds.
*/
public class WorldManager implements MVWorldManager {
private final MultiverseCore plugin;
private final Pattern worldNamePattern = Pattern.compile("[a-zA-Z0-9/._-]+");
private final WorldPurger worldPurger;
private final Map<String, MultiverseWorld> worlds;
private Map<String, WorldProperties> worldsFromTheConfig;
@@ -74,7 +70,6 @@ public class WorldManager implements MVWorldManager {
* {@inheritDoc}
*/
@Override
@Deprecated
public void getDefaultWorldGenerators() {
this.defaultGens = new HashMap<String, String>();
File[] files = this.plugin.getServerFolder().listFiles(new FilenameFilter() {
@@ -92,131 +87,86 @@ public class WorldManager implements MVWorldManager {
}
}
} else {
Logging.warning("Could not read 'bukkit.yml'. Any Default worldgenerators will not be loaded!");
this.plugin.log(Level.WARNING, "Could not read 'bukkit.yml'. Any Default worldgenerators will not be loaded!");
}
}
/**
* {@inheritDoc}
* @deprecated Use {@link #cloneWorld(String, String)} instead.
*/
@Override
@Deprecated
public boolean cloneWorld(String oldName, String newName, String generator) {
return this.cloneWorld(oldName, newName);
}
/**
* {@inheritDoc}
*/
@Override
public boolean cloneWorld(String oldName, String newName) {
// Make sure we already know about the old world and that we don't
// already know about the new world.
if (!this.worldsFromTheConfig.containsKey(oldName)) {
for (Map.Entry<String, WorldProperties> entry : this.worldsFromTheConfig.entrySet()) {
if (oldName.equals(entry.getValue().getAlias())) {
oldName = entry.getKey();
break;
}
}
if (!this.worldsFromTheConfig.containsKey(oldName)) {
Logging.warning("Old world '%s' does not exist", oldName);
return false;
}
}
// Make sure we don't already know about the new world.
if (this.isMVWorld(newName)) {
Logging.warning("New world '%s' already exists", newName);
return false;
}
// Check for valid world name
if (!(WorldNameChecker.isValidWorldName(oldName) && WorldNameChecker.isValidWorldName(oldName))) {
// Make sure the old world is actually a world!
if (this.getUnloadedWorlds().contains(oldName) || !this.isMVWorld(oldName)) {
return false;
}
final File oldWorldFile = new File(this.plugin.getServer().getWorldContainer(), oldName);
final File newWorldFile = new File(this.plugin.getServer().getWorldContainer(), newName);
final List<String> ignoreFiles = new ArrayList<>(Arrays.asList("session.lock", "uid.dat"));
// Make sure the new world doesn't exist outside of multiverse.
if (newWorldFile.exists()) {
Logging.warning("Folder for new world '%s' already exists", newName);
return false;
}
// Load the old world... but just the metadata.
boolean wasJustLoaded = false;
boolean wasLoadSpawn = false;
if (this.plugin.getServer().getWorld(oldName) == null) {
wasJustLoaded = true;
WorldProperties props = this.worldsFromTheConfig.get(oldName);
wasLoadSpawn = props.isKeepingSpawnInMemory();
if (wasLoadSpawn) {
// No chunks please.
props.setKeepSpawnInMemory(false);
}
if (!this.loadWorld(oldName)) {
return false;
}
this.plugin.getServer().getWorld(oldName).setAutoSave(false);
}
// Grab a bit of metadata from the old world.
MultiverseWorld oldWorld = getMVWorld(oldName);
unloadWorld(oldName);
// Don't need the loaded world anymore.
if (wasJustLoaded) {
this.unloadWorld(oldName, true);
oldWorld = null;
if (wasLoadSpawn) {
this.worldsFromTheConfig.get(oldName).setKeepSpawnInMemory(true);
}
}
removePlayersFromWorld(oldName);
boolean wasAutoSave = false;
if (oldWorld != null && oldWorld.getCBWorld().isAutoSave()) {
wasAutoSave = true;
Logging.config("Saving world '%s'", oldName);
oldWorld.getCBWorld().setAutoSave(false);
oldWorld.getCBWorld().save();
}
Logging.config("Copying files for world '%s'", oldName);
if (!FileUtils.copyFolder(oldWorldFile, newWorldFile, ignoreFiles)) {
Logging.warning("Failed to copy files for world '%s', see the log info", newName);
Logging.config("Copying data for world '%s'", oldName);
try {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
FileUtils.copyFolder(oldWorldFile, newWorldFile, Logger.getLogger("Minecraft"));
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// do nothing
}
File uidFile = new File(newWorldFile, "uid.dat");
uidFile.delete();
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
if (oldWorld != null && wasAutoSave) {
oldWorld.getCBWorld().setAutoSave(true);
}
Logging.fine("Kind of copied stuff");
WorldCreator worldCreator = new WorldCreator(newName);
Logging.fine("Started to copy settings");
worldCreator.copy(this.getMVWorld(oldName).getCBWorld());
Logging.fine("Copied lots of settings");
boolean useSpawnAdjust = this.getMVWorld(oldName).getAdjustSpawn();
Logging.fine("Copied more settings");
Environment environment = worldCreator.environment();
Logging.fine("Copied most settings");
if (newWorldFile.exists()) {
Logging.fine("Succeeded at copying files");
// initialize new properties with old ones
WorldProperties newProps = new WorldProperties();
newProps.copyValues(this.worldsFromTheConfig.get(oldName));
// don't keep the alias the same -- that would be useless
newProps.setAlias("");
// store the new properties in worlds config map
this.worldsFromTheConfig.put(newName, newProps);
// save the worlds config to disk (worlds.yml)
if (!saveWorldsConfig()) {
Logging.severe("Failed to save worlds.yml");
return false;
Logging.fine("Succeeded at copying stuff");
if (this.addWorld(newName, environment, null, null, null, generator, useSpawnAdjust)) {
// getMVWorld() doesn't actually return an MVWorld
Logging.fine("Succeeded at importing stuff");
MVWorld newWorld = (MVWorld) this.getMVWorld(newName);
MVWorld oldWorld = (MVWorld) this.getMVWorld(oldName);
newWorld.copyValues(oldWorld);
try {
// don't keep the alias the same -- that would be useless
newWorld.setPropertyValue("alias", newName);
} catch (PropertyDoesNotExistException e) {
// this should never happen
throw new RuntimeException(e);
}
return true;
}
// actually load the world
if (doLoad(newName)) {
Logging.fine("Succeeded at loading cloned world '" + newName + "'");
return true;
}
Logging.severe("Failed to load the cloned world '" + newName + "'");
return false;
}
Logging.warning("Failed to copy files for world '%s', see the log info", newName);
return false;
}
@@ -235,16 +185,6 @@ public class WorldManager implements MVWorldManager {
@Override
public boolean addWorld(String name, Environment env, String seedString, WorldType type, Boolean generateStructures,
String generator, boolean useSpawnAdjust) {
if (name.equalsIgnoreCase("plugins") || name.equalsIgnoreCase("logs")) {
return false;
}
if (!WorldNameChecker.isValidWorldName(name)) {
Logging.warning("Invalid world name '" + name + "'");
Logging.warning("World name should not contain spaces or special characters!");
return false;
}
Long seed = null;
WorldCreator c = new WorldCreator(name);
if (seedString != null && seedString.length() > 0) {
@@ -287,7 +227,7 @@ public class WorldManager implements MVWorldManager {
Logging.info(builder.toString());
if (!doLoad(c, true)) {
Logging.severe("Failed to Create/Load the world '" + name + "'");
this.plugin.log(Level.SEVERE, "Failed to Create/Load the world '" + name + "'");
return false;
}
@@ -302,7 +242,6 @@ public class WorldManager implements MVWorldManager {
* {@inheritDoc}
*/
@Override
@Deprecated
public ChunkGenerator getChunkGenerator(String generator, final String generatorID, final String worldName) {
if (generator == null) {
return null;
@@ -361,7 +300,7 @@ public class WorldManager implements MVWorldManager {
MultiverseWorld world = this.getMVWorld(this.firstSpawn);
if (world == null) {
// If the spawn world was unloaded, get the default world
Logging.warning("The world specified as the spawn world (" + this.firstSpawn + ") did not exist!!");
this.plugin.log(Level.WARNING, "The world specified as the spawn world (" + this.firstSpawn + ") did not exist!!");
try {
return this.getMVWorld(this.plugin.getServer().getWorlds().get(0));
} catch (IndexOutOfBoundsException e) {
@@ -377,21 +316,9 @@ public class WorldManager implements MVWorldManager {
*/
@Override
public boolean unloadWorld(String name) {
return this.unloadWorld(name, true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean unloadWorld(String name, boolean unloadBukkit) {
if (this.worlds.containsKey(name)) {
this.worldsFromTheConfig.get(name).cacheVirtualProperties();
if (unloadBukkit && this.unloadWorldFromBukkit(name, true)) {
this.worlds.remove(name);
Logging.info("World '%s' was unloaded from memory.", name);
return true;
} else if (!unloadBukkit){
if (this.unloadWorldFromBukkit(name, true)) {
this.worlds.remove(name);
Logging.info("World '%s' was unloaded from memory.", name);
return true;
@@ -429,15 +356,9 @@ public class WorldManager implements MVWorldManager {
}
private void brokenWorld(String name) {
Logging.severe("The world '" + name + "' could NOT be loaded because it contains errors and is probably corrupt!");
Logging.severe("Try using Minecraft Region Fixer to repair your world! '" + name + "'");
Logging.severe("https://github.com/Fenixin/Minecraft-Region-Fixer");
}
private void nullWorld(String name) {
Logging.severe("The world '" + name + "' could NOT be loaded because the server didn't like it!");
Logging.severe("We don't really know why this is. Contact the developer of your server software!");
Logging.severe("Server version info: " + Bukkit.getServer().getVersion());
this.plugin.log(Level.SEVERE, "The world '" + name + "' could NOT be loaded because it contains errors!");
this.plugin.log(Level.SEVERE, "Try using Chukster to repair your world! '" + name + "'");
this.plugin.log(Level.SEVERE, "http://forums.bukkit.org/threads/admin-chunkster.8186/");
}
private boolean doLoad(String name) {
@@ -476,9 +397,9 @@ public class WorldManager implements MVWorldManager {
if (worlds.containsKey(worldName))
throw new IllegalArgumentException("That world is already loaded!");
if (!ignoreExists && !new File(this.plugin.getServer().getWorldContainer(), worldName).exists() && !new File(this.plugin.getServer().getWorldContainer().getParent(), worldName).exists()) {
Logging.warning("WorldManager: Can't load this world because the folder was deleted/moved: " + worldName);
Logging.warning("Use '/mv remove' to remove it from the config!");
if (!ignoreExists && !new File(this.plugin.getServer().getWorldContainer(), worldName).exists()) {
this.plugin.log(Level.WARNING, "WorldManager: Can't load this world because the folder was deleted/moved: " + worldName);
this.plugin.log(Level.WARNING, "Use '/mv remove' to remove it from the config!");
return false;
}
@@ -491,14 +412,8 @@ public class WorldManager implements MVWorldManager {
brokenWorld(worldName);
return false;
}
if (cbworld == null) {
nullWorld(worldName);
return false;
}
MVWorld world = new MVWorld(plugin, cbworld, mvworld);
if (MultiverseCoreConfiguration.getInstance().isAutoPurgeEnabled()) {
this.worldPurger.purgeWorld(world);
}
this.worldPurger.purgeWorld(world);
this.worlds.put(worldName, world);
return true;
}
@@ -508,13 +423,6 @@ public class WorldManager implements MVWorldManager {
*/
@Override
public boolean deleteWorld(String name, boolean removeFromConfig, boolean deleteWorldFolder) {
if (this.hasUnloadedWorld(name, false)) {
// Attempt to load if unloaded so we can actually delete the world
if (!this.doLoad(name)) {
return false;
}
}
World world = this.plugin.getServer().getWorld(name);
if (world == null) {
// We can only delete loaded worlds
@@ -525,7 +433,7 @@ public class WorldManager implements MVWorldManager {
MVWorldDeleteEvent mvwde = new MVWorldDeleteEvent(getMVWorld(name), removeFromConfig);
this.plugin.getServer().getPluginManager().callEvent(mvwde);
if (mvwde.isCancelled()) {
Logging.fine("Tried to delete a world, but the event was cancelled!");
this.plugin.log(Level.FINE, "Tried to delete a world, but the event was cancelled!");
return false;
}
@@ -541,7 +449,7 @@ public class WorldManager implements MVWorldManager {
try {
File worldFile = world.getWorldFolder();
Logging.finer("deleteWorld(): worldFile: " + worldFile.getAbsolutePath());
plugin.log(Level.FINER, "deleteWorld(): worldFile: " + worldFile.getAbsolutePath());
if (deleteWorldFolder ? FileUtils.deleteFolder(worldFile) : FileUtils.deleteFolderContents(worldFile)) {
Logging.info("World '%s' was DELETED.", name);
return true;
@@ -696,7 +604,10 @@ public class WorldManager implements MVWorldManager {
for (World w : myWorlds) {
String name = w.getName();
if (!worldsFromTheConfig.containsKey(name)) {
String generator = this.plugin.getMVGeneratorManager().getDefaultWorldGen(name);
String generator = null;
if (this.defaultGens.containsKey(name)) {
generator = this.defaultGens.get(name);
}
this.addWorld(name, w.getEnvironment(), String.valueOf(w.getSeed()), w.getWorldType(), w.canGenerateStructures(), generator);
}
}
@@ -787,11 +698,6 @@ public class WorldManager implements MVWorldManager {
private static final char SEPARATOR = '\uF8FF';
public boolean isKeepingSpawnInMemory(World world) {
WorldProperties properties = worldsFromTheConfig.get(world.getName());
return properties == null || properties.isKeepingSpawnInMemory();
}
/**
* {@inheritDoc}
*/
@@ -852,7 +758,7 @@ public class WorldManager implements MVWorldManager {
this.configWorlds.save(new File(this.plugin.getDataFolder(), "worlds.yml"));
return true;
} catch (IOException e) {
Logging.severe("Could not save worlds.yml. Please check your settings.");
this.plugin.log(Level.SEVERE, "Could not save worlds.yml. Please check your settings.");
return false;
}
}
@@ -923,20 +829,4 @@ public class WorldManager implements MVWorldManager {
public FileConfiguration getConfigWorlds() {
return this.configWorlds;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasUnloadedWorld(String name, boolean includeLoaded) {
if (getMVWorld(name) != null) {
return includeLoaded;
}
for (Map.Entry<String, WorldProperties> entry : this.worldsFromTheConfig.entrySet()) {
if (name.equals(entry.getKey()) || name.equals(entry.getValue().getAlias())) {
return true;
}
}
return false;
}
}
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more