Compare commits

..
Author SHA1 Message Date
main() d65cc8215c Testing... 2012-05-03 17:05:17 +02:00
main() c6feb127de Rewritten for SerializationConfig
Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/MVWorld.java
	src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java
2012-05-03 16:47:11 +02:00
main() 77480915a1 Merge branch 'master' of github.com:Multiverse/Multiverse-Core into allow-flight 2012-04-30 14:31:06 +02:00
main() c233b74c98 Merge branch 'master' into allow-flight
Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java
2012-02-26 16:50:02 +01:00
main() ae95a4c4f9 Merge branch 'master' of github.com:Multiverse/Multiverse-Core into allow-flight 2012-02-04 20:00:21 +01:00
Eric Stokes 49fd9e81d1 Inital allow flight code, if we use it 2012-01-29 16:57:16 -07:00
139 changed files with 3397 additions and 6805 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]
-6
View File
@@ -1,6 +0,0 @@
language: java
jdk:
- oraclejdk8
notifications:
email: false
dist: trusty
-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.
+2
View File
@@ -104,6 +104,7 @@
</module>
<module name="LeftCurly"/>
<module name="RightCurly"/>
<module name="DoubleCheckedLocking"/>
<module name="EmptyStatement"/>
<module name="EqualsHashCode"/>
<module name="HiddenField">
@@ -115,6 +116,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
+77 -209
View File
@@ -3,40 +3,22 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.onarandombox.multiversecore</groupId>
<artifactId>Multiverse-Core</artifactId>
<version>4.2.3-SNAPSHOT</version>
<version>2.4</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>
</repository>
<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>Bukkit Official</id>
<url>http://repo.bukkit.org/content/repositories/public</url>
</repository>
</repositories>
@@ -70,17 +52,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 +61,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>
@@ -153,10 +101,16 @@
</archive>
</configuration>
</plugin>
<!-- Maven Source Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
</plugin>
<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,53 +123,23 @@
<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.8</version>
<configuration>
<enableRulesSummary>true</enableRulesSummary>
<configLocation>${project.basedir}/config/mv_checks.xml</configLocation>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<executions>
<execution>
<id>javadoc-jar</id>
<phase>verify</phase>
<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.1.1</version>
<version>1.5</version>
<executions>
<execution>
<phase>package</phase>
@@ -223,175 +147,119 @@
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>me.main__.util:SerializationConfig</include>
<include>com.fernferret.allpay:AllPay</include>
<include>com.pneumaticraft.commandhandler:CommandHandler</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>
</relocation>
<relocation>
<pattern>buscript</pattern>
<shadedPattern>com.onarandombox.buscript</shadedPattern>
</relocation>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>com.onarandombox.bstats</shadedPattern>
</relocation>
<relocation>
<pattern>com.dumptruckman.minecraft.util.Logging</pattern>
<shadedPattern>com.onarandombox.MultiverseCore.utils.CoreLogging</shadedPattern>
</relocation>
<relocation>
<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>
<shadedPattern>com.pneumaticraft.commandhandler.multiverse</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>se.eris</groupId>
<artifactId>notnull-instrumenter-maven-plugin</artifactId>
<version>0.6.8</version>
<executions>
<execution>
<goals>
<goal>instrument</goal>
<goal>tests-instrument</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Bukkit Dependency -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.13.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.2.5-R1.0</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>
<version>1.6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of SerializationConfig Dependency -->
<!-- Start of Economy Dependency -->
<!-- Start of AllPay Dependency -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
<groupId>com.fernferret.allpay</groupId>
<artifactId>AllPay</artifactId>
<version>10</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of Economy Dependency -->
<!-- End of AllPay 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>
<dependency>
<groupId>com.dumptruckman.minecraft</groupId>
<artifactId>buscript</artifactId>
<version>2.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.7</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.dumptruckman.minecraft</groupId>
<artifactId>Logging</artifactId>
<version>1.1.1</version>
</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 CommandHandler 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.0</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.0</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.0</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>
File diff suppressed because it is too large. Load diff
@@ -7,24 +7,8 @@
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.onarandombox.MultiverseCore.MVWorld.NullLocation;
import com.fernferret.allpay.AllPay;
import com.fernferret.allpay.GenericBank;
import com.onarandombox.MultiverseCore.api.BlockSafety;
import com.onarandombox.MultiverseCore.api.Core;
import com.onarandombox.MultiverseCore.api.LocationManipulation;
@@ -32,42 +16,9 @@ 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;
import com.onarandombox.MultiverseCore.commands.CloneCommand;
import com.onarandombox.MultiverseCore.commands.ConfigCommand;
import com.onarandombox.MultiverseCore.commands.ConfirmCommand;
import com.onarandombox.MultiverseCore.commands.CoordCommand;
import com.onarandombox.MultiverseCore.commands.CreateCommand;
import com.onarandombox.MultiverseCore.commands.DebugCommand;
import com.onarandombox.MultiverseCore.commands.DeleteCommand;
import com.onarandombox.MultiverseCore.commands.EnvironmentCommand;
import com.onarandombox.MultiverseCore.commands.GameruleCommand;
import com.onarandombox.MultiverseCore.commands.GamerulesCommand;
import com.onarandombox.MultiverseCore.commands.GeneratorCommand;
import com.onarandombox.MultiverseCore.commands.HelpCommand;
import com.onarandombox.MultiverseCore.commands.ImportCommand;
import com.onarandombox.MultiverseCore.commands.InfoCommand;
import com.onarandombox.MultiverseCore.commands.ListCommand;
import com.onarandombox.MultiverseCore.commands.LoadCommand;
import com.onarandombox.MultiverseCore.commands.ModifyAddCommand;
import com.onarandombox.MultiverseCore.commands.ModifyClearCommand;
import com.onarandombox.MultiverseCore.commands.ModifyCommand;
import com.onarandombox.MultiverseCore.commands.ModifyRemoveCommand;
import com.onarandombox.MultiverseCore.commands.ModifySetCommand;
import com.onarandombox.MultiverseCore.commands.PurgeCommand;
import com.onarandombox.MultiverseCore.commands.RegenCommand;
import com.onarandombox.MultiverseCore.commands.ReloadCommand;
import com.onarandombox.MultiverseCore.commands.RemoveCommand;
import com.onarandombox.MultiverseCore.commands.ScriptCommand;
import com.onarandombox.MultiverseCore.commands.SetSpawnCommand;
import com.onarandombox.MultiverseCore.commands.SilentCommand;
import com.onarandombox.MultiverseCore.commands.SpawnCommand;
import com.onarandombox.MultiverseCore.commands.TeleportCommand;
import com.onarandombox.MultiverseCore.commands.UnloadCommand;
import com.onarandombox.MultiverseCore.commands.VersionCommand;
import com.onarandombox.MultiverseCore.commands.WhoCommand;
import com.onarandombox.MultiverseCore.commands.*;
import com.onarandombox.MultiverseCore.destination.AnchorDestination;
import com.onarandombox.MultiverseCore.destination.BedDestination;
import com.onarandombox.MultiverseCore.destination.CannonDestination;
@@ -75,79 +26,55 @@ 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.listeners.MVAsyncPlayerChatListener;
import com.onarandombox.MultiverseCore.listeners.MVChatListener;
import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException;
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.MVPortalListener;
import com.onarandombox.MultiverseCore.listeners.MVPluginListener;
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.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;
import com.onarandombox.MultiverseCore.utils.UnsafeCallWrapper;
import com.onarandombox.MultiverseCore.utils.VaultHandler;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import com.onarandombox.MultiverseCore.listeners.MVPortalListener;
import com.onarandombox.MultiverseCore.utils.*;
import com.pneumaticraft.commandhandler.CommandHandler;
import me.main__.util.SerializationConfig.NoSuchPropertyException;
import me.main__.util.SerializationConfig.SerializationConfig;
import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
import org.bukkit.Location;
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 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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* 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 = 14;
// TODO: Investigate if this one is really needed to be static.
// Doubt it. -- FernFerret
private static final Map<String, String> teleportQueue = new HashMap<String, String>();
private static Map<String, String> teleportQueue = new HashMap<String, String>();
private final AnchorManager anchorManager = new AnchorManager(this);
private AnchorManager anchorManager = new AnchorManager(this);
// 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);
}
private MultiverseCoreConfiguration config;
/**
* This method is used to find out who is teleporting a player.
@@ -170,10 +97,15 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
* @param teleportee The name of the player that was teleported.
*/
public static void addPlayerToTeleportQueue(String teleporter, String teleportee) {
Logging.finest("Adding mapping '%s' => '%s' to teleport queue", teleporter, teleportee);
staticLog(Level.FINEST, "Adding mapping '" + teleporter + "' => '" + teleportee + "' to teleport queue");
teleportQueue.put(teleportee, teleporter);
}
@Override
public String toString() {
return "The Multiverse-Core Plugin";
}
/**
* {@inheritDoc}
* @deprecated This is now deprecated, nobody needs it any longer.
@@ -201,6 +133,10 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return MultiverseCore.PROTOCOL;
}
// Useless stuff to keep us going.
private static final Logger LOGGER = Logger.getLogger("Minecraft");
private static DebugLog debugLog;
// Setup our Map for our Commands using the CommandHandler.
private CommandHandler commandHandler;
@@ -212,27 +148,26 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Configurations
private FileConfiguration multiverseConfig = null;
private final MVWorldManager worldManager = new WorldManager(this);
private 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 MVWeatherListener weatherListener = new MVWeatherListener(this);
private final MVPortalListener portalListener = new MVPortalListener(this);
private final MVWorldListener worldListener = new MVWorldListener(this);
private MVChatListener chatListener;
private MVPlayerListener playerListener = new MVPlayerListener(this);
private MVEntityListener entityListener = new MVEntityListener(this);
private MVPluginListener pluginListener = new MVPluginListener(this);
private MVWeatherListener weatherListener = new MVWeatherListener(this);
private MVPortalListener portalListener = new MVPortalListener(this);
// HashMap to contain information relating to the Players.
private HashMap<String, MVPlayerSession> playerSessions;
private MVEconomist economist;
private Buscript buscript;
private GenericBank bank = null;
private AllPay banker;
private int pluginCount;
private DestinationFactory destFactory;
//private SpoutInterface spoutInterface = null;
private MultiverseMessaging messaging;
private BlockSafety blockSafety;
private LocationManipulation locationManipulation;
private SafeTTeleporter safeTTeleporter;
private UnsafeCallWrapper unsafeCallWrapper;
private File serverFolder = new File(System.getProperty("user.dir"));
@@ -241,30 +176,35 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Register our config
SerializationConfig.registerAll(MultiverseCoreConfiguration.class);
// Register our world
SerializationConfig.registerAll(WorldProperties.class);
SerializationConfig.registerAll(MVWorld.class);
// Create our DataFolder
getDataFolder().mkdirs();
// Setup our Debug Log
Logging.init(this);
SerializationConfig.initLogging(Logging.getLogger());
debugLog = new DebugLog("Multiverse-Core", getDataFolder() + File.separator + "debug.log");
// Setup our BlockSafety
this.blockSafety = new SimpleBlockSafety(this);
// Setup our LocationManipulation
this.locationManipulation = new SimpleLocationManipulation();
// Setup our SafeTTeleporter
this.safeTTeleporter = new SimpleSafeTTeleporter(this);
this.unsafeCallWrapper = new UnsafeCallWrapper(this);
}
/**
* {@inheritDoc}
* @deprecated This is deprecated.
*/
@Override
@Deprecated
public VaultHandler getVaultHandler() {
return getEconomist().getVaultHandler();
public FileConfiguration getMVConfiguration() {
return this.multiverseConfig;
}
public MVEconomist getEconomist() {
return economist;
/**
* {@inheritDoc}
*/
@Override
public GenericBank getBank() {
return this.bank;
}
/**
@@ -272,10 +212,10 @@ 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 + " ");
// Output a little snippet to show it's enabled.
this.log(Level.INFO, "- Version " + this.getDescription().getVersion() + " (API v" + PROTOCOL + ") Enabled - By " + getAuthors());
// Load the defaultWorldGenerators
this.worldManager.getDefaultWorldGenerators();
@@ -283,6 +223,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// 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.
@@ -302,65 +244,28 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Setup & Load our Configuration files.
loadConfigs();
if (this.multiverseConfig != null) {
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();
// Now set the firstspawnworld (after the worlds are loaded):
this.worldManager.setFirstSpawnWorld(getMVConfig().getFirstSpawnWorld());
this.worldManager.setFirstSpawnWorld(config.getFirstSpawnWorld());
try {
getMVConfig().setFirstSpawnWorld(this.worldManager.getFirstSpawnWorld().getName());
config.setFirstSpawnWorld(this.worldManager.getFirstSpawnWorld().getName());
} catch (NullPointerException e) {
// A test that had no worlds loaded was being run. This should never happen in production
}
this.saveMVConfig();
// Register async or sync player chat according to config
try {
Class.forName("org.bukkit.event.player.AsyncPlayerChatEvent");
} catch (ClassNotFoundException e) {
getMVConfig().setUseAsyncChat(false);
}
if (getMVConfig().getUseAsyncChat()) {
this.chatListener = new MVAsyncPlayerChatListener(this, this.playerListener);
} else {
this.chatListener = new MVPlayerChatListener(this, this.playerListener);
}
getServer().getPluginManager().registerEvents(this.chatListener, this);
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() {
try {
buscript = new Buscript(this);
// Add global variable "multiverse" to javascript environment
buscript.setScriptVariable("multiverse", this);
} catch (NullPointerException e) {
buscript = null;
Logging.warning("Buscript failed to load! The script command will be disabled!");
/*
// 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.");
}
*/
}
private void initializeDestinationFactory() {
@@ -381,11 +286,10 @@ 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);
}
/**
@@ -395,33 +299,24 @@ 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);
this.migrateWorldConfig();
this.worldManager.loadWorldConfig(new File(getDataFolder(), "worlds.yml"));
MultiverseCoreConfiguration wantedConfig = null;
try {
wantedConfig = (MultiverseCoreConfiguration) multiverseConfig.get("multiverse-configuration");
} catch (Exception ignore) {
} catch (Exception e) {
// We're just thinking "no risk no fun" and therefore have to catch and forget this exception
} finally {
config = ((wantedConfig == null) ? new MultiverseCoreConfiguration() : wantedConfig);
}
this.migrateWorldConfig();
this.worldManager.loadWorldConfig(new File(getDataFolder(), "worlds.yml"));
this.messaging.setCooldown(getMVConfig().getMessageCooldown());
this.messaging.setCooldown(config.getMessageCooldown());
// Remove old values.
this.multiverseConfig.set("enforcegamemodes", null);
@@ -431,12 +326,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));
}
}
/**
@@ -445,85 +334,72 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*/
private void migrate22Values() {
if (this.multiverseConfig.isSet("worldnameprefix")) {
Logging.config("Migrating 'worldnameprefix'...");
this.getMVConfig().setPrefixChat(this.multiverseConfig.getBoolean("worldnameprefix"));
this.log(Level.INFO, "Migrating 'worldnameprefix'...");
this.config.setPrefixChat(this.multiverseConfig.getBoolean("worldnameprefix"));
this.multiverseConfig.set("worldnameprefix", null);
}
if (this.multiverseConfig.isSet("firstspawnworld")) {
Logging.config("Migrating 'firstspawnworld'...");
this.getMVConfig().setFirstSpawnWorld(this.multiverseConfig.getString("firstspawnworld"));
this.log(Level.INFO, "Migrating 'firstspawnworld'...");
this.config.setFirstSpawnWorld(this.multiverseConfig.getString("firstspawnworld"));
this.multiverseConfig.set("firstspawnworld", null);
}
if (this.multiverseConfig.isSet("enforceaccess")) {
Logging.config("Migrating 'enforceaccess'...");
this.getMVConfig().setEnforceAccess(this.multiverseConfig.getBoolean("enforceaccess"));
this.log(Level.INFO, "Migrating 'enforceaccess'...");
this.config.setEnforceAccess(this.multiverseConfig.getBoolean("enforceaccess"));
this.multiverseConfig.set("enforceaccess", null);
}
if (this.multiverseConfig.isSet("displaypermerrors")) {
Logging.config("Migrating 'displaypermerrors'...");
this.getMVConfig().setDisplayPermErrors(this.multiverseConfig.getBoolean("displaypermerrors"));
this.log(Level.INFO, "Migrating 'displaypermerrors'...");
this.config.setDisplayPermErrors(this.multiverseConfig.getBoolean("displaypermerrors"));
this.multiverseConfig.set("displaypermerrors", null);
}
if (this.multiverseConfig.isSet("teleportintercept")) {
Logging.config("Migrating 'teleportintercept'...");
this.getMVConfig().setTeleportIntercept(this.multiverseConfig.getBoolean("teleportintercept"));
this.log(Level.INFO, "Migrating 'teleportintercept'...");
this.config.setTeleportIntercept(this.multiverseConfig.getBoolean("teleportintercept"));
this.multiverseConfig.set("teleportintercept", null);
}
if (this.multiverseConfig.isSet("firstspawnoverride")) {
Logging.config("Migrating 'firstspawnoverride'...");
this.getMVConfig().setFirstSpawnOverride(this.multiverseConfig.getBoolean("firstspawnoverride"));
this.log(Level.INFO, "Migrating 'firstspawnoverride'...");
this.config.setFirstSpawnOverride(this.multiverseConfig.getBoolean("firstspawnoverride"));
this.multiverseConfig.set("firstspawnoverride", null);
}
if (this.multiverseConfig.isSet("messagecooldown")) {
Logging.config("Migrating 'messagecooldown'...");
this.getMVConfig().setMessageCooldown(this.multiverseConfig.getInt("messagecooldown"));
this.log(Level.INFO, "Migrating 'messagecooldown'...");
this.config.setMessageCooldown(this.multiverseConfig.getInt("messagecooldown"));
this.multiverseConfig.set("messagecooldown", null);
}
if (this.multiverseConfig.isSet("debug")) {
Logging.config("Migrating 'debug'...");
this.getMVConfig().setGlobalDebug(this.multiverseConfig.getInt("debug"));
this.log(Level.INFO, "Migrating 'debug'...");
this.config.setGlobalDebug(this.multiverseConfig.getInt("debug"));
this.multiverseConfig.set("debug", null);
}
if (this.multiverseConfig.isSet("version")) {
Logging.config("Migrating 'version'...");
this.log(Level.INFO, "Migrating 'version'...");
this.multiverseConfig.set("version", null);
}
}
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!");
}
private void migrateWorldConfig() {
FileConfiguration wconf = YamlConfiguration
.loadConfiguration(new File(getDataFolder(), "worlds.yml"));
if (!wconf.isConfigurationSection("worlds")) { // empty config
Logging.fine("No worlds to migrate!");
if (!wconf.isConfigurationSection("worlds")) // empty config
return;
}
Map<String, Object> values = wconf.getConfigurationSection("worlds").getValues(false);
boolean wasChanged = false;
Map<String, Object> newValues = new LinkedHashMap<String, Object>(values.size());
for (Map.Entry<String, Object> entry : values.entrySet()) {
if (entry.getValue() instanceof WorldProperties) {
if (entry.getValue() instanceof MVWorld) {
// fine
newValues.put(entry.getKey(), entry.getValue());
} else if (entry.getValue() instanceof ConfigurationSection) {
Logging.fine("Migrating: " + entry.getKey());
// we have to migrate this
WorldProperties world = new WorldProperties(Collections.EMPTY_MAP);
MVWorld world = new MVWorld(Collections.EMPTY_MAP);
ConfigurationSection section = (ConfigurationSection) entry.getValue();
// migrate animals and monsters
@@ -557,9 +433,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"));
@@ -594,9 +469,10 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// migrate gamemode
if (section.isString("gamemode")) {
final GameMode gameMode = GameMode.valueOf(section.getString("gamemode").toUpperCase());
if (gameMode != null) {
world.setGameMode(gameMode);
try {
world.setPropertyValue("gamemode", section.getString("gamemode"));
} catch (PropertyDoesNotExistException e) {
throw new RuntimeException("Who forgot to update the migrator?", e);
}
}
@@ -618,8 +494,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// migrate portalform
if (section.isString("portalform")) {
try {
world.setProperty("portalform", section.getString("portalform"), true);
} catch (NoSuchPropertyException e) {
world.setPropertyValue("portalform", section.getString("portalform"));
} catch (PropertyDoesNotExistException e) {
throw new RuntimeException("Who forgot to update the migrator?", e);
}
}
@@ -627,8 +503,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// migrate environment
if (section.isString("environment")) {
try {
world.setProperty("environment", section.getString("environment"), true);
} catch (NoSuchPropertyException e) {
world.setPropertyValue("environment", section.getString("environment"));
} catch (PropertyDoesNotExistException e) {
throw new RuntimeException("Who forgot to update the migrator?", e);
}
}
@@ -666,7 +542,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// migrate spawn
if (section.isConfigurationSection("spawn")) {
ConfigurationSection spawnSect = section.getConfigurationSection("spawn");
Location spawnLoc = new NullLocation();
Location spawnLoc = world.getSpawnLocation();
if (spawnSect.isDouble("yaw"))
spawnLoc.setYaw((float) spawnSect.getDouble("yaw"));
if (spawnSect.isDouble("pitch"))
@@ -681,31 +557,11 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
world.setSpawnLocation(spawnLoc);
}
// 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;
}
if (difficulty != null) {
world.setDifficulty(difficulty);
}
}
// migrate keepspawninmemory
if (section.isBoolean("keepspawninmemory")) {
world.setKeepSpawnInMemory(section.getBoolean("keepspawninmemory"));
}
newValues.put(entry.getKey(), world);
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;
}
@@ -748,7 +604,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.commandHandler.registerCommand(new ListCommand(this));
this.commandHandler.registerCommand(new InfoCommand(this));
this.commandHandler.registerCommand(new CreateCommand(this));
this.commandHandler.registerCommand(new CloneCommand(this));
this.commandHandler.registerCommand(new ImportCommand(this));
this.commandHandler.registerCommand(new ReloadCommand(this));
this.commandHandler.registerCommand(new SetSpawnCommand(this));
@@ -775,12 +630,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Misc Commands
this.commandHandler.registerCommand(new EnvironmentCommand(this));
this.commandHandler.registerCommand(new DebugCommand(this));
this.commandHandler.registerCommand(new SilentCommand(this));
this.commandHandler.registerCommand(new GeneratorCommand(this));
this.commandHandler.registerCommand(new CheckCommand(this));
this.commandHandler.registerCommand(new ScriptCommand(this));
this.commandHandler.registerCommand(new GameruleCommand(this));
this.commandHandler.registerCommand(new GamerulesCommand(this));
}
/**
@@ -789,7 +640,10 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
@Override
public void onDisable() {
this.saveMVConfigs();
Logging.shutdown();
debugLog.close();
this.banker = null;
this.bank = null;
log(Level.INFO, "- Disabled");
}
/**
@@ -800,11 +654,22 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
if (this.playerSessions.containsKey(player.getName())) {
return this.playerSessions.get(player.getName());
} else {
this.playerSessions.put(player.getName(), new MVPlayerSession(player, getMVConfig()));
this.playerSessions.put(player.getName(), new MVPlayerSession(player, config));
return this.playerSessions.get(player.getName());
}
}
/**
* {@inheritDoc}
*
* @deprecated This is deprecated.
*/
@Override
@Deprecated
public com.onarandombox.MultiverseCore.utils.SafeTTeleporter getTeleporter() {
return new com.onarandombox.MultiverseCore.utils.SafeTTeleporter(this);
}
/**
* {@inheritDoc}
*/
@@ -824,29 +689,15 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
}
ArrayList<String> allArgs = new ArrayList<String>(Arrays.asList(args));
allArgs.add(0, command.getName());
try {
return this.commandHandler.locateAndRunCommand(sender, allArgs, getMVConfig().getDisplayPermErrors());
} catch (Exception e) {
e.printStackTrace();
sender.sendMessage(ChatColor.RED + "An internal error occurred when attempting to perform this command.");
if (sender.isOp())
sender.sendMessage(ChatColor.RED + "Details were printed to the server console and logs, please add that to your bug report.");
else
sender.sendMessage(ChatColor.RED + "Try again and contact the server owner or an admin if this problem persists.");
return true;
}
return this.commandHandler.locateAndRunCommand(sender, allArgs, config.getDisplayPermErrors());
}
/**
* {@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);
staticLog(level, msg);
}
/**
@@ -854,28 +705,33 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*
* @param level The Log-{@link Level}.
* @param msg The message to log.
*
* @deprecated Replaced by {@link Logging}. Please refrain from using this from a third party plugin as the
* messages will appear to originate from Multiverse-Core.
*/
@Deprecated
public static void staticLog(Level level, String msg) {
Logging.log(level, msg);
if (level == Level.FINE && MultiverseCoreConfiguration.getInstance().getGlobalDebug() >= 1) {
staticDebugLog(Level.INFO, msg);
return;
} else if (level == Level.FINER && MultiverseCoreConfiguration.getInstance().getGlobalDebug() >= 2) {
staticDebugLog(Level.INFO, msg);
return;
} else if (level == Level.FINEST && MultiverseCoreConfiguration.getInstance().getGlobalDebug() >= 3) {
staticDebugLog(Level.INFO, msg);
return;
} else if (level != Level.FINE && level != Level.FINER && level != Level.FINEST) {
LOGGER.log(level, String.format("%s %s", LOG_TAG, msg));
debugLog.log(level, String.format("%s %s", LOG_TAG, msg));
}
}
/**
* Print messages to the Debug Log, if the servers in Debug Mode then we also want to print the messages to the
* Print messages to the Debug Log, if the servers in Debug Mode then we also wan't to print the messages to the
* standard Server Console.
*
* @param level The Log-{@link Level}
* @param msg The message
*
* @deprecated Replaced by {@link Logging}. Please refrain from using this from a third party plugin as the
* messages will appear to originate from Multiverse-Core.
*/
@Deprecated
public static void staticDebugLog(Level level, String msg) {
Logging.log(level, msg);
LOGGER.log(level, "[MVCore-Debug] " + msg);
debugLog.log(level, "[MVCore-Debug] " + msg);
}
/**
@@ -967,6 +823,22 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.pluginCount -= 1;
}
/**
* {@inheritDoc}
*/
@Override
public AllPay getBanker() {
return this.banker;
}
/**
* {@inheritDoc}
*/
@Override
public void setBank(GenericBank bank) {
this.bank = bank;
}
/**
* {@inheritDoc}
*/
@@ -1008,6 +880,25 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.serverFolder = newServerFolder;
}
/*
/**
* 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}
*/
@@ -1025,15 +916,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return this.playerListener;
}
/**
* Gets the {@link MVChatListener}.
*
* @return The {@link MVChatListener}.
*/
public MVChatListener getChatListener() {
return this.chatListener;
}
/**
* Gets the {@link MVEntityListener}.
*
@@ -1059,11 +941,11 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*/
public boolean saveMVConfig() {
try {
this.multiverseConfig.set("multiverse-configuration", getMVConfig());
this.multiverseConfig.set("multiverse-configuration", config);
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;
}
}
@@ -1096,27 +978,38 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return this.worldManager.deleteWorld(name);
}
/**
* NOT deprecated for the time as queued commands use this.
* However, this is not in the API and other plugins should therefore not use it.
*
* @param oldName World to copy
* @param newName World to create
* @param generator The Custom generator plugin to use.
* @return True if success, false if fail.
*/
public Boolean cloneWorld(String oldName, String newName, String generator) {
return this.worldManager.cloneWorld(oldName, newName, generator);
}
/**
* {@inheritDoc}
* @deprecated This is deprecated!
*/
@Override
@Deprecated
public Boolean regenWorld(String name, Boolean useNewSeed, Boolean randomSeed, String seed) {
return this.worldManager.regenWorld(name, useNewSeed, randomSeed, seed);
MultiverseWorld world = this.worldManager.getMVWorld(name);
if (world == null) {
return false;
}
List<Player> ps = world.getCBWorld().getPlayers();
if (useNewSeed) {
// Set the worldseed.
if (randomSeed) {
Random random = new Random();
Long newseed = random.nextLong();
seed = newseed.toString();
}
((WorldManager) this.worldManager).getConfigWorlds().set("worlds." + name + ".seed", seed);
}
if (this.worldManager.deleteWorld(name, false)) {
this.worldManager.loadWorlds(false);
SafeTTeleporter teleporter = this.getSafeTTeleporter();
Location newSpawn = this.getServer().getWorld(name).getSpawnLocation();
// Send all players that were in the old world, BACK to it!
for (Player p : ps) {
teleporter.safelyTeleport(null, p, newSpawn, true);
}
return true;
}
return false;
}
/**
@@ -1140,9 +1033,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*/
@Override
public void setBlockSafety(BlockSafety bs) {
if (bs == null) {
throw new NullPointerException("block safety may not be null.");
}
this.blockSafety = bs;
}
@@ -1196,13 +1086,4 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
public static MultiverseCoreConfiguration getStaticConfig() {
return MultiverseCoreConfiguration.getInstance();
}
@Override
public Buscript getScriptAPI() {
return buscript;
}
public UnsafeCallWrapper getUnsafeCallWrapper() {
return this.unsafeCallWrapper;
}
}
@@ -2,13 +2,11 @@ package com.onarandombox.MultiverseCore;
import java.util.Map;
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;
/**
* Our configuration.
@@ -24,13 +22,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
MultiverseCoreConfiguration.instance = instance;
}
/**
* @return True if the static instance of config is set.
*/
public static boolean isSet() {
return instance != null;
}
/**
* Gets the statically saved instance.
* @return The statically saved instance.
@@ -42,39 +33,25 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
}
@Property
private volatile boolean enforceaccess;
private boolean enforceaccess;
@Property
private volatile boolean prefixchat;
private boolean prefixchat;
@Property
private volatile String prefixchatformat;
private boolean teleportintercept;
@Property
private volatile boolean useasyncchat;
private boolean firstspawnoverride;
@Property
private volatile boolean teleportintercept;
private boolean displaypermerrors;
@Property
private volatile boolean firstspawnoverride;
private int globaldebug;
@Property
private volatile boolean displaypermerrors;
private int messagecooldown;
@Property
private volatile int globaldebug;
private double version;
@Property
private volatile boolean silentstart;
private String firstspawnworld;
@Property
private volatile int messagecooldown;
@Property
private volatile double version;
@Property
private volatile String firstspawnworld;
@Property
private volatile int teleportcooldown;
@Property
private volatile boolean defaultportalsearch;
@Property
private volatile int portalsearchradius;
@Property
private volatile boolean autopurge;
@Property
private volatile boolean idonotwanttodonate;
private int teleportcooldown;
public MultiverseCoreConfiguration() {
super();
@@ -90,12 +67,10 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
* {@inheritDoc}
*/
@Override
protected void setDefaults() {
public void setDefaults() {
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
enforceaccess = false;
useasyncchat = true;
prefixchat = true;
prefixchatformat = "[%world%]%chat%";
teleportintercept = true;
firstspawnoverride = true;
displaypermerrors = true;
@@ -103,11 +78,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
messagecooldown = 5000;
teleportcooldown = 1000;
this.version = 2.9;
silentstart = false;
defaultportalsearch = false;
portalsearchradius = 128;
autopurge = true;
idonotwanttodonate = false;
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
}
@@ -156,22 +126,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}
@@ -235,8 +189,6 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
@Override
public void setGlobalDebug(int globalDebug) {
this.globaldebug = globalDebug;
Logging.setDebugLevel(globalDebug);
Bukkit.getPluginManager().callEvent(new MVDebugModeEvent(globalDebug));
}
/**
@@ -302,65 +254,4 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
public void setTeleportCooldown(int teleportCooldown) {
this.teleportcooldown = teleportCooldown;
}
@Override
public void setUseAsyncChat(boolean useAsyncChat) {
this.useasyncchat = useAsyncChat;
}
@Override
public boolean getUseAsyncChat() {
return this.useasyncchat;
}
@Override
public void setSilentStart(boolean silentStart) {
Logging.setShowingConfig(!silentStart);
this.silentstart = silentStart;
}
@Override
public boolean getSilentStart() {
return silentstart;
}
@Override
public void setUseDefaultPortalSearch(boolean useDefaultPortalSearch) {
defaultportalsearch = useDefaultPortalSearch;
}
@Override
public boolean isUsingDefaultPortalSearch() {
return defaultportalsearch;
}
@Override
public void setPortalSearchRadius(int searchRadius) {
this.portalsearchradius = searchRadius;
}
@Override
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;
}
}
@@ -1,655 +0,0 @@
package com.onarandombox.MultiverseCore;
import com.onarandombox.MultiverseCore.MVWorld.NullLocation;
import com.onarandombox.MultiverseCore.configuration.EntryFee;
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;
import com.onarandombox.MultiverseCore.enums.EnglishChatStyle;
import me.main__.util.SerializationConfig.IllegalPropertyValueException;
import me.main__.util.SerializationConfig.Property;
import me.main__.util.SerializationConfig.SerializationConfig;
import me.main__.util.SerializationConfig.Serializor;
import me.main__.util.SerializationConfig.Validator;
import me.main__.util.SerializationConfig.VirtualProperty;
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;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* This is a property class, I think we don't need that much javadoc.
* BEGIN CHECKSTYLE-SUPPRESSION: Javadoc
*/
@SerializableAs("MVWorld")
public class WorldProperties extends SerializationConfig {
private static final Map<String, String> PROPERTY_ALIASES;
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("scaling", "scale");
PROPERTY_ALIASES.put("aliascolor", "color");
PROPERTY_ALIASES.put("heal", "autoHeal");
PROPERTY_ALIASES.put("storm", "allowWeather");
PROPERTY_ALIASES.put("weather", "allowWeather");
PROPERTY_ALIASES.put("spawnmemory", "keepSpawnInMemory");
PROPERTY_ALIASES.put("memory", "keepSpawnInMemory");
PROPERTY_ALIASES.put("mode", "gameMode");
PROPERTY_ALIASES.put("diff", "difficulty");
PROPERTY_ALIASES.put("spawnlocation", "spawn");
PROPERTY_ALIASES.put("limit", "playerLimit");
PROPERTY_ALIASES.put("animals", "spawning.animals.spawn");
PROPERTY_ALIASES.put("monsters", "spawning.monsters.spawn");
PROPERTY_ALIASES.put("animalsrate", "spawning.animals.spawnrate");
PROPERTY_ALIASES.put("monstersrate", "spawning.monsters.spawnrate");
PROPERTY_ALIASES.put("flight", "allowFlight");
PROPERTY_ALIASES.put("fly", "allowFlight");
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) {
super();
if (!fixSpawn) {
this.adjustSpawn = false;
}
setScaling(getDefaultScale(environment));
keepSpawnFallback = true;
}
void setMVWorld(MVWorld world) {
registerObjectUsing(world);
registerGlobalValidator(new WorldPropertyValidator());
}
/**
* Serializor for the color-property.
*/
private static final class EnumPropertySerializor<T extends Enum<T>> implements Serializor<T, String> {
@Override
public String serialize(T from) {
return from.toString();
}
@Override
public T deserialize(String serialized, Class<T> wanted) throws IllegalPropertyValueException {
try {
return Enum.valueOf(wanted, serialized.toUpperCase());
} catch (IllegalArgumentException e) {
throw new IllegalPropertyValueException(e);
}
}
}
/**
* Serializor for the difficulty-property.
*/
private static final class DifficultyPropertySerializor implements Serializor<Difficulty, String> {
@Override
public String serialize(Difficulty from) {
return from.toString();
}
@Override
public Difficulty deserialize(String serialized, Class<Difficulty> wanted) throws IllegalPropertyValueException {
try {
return Difficulty.getByValue(Integer.parseInt(serialized));
} catch (Exception e) {
}
try {
return Difficulty.valueOf(serialized.toUpperCase());
} catch (Exception e) {
}
throw new IllegalPropertyValueException();
}
}
/**
* Serializor for the gameMode-property.
*/
private static final class GameModePropertySerializor implements Serializor<GameMode, String> {
@Override
public String serialize(GameMode from) {
return from.toString();
}
@Override
public GameMode deserialize(String serialized, Class<GameMode> wanted) throws IllegalPropertyValueException {
try {
return GameMode.getByValue(Integer.parseInt(serialized));
} catch (NumberFormatException nfe) {
}
try {
return GameMode.valueOf(serialized.toUpperCase());
} catch (Exception e) {
}
throw new IllegalPropertyValueException();
}
}
/**
* Serializor for the time-property.
*/
private static final class TimePropertySerializor implements Serializor<Long, String> {
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
private static final String TIME_REGEX = "(\\d\\d?):?(\\d\\d)(a|p)?m?";
private static final Map<String, String> TIME_ALIASES;
static {
Map<String, String> staticTimes = new HashMap<String, String>();
staticTimes.put("morning", "8:00");
staticTimes.put("day", "12:00");
staticTimes.put("noon", "12:00");
staticTimes.put("midnight", "0:00");
staticTimes.put("night", "20:00");
// now set TIME_ALIASES to a "frozen" map
TIME_ALIASES = Collections.unmodifiableMap(staticTimes);
}
@Override
public String serialize(Long from) {
// I'm tired, so they get time in 24 hour for now.
// Someone else can add 12 hr format if they want :P
int hours = (int) ((from / 1000 + 8) % 24);
int minutes = (int) (60 * (from % 1000) / 1000);
return String.format("%d:%02d", hours, minutes);
}
@Override
public Long deserialize(String serialized, Class<Long> wanted) throws IllegalPropertyValueException {
if (TIME_ALIASES.containsKey(serialized.toLowerCase())) {
serialized = TIME_ALIASES.get(serialized.toLowerCase());
}
// Regex that extracts a time in the following formats:
// 11:11pm, 11:11, 23:11, 1111, 1111p, and the aliases at the top of this file.
Pattern pattern = Pattern.compile(TIME_REGEX, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(serialized);
matcher.find();
int hour = 0;
double minute = 0;
int count = matcher.groupCount();
if (count >= 2) {
hour = Integer.parseInt(matcher.group(1));
minute = Integer.parseInt(matcher.group(2));
}
// If there were 4 matches (all, hour, min, am/pm)
if (count == 4) {
// We want 24 hour time for calcs, but if they
// added a p[m], turn it into a 24 hr one.
if (matcher.group(3).equals("p")) {
hour += 12;
}
}
// Translate 24th hour to 0th hour.
if (hour == 24) {
hour = 0;
}
// Clamp the hour
if (hour > 23 || hour < 0) {
throw new IllegalPropertyValueException("Illegal hour!");
}
// Clamp the minute
if (minute > 59 || minute < 0) {
throw new IllegalPropertyValueException("Illegal minute!");
}
// 60 seconds in a minute, time needs to be in hrs * 1000, per
// the bukkit docs.
double totaltime = (hour + (minute / 60.0)) * 1000;
// Somehow there's an 8 hour offset...
totaltime -= 8000;
if (totaltime < 0) {
totaltime = 24000 + totaltime;
}
return (long) totaltime;
}
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
}
// --------------------------------------------------------------
// Begin properties
@Property(description = "Sorry, 'hidden' must either be: true or false.")
private volatile boolean hidden;
@Property(description = "Alias must be a valid string.")
private volatile String alias;
@Property(serializor = EnumPropertySerializor.class, description = "Sorry, 'color' must be a valid color-name.")
private volatile EnglishChatColor color;
@Property(serializor = EnumPropertySerializor.class, description = "Sorry, 'style' must be a valid style-name.")
private volatile EnglishChatStyle style;
@Property(description = "Sorry, 'pvp' must either be: true or false.", virtualType = Boolean.class, persistVirtual = true)
volatile VirtualProperty<Boolean> pvp; // SUPPRESS CHECKSTYLE: VisibilityModifier
@Property(description = "Scale must be a positive double value. ex: 2.3")
private volatile double scale;
@Property(description = "You must set this to the NAME not alias of a world.")
private volatile String respawnWorld;
@Property(description = "Sorry, this must either be: true or false.")
private volatile boolean allowWeather;
@Property(serializor = DifficultyPropertySerializor.class, virtualType = Difficulty.class, persistVirtual = true,
description = "Difficulty must be set as one of the following: peaceful easy normal hard")
volatile VirtualProperty<Difficulty> difficulty; // SUPPRESS CHECKSTYLE: VisibilityModifier
@Property(description = "Sorry, 'animals' must either be: true or false.")
private volatile SpawnSettings spawning;
@Property
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.")
private volatile boolean autoHeal;
@Property(description = "Sorry, 'adjustspawn' must either be: true or false.")
private volatile boolean adjustSpawn;
@Property(serializor = EnumPropertySerializor.class, description = "Allow portal forming must be NONE, ALL, NETHER or END.")
private volatile AllowedPortalType portalForm;
@Property(serializor = GameModePropertySerializor.class, description = "GameMode must be set as one of the following: survival creative")
private volatile GameMode gameMode;
@Property(description = "Sorry, this must either be: true or false.", virtualType = Boolean.class, persistVirtual = true)
volatile VirtualProperty<Boolean> keepSpawnInMemory; // SUPPRESS CHECKSTYLE: VisibilityModifier
@Property
volatile SpawnLocation spawnLocation; // SUPPRESS CHECKSTYLE: VisibilityModifier
@Property(virtualType = Location.class,
description = "There is no help available for this variable. Go bug Rigby90 about it.")
volatile VirtualProperty<Location> spawn; // SUPPRESS CHECKSTYLE: VisibilityModifier
@Property(description = "Set this to false ONLY if you don't want this world to load itself on server restart.")
private volatile boolean autoLoad;
@Property(description = "If a player dies in this world, shoudld they go to their bed?")
private volatile boolean bedRespawn;
@Property
private volatile List<String> worldBlacklist;
@Property(serializor = TimePropertySerializor.class, virtualType = Long.class,
description = "Set the time to whatever you want! (Will NOT freeze time)")
volatile VirtualProperty<Long> time; // SUPPRESS CHECKSTYLE: VisibilityModifier
@Property
volatile Environment environment; // SUPPRESS CHECKSTYLE: VisibilityModifier
@Property
volatile long seed; // SUPPRESS CHECKSTYLE: VisibilityModifier
@Property
private volatile String generator;
@Property
private volatile int playerLimit;
@Property
private volatile boolean allowFlight;
// End of properties
// --------------------------------------------------------------
void setValidator(String fieldName, Validator validator) {
registerValidator(fieldName, validator); //To change body of overridden methods use File | Settings | File Templates.
}
/**
* {@inheritDoc}
*/
@Override
public void copyValues(SerializationConfig other) {
super.copyValues(other);
}
/**
* This prepares the MVWorld for unloading.
*/
public void cacheVirtualProperties() {
try {
this.buildVPropChanges();
} catch (IllegalStateException e) {
// do nothing
}
}
/**
* {@inheritDoc}
*/
@Override
protected void setDefaults() {
this.hidden = false;
this.alias = new String();
this.color = EnglishChatColor.WHITE;
this.style = EnglishChatStyle.NORMAL;
this.scale = 1D;
this.respawnWorld = new String();
this.allowWeather = true;
this.spawning = new SpawnSettings();
this.entryfee = new EntryFee();
this.hunger = true;
this.autoHeal = true;
this.adjustSpawn = true;
this.portalForm = AllowedPortalType.ALL;
this.gameMode = GameMode.SURVIVAL;
this.spawnLocation = new NullLocation();
this.autoLoad = true;
this.bedRespawn = true;
this.worldBlacklist = new ArrayList<String>();
this.generator = null;
this.playerLimit = -1;
this.allowFlight = true;
}
private static double getDefaultScale(Environment environment) {
if (environment == Environment.NETHER) {
return 8.0; // SUPPRESS CHECKSTYLE: MagicNumberCheck
} else if (environment == Environment.THE_END) {
return 16.0; // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
return 1.0;
}
/**
* getAliases().
* @return The alias-map.
* @see SerializationConfig
*/
protected static Map<String, String> getAliases() {
return PROPERTY_ALIASES;
}
void flushChanges() {
this.flushPendingVPropChanges();
}
public String getAlias() {
return this.alias;
}
public void setAlias(String alias) {
this.setPropertyValueUnchecked("alias", alias);
}
public Environment getEnvironment() {
return this.environment;
}
public void setEnvironment(Environment environment) {
this.setPropertyValueUnchecked("environment", environment);
}
public long getSeed() {
return this.seed;
}
public void setSeed(long seed) {
this.setPropertyValueUnchecked("seed", seed);
}
public String getGenerator() {
return this.generator;
}
public void setGenerator(String generator) {
this.setPropertyValueUnchecked("generator", generator);
}
public int getPlayerLimit() {
return this.playerLimit;
}
public void setPlayerLimit(int limit) {
this.setPropertyValueUnchecked("playerLimit", limit);
}
public boolean canAnimalsSpawn() {
return this.spawning.getAnimalSettings().doSpawn();
}
public void setAllowAnimalSpawn(boolean animals) {
this.setPropertyValueUnchecked("spawning.animals.spawn", animals);
}
public List<String> getAnimalList() {
// These don't fire events at the moment. Should they?
return this.spawning.getAnimalSettings().getExceptions();
}
public boolean canMonstersSpawn() {
return this.spawning.getMonsterSettings().doSpawn();
}
public void setAllowMonsterSpawn(boolean monsters) {
this.setPropertyValueUnchecked("spawning.monsters.spawn", monsters);
}
public int getAnimalSpawnRate() {
return this.spawning.getAnimalSettings().getSpawnRate();
}
public int getMonsterSpawnRate() {
return this.spawning.getMonsterSettings().getSpawnRate();
}
public List<String> getMonsterList() {
// These don't fire events at the moment. Should they?
return this.spawning.getMonsterSettings().getExceptions();
}
public boolean isPVPEnabled() {
return this.pvp.get();
}
public void setPVPMode(boolean pvp) {
this.setPropertyValueUnchecked("pvp", pvp);
}
public boolean isHidden() {
return this.hidden;
}
public void setHidden(boolean hidden) {
this.setPropertyValueUnchecked("hidden", hidden);
}
public List<String> getWorldBlacklist() {
return this.worldBlacklist;
}
public double getScaling() {
return this.scale;
}
public boolean setScaling(double scaling) {
return this.setPropertyValueUnchecked("scale", scaling);
}
public boolean setColor(String aliasColor) {
return this.setPropertyUnchecked("color", aliasColor);
}
public boolean setColor(EnglishChatColor color) {
return this.setPropertyValueUnchecked("color", color);
}
public EnglishChatColor getColor() {
return this.color;
}
public String getRespawnToWorld() {
return this.respawnWorld;
}
public boolean setRespawnToWorld(String respawnToWorld) {
return this.setPropertyValueUnchecked("respawnWorld", respawnToWorld);
}
public Material getCurrency() {
return this.entryfee.getCurrency();
}
public void setCurrency(@Nullable Material currency) {
this.setPropertyValueUnchecked("entryfee.currency", currency);
}
public double getPrice() {
return this.entryfee.getAmount();
}
public void setPrice(double price) {
this.setPropertyValueUnchecked("entryfee.amount", price);
}
public boolean setGameMode(String mode) {
return this.setPropertyUnchecked("gameMode", mode);
}
public boolean setGameMode(GameMode mode) {
return this.setPropertyValueUnchecked("gameMode", mode);
}
public GameMode getGameMode() {
return this.gameMode;
}
public void setEnableWeather(boolean weather) {
this.setPropertyValueUnchecked("allowWeather", weather);
}
public boolean isWeatherEnabled() {
return this.allowWeather;
}
public boolean isKeepingSpawnInMemory() {
if (keepSpawnInMemory == null) {
return keepSpawnFallback;
}
try {
return this.keepSpawnInMemory.get();
} catch (IllegalStateException e) {
return keepSpawnFallback;
}
}
public void setKeepSpawnInMemory(boolean value) {
this.setPropertyValueUnchecked("keepSpawnInMemory", value);
}
public boolean getHunger() {
return this.hunger;
}
public void setHunger(boolean hunger) {
this.setPropertyValueUnchecked("hunger", hunger);
}
public Location getSpawnLocation() {
return this.spawn.get();
}
public void setSpawnLocation(Location l) {
this.setPropertyValueUnchecked("spawn", l);
}
public Difficulty getDifficulty() {
return this.difficulty.get();
}
@Deprecated // SUPPRESS CHECKSTYLE: Deprecated
public boolean setDifficulty(String difficulty) {
return this.setPropertyUnchecked("difficulty", difficulty);
}
public boolean setDifficulty(Difficulty difficulty) {
return this.setPropertyValueUnchecked("difficulty", difficulty);
}
public boolean getAutoHeal() {
return this.autoHeal;
}
public void setAutoHeal(boolean heal) {
this.setPropertyValueUnchecked("autoHeal", heal);
}
public void setAdjustSpawn(boolean adjust) {
this.setPropertyValueUnchecked("adjustSpawn", adjust);
}
public boolean getAdjustSpawn() {
return this.adjustSpawn;
}
public void setAutoLoad(boolean load) {
this.setPropertyValueUnchecked("autoLoad", load);
}
public boolean getAutoLoad() {
return this.autoLoad;
}
public void setBedRespawn(boolean respawn) {
this.setPropertyValueUnchecked("bedRespawn", respawn);
}
public boolean getBedRespawn() {
return this.bedRespawn;
}
public String getAllPropertyNames() {
ChatColor myColor = ChatColor.AQUA;
StringBuilder result = new StringBuilder();
Map<String, Object> serialized = this.serialize();
for (String key : serialized.keySet()) {
result.append(myColor).append(key).append(' ');
myColor = (myColor == ChatColor.AQUA) ? ChatColor.GOLD : ChatColor.AQUA;
}
return result.toString();
}
public String getTime() {
return this.getPropertyUnchecked("time");
}
public boolean setTime(String timeAsString) {
return this.setPropertyUnchecked("time", timeAsString);
}
public AllowedPortalType getAllowedPortals() {
return portalForm;
}
public void allowPortalMaking(AllowedPortalType portalType) {
this.setPropertyValueUnchecked("portalForm", portalType);
}
public EnglishChatStyle getStyle() {
return style;
}
public boolean setStyle(String style) {
return this.setPropertyUnchecked("style", style);
}
public boolean getAllowFlight() {
return this.allowFlight;
}
public void setAllowFlight(final boolean allowFlight) {
this.setPropertyValueUnchecked("allowFlight", allowFlight);
}
}
@@ -35,13 +35,6 @@ public interface BlockSafety {
*/
boolean playerCanSpawnHereSafely(Location l);
/**
* Gets a safe bed spawn location OR null if the bed is invalid.
* @param l The location of the bead head (block with the pillow on it).
* @return Safe location around the bed or null if no location was found.
*/
Location getSafeBedSpawn(Location l);
/**
* Gets the location of the top block at the specified {@link Location}.
* @param l Any {@link Location}.
@@ -7,17 +7,12 @@
package com.onarandombox.MultiverseCore.api;
import buscript.Buscript;
import com.fernferret.allpay.AllPay;
import com.fernferret.allpay.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;
import com.onarandombox.MultiverseCore.utils.SimpleLocationManipulation;
import com.onarandombox.MultiverseCore.utils.SimpleSafeTTeleporter;
import com.onarandombox.MultiverseCore.utils.VaultHandler;
import com.onarandombox.MultiverseCore.utils.*;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
/**
@@ -28,22 +23,20 @@ import org.bukkit.entity.Player;
public interface Core {
/**
* Returns the Vault handler used by Multiverse. The returned object will have all methods necessary for
* interfacing with Vault.
* Gets the Multiverse config file.
*
* @return the Vault handler for Multiverse.
* @deprecated we are now using {@link #getEconomist()} for all economy needs.
* @return The Multiverse config file.
* @deprecated Don't modify the config-file manually!
*/
@Deprecated
VaultHandler getVaultHandler();
FileConfiguration getMVConfiguration();
/**
* Retrieves Multiverse's friendly economist. The economist can be used for dealing with economies without
* worrying about any of the messy details.
* Gets the Banking system that Multiverse-Core has hooked into.
*
* @return the economy manager for Multiverse.
* @return A {@link GenericBank} that can be used for payments.
*/
MVEconomist getEconomist();
GenericBank getBank();
/**
* Reloads the Multiverse Configuration files:
@@ -70,6 +63,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.
@@ -97,7 +101,7 @@ public interface Core {
/**
* Gets the primary class responsible for managing Multiverse Worlds.
*
* @return {@link MVWorldManager}.
* @return {@link WorldManager}.
*/
MVWorldManager getMVWorldManager();
@@ -124,12 +128,23 @@ public interface Core {
* @param seed The seed of the world.
*
* @return True if success, false if fail.
*
* @deprecated Use {@link MVWorldManager#regenWorld(String, boolean, boolean, String)} instead.
*/
@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}
*/
void setBank(GenericBank bank);
/**
* Gets this plugin's {@link AllPay}-Banker.
*
* @return An {@link AllPay}-Banker
*/
AllPay getBanker();
/**
* Decrements the number of plugins that have specifically hooked into core.
*/
@@ -207,11 +222,4 @@ public interface Core {
* @return The configuration.
*/
MultiverseCoreConfig getMVConfig();
/**
* Gets the buscript object for Multiverse. This is what handles Javascript processing.
*
* @return The Multiverse buscript object.
*/
Buscript getScriptAPI();
}
@@ -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.
@@ -30,14 +30,14 @@ public interface MVPlugin extends LoggablePlugin {
/**
* Gets the reference to MultiverseCore.
*
* @return A valid {@link com.onarandombox.MultiverseCore}.
* @return A valid {@link MultiverseCore}.
*/
MultiverseCore getCore();
/**
* Sets the reference to MultiverseCore.
*
* @param core A valid {@link com.onarandombox.MultiverseCore}.
* @param core A valid {@link MultiverseCore}.
*/
void setCore(MultiverseCore core);
@@ -9,6 +9,7 @@ package com.onarandombox.MultiverseCore.api;
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;
@@ -60,34 +61,10 @@ public interface MVWorldManager {
String generator, boolean useSpawnAdjust);
/**
* 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
* @param generator The Custom generator plugin to use. Ignored.
* @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.
*
* @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);
@@ -103,17 +80,6 @@ public interface MVWorldManager {
*/
boolean deleteWorld(String name, boolean removeConfig);
/**
*
* @param name The name of the world to remove
* @param removeFromConfig If true(default), we'll remove the entries from the
* config. If false, they'll stay and the world may come back.
* @param deleteWorldFolder If true the world folder will be completely deleted. If false
* only the contents of the world folder will be deleted
* @return True if success, false if failure.
*/
boolean deleteWorld(String name, boolean removeFromConfig, boolean deleteWorldFolder);
/**
* Unload a world from Multiverse.
*
@@ -122,15 +88,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)}.
@@ -199,7 +156,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.
@@ -207,7 +164,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.
*/
@@ -288,30 +245,4 @@ public interface MVWorldManager {
* @return The {@link MultiverseWorld} new players should spawn in.
*/
MultiverseWorld getFirstSpawnWorld();
/**
* Regenerates a world.
*
* @param name Name of the world to regenerate
* @param useNewSeed If a new seed should be used
* @param randomSeed IF the new seed should be random
* @param seed The seed of the world.
*
* @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);
}
@@ -121,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.
@@ -145,86 +133,4 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable {
* @return enforceAccess.
*/
boolean getEnforceAccess();
/**
* Sets useasyncchat.
* @param useAsyncChat The new value.
*/
void setUseAsyncChat(boolean useAsyncChat);
/**
* Gets useasyncchat.
* @return useasyncchat.
*/
boolean getUseAsyncChat();
/**
* Sets whether to suppress startup messages.
*
* @param silentStart true to suppress messages.
*/
void setSilentStart(boolean silentStart);
/**
* Whether we are suppressing startup messages.
*
* @return true if we are suppressing startup messages.
*/
boolean getSilentStart();
/**
* Sets whether or not to let Bukkit determine portal search radius on its own or if Multiverse should give input.
*
* @param useDefaultPortalSearch True to let Bukkit determine portal search radius on its own.
*/
void setUseDefaultPortalSearch(boolean useDefaultPortalSearch);
/**
* Gets whether or not Bukkit will be determining portal search radius on its own or if Multiverse should help.
*
* @return True means Bukkit will use its own default values.
*/
boolean isUsingDefaultPortalSearch();
/**
* Sets the radius at which vanilla style portals will be searched for to connect to worlds together.
*
* @param searchRadius The portal search radius.
*/
void setPortalSearchRadius(int searchRadius);
/**
* Gets the radius at which vanilla style portals will be searched for to connect to worlds together.
*
* @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);
}
@@ -1,161 +0,0 @@
package com.onarandombox.MultiverseCore.api;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.utils.DebugLog;
import com.pneumaticraft.commandhandler.CommandHandler;
/**
* Make things easier for MV-Plugins!
*/
public abstract class MultiversePlugin extends JavaPlugin implements MVPlugin {
private MultiverseCore core;
/**
* Prefix for standard log entrys.
*/
protected String logTag;
private DebugLog debugLog;
/**
* {@inheritDoc}
*
* Note: You can't override this, use {@link #onPluginEnable()} instead!
* @see #onPluginEnable()
*/
@Override
public final void onEnable() {
MultiverseCore theCore = (MultiverseCore) this.getServer().getPluginManager().getPlugin("Multiverse-Core");
if (theCore == null) {
this.getLogger().severe("Core not found! The plugin dev needs to add a dependency!");
this.getLogger().severe("Disabling!");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
if (theCore.getProtocolVersion() < this.getProtocolVersion()) {
this.getLogger().severe("You need a newer version of Multiverse-Core!");
this.getLogger().severe("Disabling!");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
this.setCore(theCore);
this.getServer().getLogger().info(String.format("%s - Version %s enabled - By %s",
this.getDescription().getName(), this.getDescription().getVersion(), getAuthors()));
getDataFolder().mkdirs();
File debugLogFile = new File(getDataFolder(), "debug.log");
try {
debugLogFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
debugLog = new DebugLog(this.getDescription().getName(), getDataFolder() + File.separator + "debug.log");
debugLog.setTag(String.format("[%s-Debug]", this.getDescription().getName()));
this.onPluginEnable();
}
/**
* Parse the Authors Array into a readable String with ',' and 'and'.
*
* @return The readable authors-{@link String}
*/
protected String getAuthors() {
String authors = "";
List<String> auths = this.getDescription().getAuthors();
if (auths.size() == 0) {
return "";
}
if (auths.size() == 1) {
return auths.get(0);
}
for (int i = 0; i < auths.size(); i++) {
if (i == this.getDescription().getAuthors().size() - 1) {
authors += " and " + this.getDescription().getAuthors().get(i);
} else {
authors += ", " + this.getDescription().getAuthors().get(i);
}
}
return authors.substring(2);
}
/**
* Called when the plugin is enabled.
* @see #onEnable()
*/
protected abstract void onPluginEnable();
/**
* You can register commands here.
* @param handler The CommandHandler.
*/
protected abstract void registerCommands(CommandHandler handler);
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!this.isEnabled()) {
sender.sendMessage("This plugin is Disabled!");
return true;
}
ArrayList<String> allArgs = new ArrayList<String>(args.length + 1);
allArgs.add(command.getName());
allArgs.addAll(Arrays.asList(args));
return this.getCore().getCommandHandler().locateAndRunCommand(sender, allArgs);
}
@Override
public void log(Level level, String msg) {
int debugLevel = this.getCore().getMVConfig().getGlobalDebug();
if ((level == Level.FINE && debugLevel >= 1) || (level == Level.FINER && debugLevel >= 2)
|| (level == Level.FINEST && debugLevel >= 3)) {
debugLog.log(level, msg);
} else if (level != Level.FINE && level != Level.FINER && level != Level.FINEST) {
String message = new StringBuilder(getLogTag()).append(msg).toString();
this.getServer().getLogger().log(level, message);
debugLog.log(level, message);
}
}
private String getLogTag() {
if (logTag == null)
logTag = String.format("[%s]", this.getDescription().getName());
return logTag;
}
/**
* Sets the debug log-tag.
* @param tag The new tag.
*/
protected final void setDebugLogTag(String tag) {
this.debugLog.setTag(tag);
}
@Override
public final String dumpVersionInfo(String buffer) {
throw new UnsupportedOperationException("This is gone.");
}
@Override
public final MultiverseCore getCore() {
if (this.core == null)
throw new IllegalStateException("Core is null!");
return this.core;
}
@Override
public final void setCore(MultiverseCore core) {
this.core = core;
}
}
@@ -9,16 +9,15 @@ package com.onarandombox.MultiverseCore.api;
import com.onarandombox.MultiverseCore.enums.AllowedPortalType;
import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException;
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 +154,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}.
*
@@ -258,21 +288,6 @@ public interface MultiverseWorld {
*/
boolean setColor(String color);
/**
* Gets the style that this world's name/alias will display as.
*
* @return The style of this world. {@code null} for "normal" style.
*/
ChatColor getStyle();
/**
* Sets the style that this world's name/alias will display as.
*
* @param style A valid style name.
* @return True if the style was set, false if not.
*/
boolean setStyle(String style);
/**
* Tells you if someone entered a valid color.
*
@@ -475,28 +490,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.
@@ -593,22 +606,6 @@ public interface MultiverseWorld {
*/
void setBedRespawn(boolean autoLoad);
/**
* Sets the player limit for this world after which players without an override
* permission node will not be allowed in. A value of -1 or less signifies no limit
*
* @param limit The new limit
*/
void setPlayerLimit(int limit);
/**
* Gets the player limit for this world after which players without an override
* permission node will not be allowed in. A value of -1 or less signifies no limit
*
* @return The player limit
*/
int getPlayerLimit();
/**
* Same as {@link #getTime()}, but returns a string.
* @return The time as a short string: 12:34pm
@@ -659,16 +656,23 @@ public interface MultiverseWorld {
String getAllPropertyNames();
/**
* Whether or not players are allowed to fly in this world.
* Gets whether or not flight is allowed in this world.
* <p>
* It should be noted that this refers to clientside flying. Creative
* mode will always allow server based flying.
*
* @return True if players allowed to fly in this world.
* @return True if flight is allowed.
*/
boolean getAllowFlight();
boolean isFlightAllowed();
/**
* Sets whether or not players are allowed to fly in this world.
* Sets whether or not flight is allowed in this world.
* <p>
* It should be noted that this refers to clientside flying. Creative
* mode will always allow server based flying.
*
* @param allowFlight True to allow flight in this world.
* @param flightAllowed Wheter or not flight is allowed in this world.
*/
void setAllowFlight(final boolean allowFlight);
void setFlightAllowed(boolean flightAllowed);
}
@@ -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);
}
@@ -3,21 +3,21 @@ package com.onarandombox.MultiverseCore.api;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
/**
* Used to remove animals from worlds that don't belong there.
*/
public interface WorldPurger {
/**
* Synchronizes the given worlds with their settings.
* Synchronizes the given world with it's settings.
*
* @param worlds A list of {@link MultiverseWorld}
*/
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}.
*/
@@ -46,23 +46,4 @@ public interface WorldPurger {
void purgeWorld(MultiverseWorld mvworld, List<String> thingsToKill, boolean negateAnimals,
boolean negateMonsters, CommandSender sender);
/**
* Determines whether the specified creature should be killed.
*
* @param e The creature.
* @param thingsToKill A {@link List} of animals/monsters to be killed.
* @param negateAnimals Whether the monsters in the list should be negated.
* @param negateMonsters Whether the animals in the list should be negated.
* @return {@code true} if the creature should be killed, otherwise {@code false}.
*/
boolean shouldWeKillThisCreature(Entity e, List<String> thingsToKill, boolean negateAnimals, boolean negateMonsters);
/**
* Determines whether the specified creature should be killed and automatically reads the params from a world object.
*
* @param w The world.
* @param e The creature.
* @return {@code true} if the creature should be killed, otherwise {@code false}.
*/
boolean shouldWeKillThisCreature(MultiverseWorld w, Entity e);
}
@@ -11,7 +11,6 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
@@ -35,11 +34,7 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
this.addCommandExample("/mv anchor " + ChatColor.GREEN + "otherthing");
this.addCommandExample("/mv anchor " + ChatColor.GREEN + "awesomething " + ChatColor.RED + "-d");
this.addCommandExample("/mv anchors ");
this.setPermission("multiverse.core.anchor.list", "Allows a player to list all anchors.", PermissionDefault.OP);
this.addAdditonalPermission(new Permission("multiverse.core.anchor.create",
"Allows a player to create anchors.", PermissionDefault.OP));
this.addAdditonalPermission(new Permission("multiverse.core.anchor.delete",
"Allows a player to delete anchors.", PermissionDefault.OP));
this.setPermission("multiverse.core.anchor", "Allows management of Anchor Destinations.", PermissionDefault.OP);
this.setItemsPerPage(8); // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
@@ -54,11 +49,6 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
}
private void showList(CommandSender sender, List<String> args) {
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.list", true)) {
sender.sendMessage(ChatColor.RED + "You don't have the permission to list anchors!");
return;
}
sender.sendMessage(ChatColor.LIGHT_PURPLE + "====[ Multiverse Anchor List ]====");
Player p = null;
if (sender instanceof Player) {
@@ -115,14 +105,10 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
return;
}
if (args.size() == 2 && args.get(1).equalsIgnoreCase("-d")) {
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.delete", true)) {
sender.sendMessage(ChatColor.RED + "You don't have the permission to delete anchors!");
if (this.plugin.getAnchorManager().deleteAnchor(args.get(0))) {
sender.sendMessage("Anchor '" + args.get(0) + "' was successfully " + ChatColor.RED + "deleted!");
} else {
if (this.plugin.getAnchorManager().deleteAnchor(args.get(0))) {
sender.sendMessage("Anchor '" + args.get(0) + "' was successfully " + ChatColor.RED + "deleted!");
} else {
sender.sendMessage("Anchor '" + args.get(0) + "' was " + ChatColor.RED + " NOT " + ChatColor.WHITE + "deleted!");
}
sender.sendMessage("Anchor '" + args.get(0) + "' was " + ChatColor.RED + " NOT " + ChatColor.WHITE + "deleted!");
}
return;
}
@@ -132,16 +118,13 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
return;
}
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.create", true)) {
sender.sendMessage(ChatColor.RED + "You don't have the permission to create anchors!");
Player player = (Player) sender;
if (this.plugin.getAnchorManager().saveAnchorLocation(args.get(0), player.getLocation())) {
sender.sendMessage("Anchor '" + args.get(0) + "' was successfully " + ChatColor.GREEN + "created!");
} else {
Player player = (Player) sender;
if (this.plugin.getAnchorManager().saveAnchorLocation(args.get(0), player.getLocation())) {
sender.sendMessage("Anchor '" + args.get(0) + "' was successfully " + ChatColor.GREEN + "created!");
} else {
sender.sendMessage("Anchor '" + args.get(0) + "' was " + ChatColor.RED + " NOT " + ChatColor.WHITE + "created!");
}
sender.sendMessage("Anchor '" + args.get(0) + "' was " + ChatColor.RED + " NOT " + ChatColor.WHITE + "created!");
}
}
@Override
@@ -37,7 +37,7 @@ public class CheckCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
Player p = this.plugin.getServer().getPlayerExact(args.get(0));
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?");
@@ -1,55 +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.commands;
import java.util.List;
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;
/**
* Creates a clone of a world.
*/
public class CloneCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
public CloneCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Clone World");
this.setCommandUsage("/mv clone" + ChatColor.GREEN + " {TARGET} {NAME}" + ChatColor.GOLD + " -g [GENERATOR[:ID]]");
this.setArgRange(2, 4); // SUPPRESS CHECKSTYLE: MagicNumberCheck
this.addKey("mvclone");
this.addKey("mvcl");
this.addKey("mv cl");
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.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)) {
// 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("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!");
}
}
}
@@ -19,7 +19,6 @@ import java.util.Map;
* Allows you to set Global MV Variables.
*/
public class ConfigCommand extends MultiverseCommand {
public ConfigCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Configuration");
@@ -24,7 +24,7 @@ import java.util.List;
* Returns detailed information on the Players where abouts.
*/
public class CoordCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public CoordCommand(MultiverseCore plugin) {
super(plugin);
@@ -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.");
}
@@ -18,15 +18,13 @@ 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;
/**
* Creates a new world and loads it.
*/
public class CreateCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public CreateCommand(MultiverseCore plugin) {
super(plugin);
@@ -67,13 +65,7 @@ public class CreateCommand extends MultiverseCommand {
}
}
if (this.worldManager.isMVWorld(worldName)) {
sender.sendMessage(ChatColor.RED + "Multiverse cannot create " + ChatColor.GOLD + ChatColor.UNDERLINE
+ "another" + ChatColor.RESET + ChatColor.RED + " world named " + worldName);
return;
}
if (worldFile.exists()) {
if (worldFile.exists() || this.worldManager.isMVWorld(worldName)) {
sender.sendMessage(ChatColor.RED + "A Folder/World already exists with this name!");
sender.sendMessage(ChatColor.RED + "If you are confident it is a world you can import with /mvimport");
return;
@@ -96,19 +88,7 @@ public class CreateCommand extends MultiverseCommand {
EnvironmentCommand.showWorldTypes(sender);
return;
}
// Determine if the generator is valid. #918
if (generator != null) {
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.
sender.sendMessage("Invalid generator! '" + generator + "'. " + ChatColor.RED + "Aborting world creation.");
return;
}
}
Command.broadcastCommandMessage(sender, "Starting creation of world '" + worldName + "'...");
if (this.worldManager.addWorld(worldName, environment, seed, type, allowStructures, generator, useSpawnAdjust)) {
@@ -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;
@@ -24,7 +23,7 @@ public class DebugCommand extends MultiverseCommand {
public DebugCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Turn Debug on/off?");
this.setCommandUsage("/mv debug" + ChatColor.GOLD + " [1|2|3|off|silent]");
this.setCommandUsage("/mv debug" + ChatColor.GOLD + " [1|2|3|off]");
this.setArgRange(0, 1);
this.addKey("mv debug");
this.addKey("mv d");
@@ -49,19 +48,18 @@ public class DebugCommand extends MultiverseCommand {
sender.sendMessage(ChatColor.RED + "Error" + ChatColor.WHITE
+ " setting debug level. Please use a number 0-3 " + ChatColor.AQUA + "(3 being many many messages!)");
}
}
plugin.saveMVConfigs();
}
this.displayDebugMode(sender);
}
private void displayDebugMode(CommandSender sender) {
final int debugLevel = plugin.getMVConfig().getGlobalDebug();
if (debugLevel == 0) {
if (plugin.getMVConfig().getGlobalDebug() == 0) {
sender.sendMessage("Multiverse Debug mode is " + ChatColor.RED + "OFF");
} else {
sender.sendMessage("Multiverse Debug mode is " + ChatColor.GREEN + debugLevel);
Logging.fine("Multiverse Debug ENABLED");
sender.sendMessage("Multiverse Debug mode is " + ChatColor.GREEN + plugin.getMVConfig().getGlobalDebug());
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!");
}
}
@@ -53,8 +53,8 @@ public class EnvironmentCommand extends MultiverseCommand {
*/
public static void showWorldTypes(CommandSender sender) {
sender.sendMessage(ChatColor.YELLOW + "Valid World Types are:");
sender.sendMessage(String.format("%sNORMAL%s, %sFLAT, %sLARGEBIOMES %sor %sVERSION_1_1",
ChatColor.GREEN, ChatColor.WHITE, ChatColor.AQUA, ChatColor.RED, ChatColor.WHITE, ChatColor.GOLD));
sender.sendMessage(String.format("%sNORMAL%s, %sFLAT %sor %sVERSION_1_1",
ChatColor.GREEN, ChatColor.WHITE, ChatColor.AQUA, ChatColor.WHITE, ChatColor.GOLD));
}
@Override
@@ -71,15 +71,10 @@ 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")) {
type = "LARGE_BIOMES";
} else if (type.equalsIgnoreCase("amplified")) {
type = "AMPLIFIED";
}
try {
// Now that we've converted a potentially unfriendly value
// to a friendly one, get it from the ENUM!
@@ -1,116 +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.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;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Allows management of Anchor Destinations.
*/
public class GameruleCommand extends MultiverseCommand {
public GameruleCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Set a Minecraft Game Rule for a World.");
this.setCommandUsage("/mv gamerule " + ChatColor.GREEN + "{RULE} {VALUE}" + ChatColor.GOLD + " [WORLD]");
this.setArgRange(2, 3);
this.addKey("mv gamerule");
this.addKey("mv rule");
this.addKey("mvgamerule");
this.addKey("mvrule");
this.addCommandExample("/mv gamerule " + ChatColor.GREEN + "doMobLoot false");
this.addCommandExample("/mvrule " + ChatColor.GREEN + "keepInventory true " + ChatColor.RED + "world_nether");
this.setPermission("multiverse.core.gamerule.set", "Allows a player to set a gamerule.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
// We NEED a world from the command line
final Player p;
if (sender instanceof Player) {
p = (Player) sender;
} else {
p = null;
}
if (args.size() == 2 && p == null) {
sender.sendMessage("From the command line, WORLD is required.");
sender.sendMessage(this.getCommandDesc());
sender.sendMessage(this.getCommandUsage());
sender.sendMessage("Nothing changed.");
return;
}
final GameRule gameRule = GameRule.getByName(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.");
} 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 + ".");
}
}
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 + ", ";
}
}
@@ -1,82 +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.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;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Allows management of Anchor Destinations.
*/
public class GamerulesCommand extends MultiverseCommand {
public GamerulesCommand(MultiverseCore plugin) {
super(plugin);
this.setName("List the Minecraft Game Rules for a World.");
this.setCommandUsage("/mv gamerules" + ChatColor.GOLD + " [WORLD]");
this.setArgRange(0, 1);
this.addKey("mv gamerules");
this.addKey("mv rules");
this.addKey("mvgamerules");
this.addKey("mvrules");
this.addCommandExample("/mv gamerules");
this.addCommandExample("/mvrules " + ChatColor.RED + "world_nether");
this.setPermission("multiverse.core.gamerule.list", "Allows a player to list gamerules.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
// We NEED a world from the command line
final Player p;
if (sender instanceof Player) {
p = (Player) sender;
} else {
p = null;
}
if (args.size() == 0 && p == null) {
sender.sendMessage("From the command line, WORLD is required.");
sender.sendMessage(this.getCommandDesc());
sender.sendMessage(this.getCommandUsage());
sender.sendMessage("Nothing changed.");
return;
}
final World world;
if (args.size() == 0) {
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();
for (final String gameRule : world.getGameRules()) {
if (gameRules.length() != 0) {
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)));
}
sender.sendMessage("=== Gamerules for " + ChatColor.AQUA + world.getName() + ChatColor.WHITE + " ===");
sender.sendMessage(gameRules.toString());
}
}
@@ -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;
@@ -16,6 +15,7 @@ import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Returns a list of loaded generator plugins.
@@ -37,7 +37,7 @@ public class GeneratorCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
Logging.info("PLEASE IGNORE the 'Plugin X does not contain any generators' message below!");
this.plugin.log(Level.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) {
@@ -57,7 +57,7 @@ public class ImportCommand extends MultiverseCommand {
File[] files = worldFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String name) {
return name.toLowerCase().endsWith(".dat");
return name.equalsIgnoreCase("level.dat");
}
});
if (files != null && files.length > 0) {
@@ -95,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();
@@ -117,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;
}
@@ -147,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 (!checkIfIsWorld(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);
}
}
}
@@ -30,7 +30,7 @@ import java.util.List;
* Returns detailed information about a world.
*/
public class InfoCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public InfoCommand(MultiverseCore plugin) {
super(plugin);
@@ -122,16 +122,10 @@ public class InfoCommand extends MultiverseCommand {
//message.add(new FancyMessage("Game Mode: ", StringUtils.capitalize(world.getGameMode().toString()), colors));
Location spawn = world.getSpawnLocation();
message.add(new FancyMessage("Spawn Location: ", plugin.getLocationManipulation().strCoords(spawn), colors));
message.add(new FancyMessage("World Scale: ", String.valueOf(world.getScaling()), colors));
message.add(new FancyMessage("World Seed: ", String.valueOf(world.getSeed()), colors));
message.add(new FancyMessage("World Scale: ", world.getScaling() + "", 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));
this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency()), colors));
} else {
message.add(new FancyMessage("Price to enter this world: ", ChatColor.GREEN + "FREE!", colors));
}
@@ -181,8 +175,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");
@@ -25,7 +25,7 @@ import java.util.List;
* Used to modify various aspects of worlds.
*/
public class ModifyAddCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public ModifyAddCommand(MultiverseCore plugin) {
super(plugin);
@@ -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;
}
@@ -85,9 +85,6 @@ public class ModifyAddCommand extends MultiverseCommand {
if (world.addToVariable(property, value)) {
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA
+ value + ChatColor.WHITE + " was " + ChatColor.GREEN + "added to " + ChatColor.GREEN + property);
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
sender.sendMessage(value + " could not be added to " + property);
}
@@ -22,7 +22,7 @@ import java.util.List;
* Removes all values from a world-property.
*/
public class ModifyClearCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public ModifyClearCommand(MultiverseCore plugin) {
super(plugin);
@@ -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
@@ -80,9 +80,6 @@ public class ModifyClearCommand extends MultiverseCommand {
sender.sendMessage(property + " was cleared. It contains 0 values now.");
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + property + ChatColor.WHITE + " was "
+ ChatColor.GREEN + "CLEARED" + ChatColor.WHITE + ". It contains " + ChatColor.LIGHT_PURPLE + "0" + ChatColor.WHITE + " values now.");
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
sender.sendMessage(ChatColor.RED + "Error: " + ChatColor.GOLD + property
+ ChatColor.WHITE + " was " + ChatColor.GOLD + "NOT" + ChatColor.WHITE + " cleared.");
@@ -22,7 +22,7 @@ import java.util.List;
* Removes values from a world-property.
*/
public class ModifyRemoveCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public ModifyRemoveCommand(MultiverseCore plugin) {
super(plugin);
@@ -78,16 +78,13 @@ 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
if (world.removeFromVariable(property, value)) {
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + value + ChatColor.WHITE
+ " was " + ChatColor.RED + "removed from " + ChatColor.GREEN + property);
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
sender.sendMessage(ChatColor.RED + "There was an error removing " + ChatColor.GRAY
+ value + ChatColor.WHITE + " from " + ChatColor.GOLD + property);
@@ -23,7 +23,7 @@ import java.util.List;
* Used to set world-properties.
*/
public class ModifySetCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public ModifySetCommand(MultiverseCore plugin) {
super(plugin);
@@ -111,9 +111,6 @@ public class ModifySetCommand extends MultiverseCommand {
if (world.setPropertyValue(property, value)) {
sender.sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Property " + ChatColor.AQUA + property
+ ChatColor.WHITE + " was set to " + ChatColor.GREEN + value);
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
sender.sendMessage(ChatColor.RED + world.getPropertyHelp(property));
}
@@ -24,7 +24,7 @@ import java.util.List;
* Removes a type of mob from a world.
*/
public class PurgeCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public PurgeCommand(MultiverseCore plugin) {
super(plugin);
@@ -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);
@@ -1,58 +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.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 java.io.File;
import java.util.List;
/**
* States who is in what world.
*/
public class ScriptCommand extends MultiverseCommand {
public ScriptCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Runs a script.");
this.setCommandUsage("/mv script" + ChatColor.GOLD + " {script} [target]");
this.setArgRange(1, 2);
this.addKey("mv script");
this.addKey("mvscript");
this.addCommandExample(String.format("/mv script %sscript.txt", ChatColor.GOLD));
this.addCommandExample(String.format("/mv script %stest.txt %ssomeplayer", ChatColor.GOLD, ChatColor.GREEN));
this.setPermission("multiverse.core.script", "Runs a script.", PermissionDefault.OP);
}
@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!");
return;
}
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
String target = null;
if (args.size() == 2) {
target = args.get(1);
}
plugin.getScriptAPI().executeScript(file, target, player);
sender.sendMessage(String.format("Script '%s%s%s' finished!", ChatColor.GOLD, file.getName(), ChatColor.WHITE));
}
}
@@ -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,40 @@ 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()));
} 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.");
}
}
}
@@ -1,52 +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.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Enables debug-information.
*/
public class SilentCommand extends MultiverseCommand {
public SilentCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Turn silent mode on/off?");
this.setCommandUsage("/mv silent" + ChatColor.GOLD + " [true|false|on|off]");
this.setArgRange(0, 1);
this.addKey("mv silent");
this.addKey("mvsilent");
this.addCommandExample("/mv silent " + ChatColor.GOLD + "true");
this.setPermission("multiverse.core.silent", "Reduces the amount of startup messages.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
if (args.size() == 1) {
if (args.get(0).equalsIgnoreCase("on")) {
args.set(0, "true");
}
plugin.getMVConfig().setSilentStart(Boolean.valueOf(args.get(0)));
plugin.saveMVConfigs();
}
this.displaySilentMode(sender);
}
private void displaySilentMode(CommandSender sender) {
if (plugin.getMVConfig().getSilentStart()) {
sender.sendMessage("Multiverse Silent Start mode is " + ChatColor.GREEN + "ON");
} else {
sender.sendMessage("Multiverse Silent Start mode is " + ChatColor.RED + "OFF");
}
}
}
@@ -50,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 = this.plugin.getServer().getPlayerExact(args.get(0));
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,11 +7,8 @@
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;
@@ -34,14 +31,14 @@ import java.util.logging.Level;
* Used to teleport players.
*/
public class TeleportCommand extends MultiverseCommand {
private final SafeTTeleporter playerTeleporter;
private SafeTTeleporter playerTeleporter;
public TeleportCommand(MultiverseCore plugin) {
super(plugin);
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 = this.plugin.getServer().getPlayerExact(args.get(0));
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);
@@ -95,7 +92,7 @@ public class TeleportCommand extends MultiverseCommand {
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;
}
@@ -159,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);
@@ -175,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);
@@ -7,118 +7,39 @@
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;
import java.util.logging.Level;
/**
* 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] 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
@@ -128,94 +49,70 @@ 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().size()).append('\n');
buffer.append("[Multiverse-Core] Multiverse Plugins Loaded: ").append(this.plugin.getPluginCount()).append('\n');
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);
}
this.plugin.log(Level.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);
}
Logging.info("Version info dumped here: %s", pasteUrl);
sender.sendMessage("Version info dumped here: " + ChatColor.GREEN + pasteUrl);
plugin.log(Level.INFO, "Version info dumped here: " + 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(), ", ");
}
}
@@ -15,15 +15,14 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
/**
* States who is in what world.
*/
public class WhoCommand extends MultiverseCommand {
private final MVWorldManager worldManager;
private MVWorldManager worldManager;
public WhoCommand(MultiverseCore plugin) {
super(plugin);
@@ -51,14 +50,6 @@ 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);
}
}
if (args.size() == 1) {
if (args.get(0).equalsIgnoreCase("--all") || args.get(0).equalsIgnoreCase("-a")) {
showAll = true;
@@ -77,19 +68,18 @@ public class WhoCommand extends MultiverseCommand {
sender.sendMessage(String.format("%s--- Players in %s%s ---", ChatColor.AQUA,
world.getColoredWorldString(), ChatColor.AQUA));
sender.sendMessage(this.buildPlayerString(world, p, visiblePlayers));
sender.sendMessage(buildPlayerString(world));
return;
}
}
// multiworld mode
sender.sendMessage(ChatColor.AQUA + "--- Worlds and their players --- "
+ visiblePlayers.size() + "/" + plugin.getServer().getMaxPlayers());
sender.sendMessage(ChatColor.AQUA + "--- Worlds and their players ---");
boolean shownOne = false;
for (MultiverseWorld world : this.worldManager.getMVWorlds()) {
if (this.plugin.getMVPerms().canEnterWorld(p, world)) { // only show world if the player can access it
if (showAll || !world.getCBWorld().getPlayers().isEmpty()) { // either show all or show if the world is not empty
sender.sendMessage(String.format("%s%s - %s", world.getColoredWorldString(), ChatColor.WHITE, buildPlayerString(world, p, visiblePlayers)));
sender.sendMessage(String.format("%s%s - %s", world.getColoredWorldString(), ChatColor.WHITE, buildPlayerString(world)));
shownOne = true;
}
}
@@ -100,18 +90,17 @@ public class WhoCommand extends MultiverseCommand {
return;
}
private static String buildPlayerString(MultiverseWorld world, Player viewer, final Collection<Player> visiblePlayers) {
// Retrieve the players in this world
private static String buildPlayerString(MultiverseWorld world) {
List<Player> players = world.getCBWorld().getPlayers();
StringBuilder playerBuilder = new StringBuilder();
for (Player player : players) {
// If the viewer is the console or the viewier is allowed to see the player, show them.
// Make sure we're also ONLY showing online players.
// Since we already checked visible players, we'll just make sure who we're about to show is in that.
if (visiblePlayers.contains(player))
if (players.size() == 0) {
return "No players found.";
} else {
StringBuilder playerBuilder = new StringBuilder();
for (Player player : players) {
playerBuilder.append(player.getDisplayName()).append(", ");
}
String bString = playerBuilder.toString();
return bString.substring(0, bString.length() - 2);
}
String bString = playerBuilder.toString();
return (bString.length() == 0) ? "No players found." : bString.substring(0, bString.length() - 2);
}
}
@@ -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,9 +14,8 @@ import org.jetbrains.annotations.Nullable;
public class EntryFee extends SerializationConfig {
@Property
private double amount;
@Property(serializor = EntryFeeCurrencySerializor.class)
@Nullable
private Material currency;
@Property
private int currency;
public EntryFee() {
super();
@@ -36,7 +31,7 @@ public class EntryFee extends SerializationConfig {
@Override
protected void setDefaults() {
amount = 0D;
currency = null;
currency = -1;
}
/**
@@ -49,8 +44,7 @@ public class EntryFee extends SerializationConfig {
/**
* @return the currency
*/
@Nullable
public Material getCurrency() {
public int getCurrency() {
return currency;
}
@@ -66,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();
}
@@ -17,8 +17,6 @@ public class SubSpawnSettings extends SerializationConfig {
@Property
private boolean spawn;
@Property
private int spawnrate;
@Property
private List<String> exceptions;
public SubSpawnSettings() {
@@ -36,7 +34,6 @@ public class SubSpawnSettings extends SerializationConfig {
public void setDefaults() {
spawn = true;
exceptions = new ArrayList<String>();
spawnrate = -1;
}
/**
@@ -54,23 +51,9 @@ public class SubSpawnSettings extends SerializationConfig {
}
/**
* @return The exceptions
* @return the exceptions
*/
public List<String> getExceptions() {
return exceptions;
}
/**
* @param rate The new spawn rate
*/
public void setSpawnRate(int rate) {
this.spawnrate = rate;
}
/**
* @return The spawn rate
*/
public int getSpawnRate() {
return this.spawnrate;
}
}
@@ -7,13 +7,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,11 +18,9 @@ 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;
/**
* {@inheritDoc}
@@ -43,15 +36,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,14 +46,7 @@ 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());
if (this.knownBedLoc == null) {
((Player) entity).sendMessage("The bed was " + ChatColor.RED + "invalid or blocked" + ChatColor.RESET + ". Sorry.");
}
this.knownBedLoc = ((Player) entity).getBedSpawnLocation();
return this.knownBedLoc;
}
return null;
@@ -87,7 +65,7 @@ public class BedDestination implements MVDestination {
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
this.plugin = (MultiverseCore) plugin;
// Not needed.
}
/**
@@ -136,6 +114,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();
}
@@ -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);
}
}
@@ -11,33 +11,49 @@ import org.bukkit.ChatColor;
/**
* A regular {@link ChatColor} represented by an english string.
* @see ChatColor
*/
public enum EnglishChatColor {
// BEGIN CHECKSTYLE-SUPPRESSION: JavadocVariable
AQUA(ChatColor.AQUA),
BLACK(ChatColor.BLACK),
BLUE(ChatColor.BLUE),
DARKAQUA(ChatColor.DARK_AQUA),
DARKBLUE(ChatColor.DARK_BLUE),
DARKGRAY(ChatColor.DARK_GRAY),
DARKGREEN(ChatColor.DARK_GREEN),
DARKPURPLE(ChatColor.DARK_PURPLE),
DARKRED(ChatColor.DARK_RED),
GOLD(ChatColor.GOLD),
GRAY(ChatColor.GRAY),
GREEN(ChatColor.GREEN),
LIGHTPURPLE(ChatColor.LIGHT_PURPLE),
RED(ChatColor.RED),
YELLOW(ChatColor.YELLOW),
WHITE(ChatColor.WHITE);
// END CHECKSTYLE-SUPPRESSION: JavadocVariable
/*
* I know. this is quite ugly.
*/
/** AQUA. */
AQUA("AQUA", ChatColor.AQUA),
/** BLACK. */
BLACK("BLACK", ChatColor.BLACK),
/** BLUE. */
BLUE("BLUE", ChatColor.BLUE),
/** DARKAQUA. */
DARKAQUA("DARKAQUA", ChatColor.DARK_AQUA),
/** DARKBLUE. */
DARKBLUE("DARKBLUE", ChatColor.DARK_BLUE),
/** DARKGRAY. */
DARKGRAY("DARKGRAY", ChatColor.DARK_GRAY),
/** DARKGREEN. */
DARKGREEN("DARKGREEN", ChatColor.DARK_GREEN),
/** DARKPURPLE. */
DARKPURPLE("DARKPURPLE", ChatColor.DARK_PURPLE),
/** DARKRED. */
DARKRED("DARKRED", ChatColor.DARK_RED),
/** GOLD. */
GOLD("GOLD", ChatColor.GOLD),
/** GRAY. */
GRAY("GRAY", ChatColor.GRAY),
/** GREEN. */
GREEN("GREEN", ChatColor.GREEN),
/** LIGHTPURPLE. */
LIGHTPURPLE("LIGHTPURPLE", ChatColor.LIGHT_PURPLE),
/** RED. */
RED("RED", ChatColor.RED),
/** YELLOW. */
YELLOW("YELLOW", ChatColor.YELLOW),
/** WHITE. */
WHITE("WHITE", ChatColor.WHITE);
private ChatColor color;
private String text;
private final ChatColor color;
//private final String text;
EnglishChatColor(ChatColor color) {
EnglishChatColor(String name, ChatColor color) {
this.color = color;
this.text = name;
}
/**
@@ -45,7 +61,7 @@ public enum EnglishChatColor {
* @return The text.
*/
public String getText() {
return this.name();
return this.text;
}
/**
@@ -76,7 +92,7 @@ public enum EnglishChatColor {
public static EnglishChatColor fromString(String text) {
if (text != null) {
for (EnglishChatColor c : EnglishChatColor.values()) {
if (text.equalsIgnoreCase(c.name())) {
if (text.equalsIgnoreCase(c.text)) {
return c;
}
}
@@ -1,49 +0,0 @@
package com.onarandombox.MultiverseCore.enums;
import org.bukkit.ChatColor;
/**
* A regular {@link ChatColor} represented by an english string.
* @see ChatColor
*/
public enum EnglishChatStyle {
// BEGIN CHECKSTYLE-SUPPRESSION: JavadocVariable
/** No style. */
NORMAL(null),
MAGIC(ChatColor.MAGIC),
BOLD(ChatColor.BOLD),
STRIKETHROUGH(ChatColor.STRIKETHROUGH),
UNDERLINE(ChatColor.UNDERLINE),
ITALIC(ChatColor.ITALIC);
// END CHECKSTYLE-SUPPRESSION: JavadocVariable
private final ChatColor color;
EnglishChatStyle(ChatColor color) {
this.color = color;
}
/**
* Gets the color.
* @return The color as {@link ChatColor}.
*/
public ChatColor getColor() {
return color;
}
/**
* Constructs an {@link EnglishChatStyle} from a {@link String}.
* @param text The {@link String}.
* @return The {@link EnglishChatStyle}.
*/
public static EnglishChatStyle fromString(String text) {
if (text != null) {
for (EnglishChatStyle c : EnglishChatStyle.values()) {
if (text.equalsIgnoreCase(c.name())) {
return c;
}
}
}
return null;
}
}
@@ -16,7 +16,7 @@ import java.util.List;
* Called when the Multiverse-config should be reloaded.
*/
public class MVConfigReloadEvent extends Event {
private final List<String> configsLoaded;
private List<String> configsLoaded;
public MVConfigReloadEvent(List<String> configsLoaded) {
this.configsLoaded = configsLoaded;
@@ -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;
}
}
@@ -17,8 +17,8 @@ import org.bukkit.event.HandlerList;
* This event is thrown when a portal is touched.
*/
public class MVPlayerTouchedPortalEvent extends Event implements Cancellable {
private final Player p;
private final Location l;
private Player p;
private Location l;
private boolean isCancelled;
private boolean canUse = true;
@@ -16,9 +16,10 @@ import org.bukkit.event.HandlerList;
* Called when a player is respawning.
*/
public class MVRespawnEvent extends Event {
private final Player player;
private final String respawnMethod;
private Player player;
private Location location;
private String respawnMethod;
public MVRespawnEvent(Location spawningAt, Player p, String respawnMethod) {
this.player = p;
@@ -21,10 +21,10 @@ import org.bukkit.event.HandlerList;
* Event that gets called when a player use the /mvtp command.
*/
public class MVTeleportEvent extends Event implements Cancellable {
private final Player teleportee;
private final CommandSender teleporter;
private final MVDestination dest;
private final boolean useSafeTeleport;
private Player teleportee;
private CommandSender teleporter;
private MVDestination dest;
private boolean useSafeTeleport;
private boolean isCancelled;
public MVTeleportEvent(MVDestination dest, Player teleportee, CommandSender teleporter, boolean safeTeleport) {
@@ -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()));
}
}
@@ -24,11 +24,11 @@ import org.bukkit.event.HandlerList;
* @param <T> The type of the property that was set.
*/
public class MVWorldPropertyChangeEvent<T> extends Event implements Cancellable {
private final MultiverseWorld world;
private final CommandSender changer;
private final String name;
private T value;
private MultiverseWorld world;
private CommandSender changer;
private boolean isCancelled = false;
private String name;
private T value;
public MVWorldPropertyChangeEvent(MultiverseWorld world, CommandSender changer, String name, T value) {
this.world = world;
@@ -1,35 +0,0 @@
package com.onarandombox.MultiverseCore.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
/**
* A wrapper for the {@link AsyncPlayerChatEvent}.
*/
public class AsyncChatEvent implements ChatEvent {
private final AsyncPlayerChatEvent event;
public AsyncChatEvent(AsyncPlayerChatEvent event) {
this.event = event;
}
@Override
public boolean isCancelled() {
return event.isCancelled();
}
@Override
public String getFormat() {
return event.getFormat();
}
@Override
public void setFormat(String s) {
event.setFormat(s);
}
@Override
public Player getPlayer() {
return event.getPlayer();
}
}
@@ -1,29 +0,0 @@
package com.onarandombox.MultiverseCore.listeners;
import org.bukkit.entity.Player;
/**
* A wrapper for the two chat-events in Bukkit.
*/
public interface ChatEvent {
/**
* @return Whether this event is cancelled.
*/
boolean isCancelled();
/**
* @return The format.
*/
String getFormat();
/**
* Sets the format.
* @param s The new format.
*/
void setFormat(String s);
/**
* @return The player.
*/
Player getPlayer();
}
@@ -1,35 +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 java.util.logging.Level;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import com.onarandombox.MultiverseCore.MultiverseCore;
/**
* Multiverse's {@link org.bukkit.event.Listener} for players.
*/
public class MVAsyncPlayerChatListener extends MVChatListener {
public MVAsyncPlayerChatListener(MultiverseCore plugin, MVPlayerListener playerListener) {
super(plugin, playerListener);
Logging.fine("Created AsyncPlayerChatEvent listener.");
}
/**
* This method is called when a player wants to chat.
* @param event The Event that was fired.
*/
@EventHandler
public void playerChat(AsyncPlayerChatEvent event) {
this.playerChat(new AsyncChatEvent(event));
}
}
@@ -1,59 +0,0 @@
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;
/**
* Multiverse's {@link org.bukkit.event.Listener} for players.
*/
public abstract class MVChatListener implements Listener {
private final MultiverseCore plugin;
private final MVWorldManager worldManager;
private final MVPlayerListener playerListener;
public MVChatListener(MultiverseCore plugin, MVPlayerListener playerListener) {
this.plugin = plugin;
this.worldManager = plugin.getMVWorldManager();
this.playerListener = playerListener;
}
/**
* This handles a {@link ChatEvent}.
* @param event The {@link ChatEvent}.
*/
public void playerChat(ChatEvent event) {
if (event.isCancelled()) {
return;
}
// Check whether the Server is set to prefix the chat with the World name.
// If not we do nothing, if so we need to check if the World has an Alias.
if (plugin.getMVConfig().getPrefixChat()) {
String world = playerListener.getPlayerWorld().get(event.getPlayer().getName());
if (world == null) {
world = event.getPlayer().getWorld().getName();
playerListener.getPlayerWorld().put(event.getPlayer().getName(), world);
}
String prefix = "";
// If we're not a MV world, don't do anything
if (!this.worldManager.isMVWorld(world)) {
return;
}
MultiverseWorld mvworld = this.worldManager.getMVWorld(world);
if (mvworld.isHidden()) {
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);
}
}
}
@@ -7,13 +7,17 @@
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;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Ghast;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Squid;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
@@ -22,14 +26,16 @@ import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import java.util.List;
import java.util.logging.Level;
/**
* Multiverse's Entity {@link Listener}.
*/
public class MVEntityListener implements Listener {
private final MultiverseCore plugin;
private final MVWorldManager worldManager;
private MultiverseCore plugin;
private MVWorldManager worldManager;
public MVEntityListener(MultiverseCore plugin) {
this.plugin = plugin;
@@ -81,8 +87,7 @@ public class MVEntityListener implements Listener {
public void creatureSpawn(CreatureSpawnEvent event) {
// Check to see if the Creature is spawned by a plugin, we don't want to prevent this behaviour.
// TODO: Allow the egg thing to be a config param. Doubt this will be per world; seems silly.
if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.SPAWNER_EGG
|| event.getSpawnReason() == SpawnReason.BREEDING) {
if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
return;
}
@@ -95,16 +100,53 @@ public class MVEntityListener implements Listener {
return;
EntityType type = event.getEntityType();
MultiverseWorld mvworld = this.worldManager.getMVWorld(world.getName());
/**
* Handle people with non-standard animals: ie a patched craftbukkit.
*/
if (type == null || type.getName() == null) {
Logging.finer("Found a null typed creature.");
if (type == null) {
this.plugin.log(Level.FINER, "Found a null typed creature.");
return;
}
MultiverseWorld mvworld = this.worldManager.getMVWorld(world.getName());
event.setCancelled(this.plugin.getMVWorldManager().getTheWorldPurger().shouldWeKillThisCreature(mvworld, event.getEntity()));
/**
* Animal Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Animals || event.getEntity() instanceof Squid)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getAnimalList(), mvworld.canAnimalsSpawn(), type.getName().toUpperCase()));
}
/**
* Monster Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Monster || event.getEntity() instanceof Ghast || event.getEntity() instanceof Slime)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getMonsterList(), mvworld.canMonstersSpawn(), type.getName().toUpperCase()));
}
}
private static boolean shouldWeKillThisCreature(List<String> creatureList, boolean allowCreatureSpawning, String creature) {
if (creatureList.isEmpty() && allowCreatureSpawning) {
// 1. There are no exceptions and animals are allowed. Save it.
return false;
} else if (creatureList.isEmpty()) {
// 2. There are no exceptions and animals are NOT allowed. Kill it.
return true;
} else if (creatureList.contains(creature.toUpperCase()) && allowCreatureSpawning) {
// 3. There ARE exceptions and animals ARE allowed. Kill it.
return true;
} else if (!creatureList.contains(creature.toUpperCase()) && allowCreatureSpawning) {
// 4. There ARE exceptions and animals ARE NOT allowed. SAVE it.
return false;
} else if (creatureList.contains(creature.toUpperCase()) && !allowCreatureSpawning) {
// 5. No animals are allowed to be spawned, BUT this one can stay...
return false;
} else if (!creatureList.contains(creature.toUpperCase()) && !allowCreatureSpawning) {
// 6. Animals are NOT allowed to spawn, and this creature is not in the save list... KILL IT
return true;
} else {
// This code should NEVER execute. I just left the verbose conditions in right now.
throw new UnsupportedOperationException();
}
}
}
@@ -1,43 +0,0 @@
package com.onarandombox.MultiverseCore.listeners;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.MapInitializeEvent;
import org.bukkit.map.MapView;
/**
* A listener for bukkit map events.
*/
public class MVMapListener implements Listener {
private final MultiverseCore plugin;
public MVMapListener(final MultiverseCore plugin) {
this.plugin = plugin;
}
/**
* This method is called when a map is initialized.
* @param event The event that was fired.
*/
@EventHandler
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().getDurability() == event.getMap().getId()) {
final Location playerLoc = player.getLocation();
final MapView map = event.getMap();
map.setCenterX(playerLoc.getBlockX());
map.setCenterZ(playerLoc.getBlockZ());
map.setWorld(playerLoc.getWorld());
return;
}
}
}
}
@@ -1,36 +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 java.util.logging.Level;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerChatEvent;
import com.onarandombox.MultiverseCore.MultiverseCore;
/**
* Multiverse's {@link org.bukkit.event.Listener} for players.
*/
@SuppressWarnings("deprecation") // this exists only for downwards compatibility
public class MVPlayerChatListener extends MVChatListener {
public MVPlayerChatListener(MultiverseCore plugin, MVPlayerListener playerListener) {
super(plugin, playerListener);
Logging.fine("Registered PlayerChatEvent listener.");
}
/**
* This method is called when a player wants to chat.
* @param event The Event that was fired.
*/
@EventHandler
public void playerChat(PlayerChatEvent event) {
this.playerChat(new NormalChatEvent(event));
}
}
@@ -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.event.MVRespawnEvent;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
@@ -27,33 +21,55 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.logging.Level;
/**
* Multiverse's {@link Listener} for players.
*/
public class MVPlayerListener implements Listener {
private final MultiverseCore plugin;
private final MVWorldManager worldManager;
private final PermissionTools pt;
private MultiverseCore plugin;
private MVWorldManager worldManager;
private PermissionTools pt;
private final Map<String, String> playerWorld = new ConcurrentHashMap<String, String>();
public MVPlayerListener(MultiverseCore plugin) {
this.plugin = plugin;
worldManager = plugin.getMVWorldManager();
pt = new PermissionTools(plugin);
}
/**
* @return the playerWorld-map
* This method is called when a player wants to chat.
* @param event The Event that was fired.
*/
public Map<String, String> getPlayerWorld() {
return playerWorld;
@EventHandler
public void playerChat(PlayerChatEvent event) {
if (event.isCancelled()) {
return;
}
// Check whether the Server is set to prefix the chat with the World name.
// If not we do nothing, if so we need to check if the World has an Alias.
if (plugin.getMVConfig().getPrefixChat()) {
String world = event.getPlayer().getWorld().getName();
String prefix = "";
// If we're not a MV world, don't do anything
if (!this.worldManager.isMVWorld(world)) {
return;
}
MultiverseWorld mvworld = this.worldManager.getMVWorld(world);
if (mvworld.isHidden()) {
return;
}
prefix = mvworld.getColoredWorldString();
String format = event.getFormat();
event.setFormat("[" + prefix + "]" + format);
}
}
/**
@@ -71,7 +87,7 @@ public class MVPlayerListener implements Listener {
if (mvWorld.getBedRespawn() && event.isBedSpawn()) {
Logging.fine("Spawning " + event.getPlayer().getName() + " at their bed");
this.plugin.log(Level.FINE, "Spawning " + event.getPlayer().getName() + " at their bed");
return;
}
@@ -110,15 +126,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): "
+ worldManager.getFirstSpawnWorld().getSpawnLocation());
this.plugin.log(Level.FINE, String.format("Moving NEW player to(firstspawnoverride): %s",
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!");
@@ -126,8 +142,7 @@ public class MVPlayerListener implements Listener {
}
}
// Handle the Players GameMode setting for the new world.
this.handleGameModeAndFlight(event.getPlayer(), event.getPlayer().getWorld());
playerWorld.put(p.getName(), p.getWorld().getName());
this.handleGameMode(event.getPlayer(), event.getPlayer().getWorld());
}
/**
@@ -137,8 +152,7 @@ public class MVPlayerListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void playerChangedWorld(PlayerChangedWorldEvent event) {
// Permissions now determine whether or not to handle a gamemode.
this.handleGameModeAndFlight(event.getPlayer(), event.getPlayer().getWorld());
playerWorld.put(event.getPlayer().getName(), event.getPlayer().getWorld().getName());
this.handleGameMode(event.getPlayer(), event.getPlayer().getWorld());
}
/**
@@ -156,8 +170,9 @@ public class MVPlayerListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void playerTeleport(PlayerTeleportEvent event) {
Logging.finer("Got teleport event for player '"
+ event.getPlayer().getName() + "' with cause '" + event.getCause() + "'");
this.plugin.log(Level.FINER, String.format(
"Got teleport event for player '%s' with cause '%s'",
event.getPlayer().getName(), event.getCause()));
if (event.isCancelled()) {
return;
}
@@ -166,25 +181,20 @@ 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 '"
+ teleporterName + "', fetched from name '" + teleportee.getName() + "'");
this.plugin.log(Level.FINER, String.format("Inferred sender '%s' from name '%s', fetched from name '%s'",
teleporter, teleporterName, 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.");
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, String.format("Player '%s' is teleporting to the same world.",
teleportee.getName()));
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
return;
}
@@ -192,51 +202,33 @@ 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()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have the FUNDS required to enter it.");
this.plugin.log(Level.FINE, String.format(
"Player '%s' was DENIED ACCESS to '%s' because '%s' don't have the FUNDS required to enter it.",
teleportee.getName(), toWorld.getAlias(), teleporter.getName()));
return;
}
// Check if player is allowed to enter the world if we're enforcing permissions
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, teleporter, teleportee));
if (event.isCancelled() && teleporter != null) {
Logging.fine("Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have: multiverse.access." + event.getTo().getWorld().getName());
return;
this.plugin.log(Level.FINE, String.format(
"Player '%s' was DENIED ACCESS to '%s' because '%s' don't have: multiverse.access.%s",
teleportee.getName(), toWorld.getAlias(), teleporter.getName(),
event.getTo().getWorld().getName()));
} else {
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
}
} else {
Logging.fine("Player '" + teleportee.getName()
+ "' was allowed to go to '" + toWorld.getAlias() + "' because enforceaccess is off.");
this.plugin.log(Level.FINE, String.format(
"Player '%s' was allowed to go to '%s' because enforceaccess is off.",
teleportee.getName(), toWorld.getAlias()));
}
// Does a limit actually exist?
if (toWorld.getPlayerLimit() > -1) {
// Are there equal or more people on the world than the limit?
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()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because the world is full and '" + teleporter.getName()
+ "' doesn't have: mv.bypass.playerlimit." + event.getTo().getWorld().getName());
event.setCancelled(true);
return;
}
}
}
// By this point anything cancelling the event has returned on the method, meaning the teleport is a success \o/
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
}
private void stateSuccess(String playerName, String worldName) {
Logging.fine("MV-Core is allowing Player '" + playerName
+ "' to go to '" + worldName + "'.");
this.plugin.log(Level.FINE, String.format(
"MV-Core is allowing Player '%s' to go to '%s'.",
playerName, worldName));
}
/**
@@ -252,7 +244,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.
@@ -282,38 +274,24 @@ 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()
+ "' was DENIED ACCESS to '" + event.getTo().getWorld().getName()
+ "' because they don't have the FUNDS required to enter.");
this.plugin.log(Level.FINE, String.format("Player '%s' was DENIED ACCESS to '%s' because they don't have the FUNDS required to enter.",
event.getPlayer().getName(), event.getTo().getWorld().getName()));
return;
}
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, event.getPlayer(), event.getPlayer()));
if (event.isCancelled()) {
Logging.fine("Player '" + event.getPlayer().getName()
+ "' was DENIED ACCESS to '" + event.getTo().getWorld().getName()
+ "' because they don't have: multiverse.access." + event.getTo().getWorld().getName());
this.plugin.log(Level.FINE, String.format("Player '%s' was DENIED ACCESS to '%s' because they don't have: multiverse.access.%s",
event.getPlayer().getName(), event.getTo().getWorld().getName(), event.getTo().getWorld().getName()));
}
} else {
Logging.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());
}
this.plugin.log(Level.FINE, String.format("Player '%s' was allowed to go to '%s' because enforceaccess is off.",
event.getPlayer().getName(), event.getTo().getWorld().getName()));
}
}
@@ -329,14 +307,14 @@ public class MVPlayerListener implements Listener {
}
// FOLLOWING 2 Methods and Private class handle Per Player GameModes.
private void handleGameModeAndFlight(Player player, World world) {
private void handleGameMode(Player player, World world) {
MultiverseWorld mvWorld = this.worldManager.getMVWorld(world.getName());
if (mvWorld != null) {
this.handleGameModeAndFlight(player, mvWorld);
this.handleGameMode(player, mvWorld);
} else {
Logging.finer("Not handling gamemode and flight for world '" + world.getName()
+ "' not managed by Multiverse.");
this.plugin.log(Level.FINER, String.format(
"Not handling gamemode for world '%s' not managed by Multiverse.", world.getName()));
}
}
@@ -345,40 +323,61 @@ public class MVPlayerListener implements Listener {
* @param player The {@link Player}.
* @param world The world the player is in.
*/
public void handleGameModeAndFlight(final Player player, final MultiverseWorld world) {
public void handleGameMode(final Player player, final MultiverseWorld world) {
// We perform this task one tick later to MAKE SURE that the player actually reaches the
// destination world, otherwise we'd be changing the player mode if they havent moved anywhere.
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
// destination world, otherwise we'd be changing the player mode if they haven't moved anywhere.
if (!this.pt.playerCanIgnoreGameModeRestriction(world, player)) {
this.plugin.log(Level.FINE, "Handeling gamemode for player: " + player.getName());
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
new Runnable() {
@Override
public void run() {
if (!MVPlayerListener.this.pt.playerCanIgnoreGameModeRestriction(world, player)) {
// Check that the player is in the new world and they haven't been teleported elsewhere or the event cancelled.
if (player.getWorld() == world.getCBWorld()) {
Logging.fine("Handling gamemode for player: %s, Changing to %s", player.getName(), world.getGameMode().toString());
Logging.finest("From World: %s", player.getWorld());
Logging.finest("To World: %s", world);
player.setGameMode(world.getGameMode());
// Check if their flight mode should change
// TODO need a override permission for this
if (player.getAllowFlight() && !world.getAllowFlight() && player.getGameMode() != GameMode.CREATIVE) {
player.setAllowFlight(false);
if (player.isFlying()) {
player.setFlying(false);
}
} else if (world.getAllowFlight()) {
if (player.getGameMode() == GameMode.CREATIVE) {
player.setAllowFlight(true);
}
}
} else {
Logging.fine("The gamemode/allowfly was NOT changed for player '%s' because he is now in world '%s' instead of world '%s'",
player.getName(), player.getWorld().getName(), world.getName());
}
// Check that the player is in the new world and they haven't been teleported elsewhere or the event cancelled.
if (player.getWorld() == world.getCBWorld()) {
MultiverseCore.staticLog(Level.FINEST, "From World: " + player.getWorld());
MultiverseCore.staticLog(Level.FINEST, "To World: " + world);
player.setGameMode(world.getGameMode());
} else {
Logging.fine("Player: " + player.getName() + " is IMMUNE to gamemode changes!");
MultiverseCore.staticLog(Level.FINE,
String.format("The gamemode was NOT changed for player '%s' because he is now in world '%s' instead of world '%s'",
player.getName(), player.getWorld().getName(), world.getName()));
}
}
}, 1L);
} else {
this.plugin.log(Level.FINE, String.format("Player: %s is IMMUNE to gamemode changes!", player.getName()));
}
}
/**
* Handles the allowflight attribute for the specified {@link Player}.
* @param player The {@link Player}.
* @param world The world the player is in.
*/
public void handleAllowFlight(final Player player, final MultiverseWorld world) {
// We perform this task one tick later to MAKE SURE that the player actually reaches the
// destination world, otherwise we'd be changing the player mode if they haven't moved anywhere.
if (!this.pt.playerCanIgnoreAllowFlightRestriction(world, player)) {
this.plugin.log(Level.FINE, "Handeling flight for player: " + player.getName());
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
new Runnable() {
@Override
public void run() {
// Check that the player is in the new world and they haven't been teleported elsewhere or the event cancelled.
if (player.getWorld() == world.getCBWorld()) {
player.setAllowFlight(world.isFlightAllowed());
MultiverseCore.staticLog(Level.FINER,
String.format("%s's allowFlight was set to %b!",
player.getName(), world.isFlightAllowed()));
} else {
MultiverseCore.staticLog(Level.FINE,
String.format("allowFlight was NOT changed for player '%s' because he is now in world '%s' instead of world '%s'",
player.getName(), player.getWorld().getName(), world.getName()));
}
}
}, 1L);
} else {
this.plugin.log(Level.FINE, "Player: " + player.getName() + " is IMMUNE to flight changes!");
}
}
}
@@ -0,0 +1,59 @@
/******************************************************************************
* 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) {
// 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,26 +7,23 @@
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.
*/
public class MVPortalListener implements Listener {
private final MultiverseCore plugin;
private MultiverseCore plugin;
public MVPortalListener(MultiverseCore core) {
this.plugin = core;
@@ -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;
}
}
@@ -18,7 +18,7 @@ import org.bukkit.event.weather.WeatherChangeEvent;
* Multiverse's Weather {@link Listener}.
*/
public class MVWeatherListener implements Listener {
private final MultiverseCore plugin;
private MultiverseCore plugin;
public MVWeatherListener(MultiverseCore plugin) {
this.plugin = plugin;
@@ -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 {
private final 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 final MultiverseCore plugin;
private final 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());
}
}
}
}
@@ -1,37 +0,0 @@
package com.onarandombox.MultiverseCore.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
/**
* A wrapper for the {@link PlayerChatEvent}.
* @deprecated This is deprecated like the {@link PlayerChatEvent}.
*/
@Deprecated
public class NormalChatEvent implements ChatEvent {
private final PlayerChatEvent event;
public NormalChatEvent(PlayerChatEvent event) {
this.event = event;
}
@Override
public boolean isCancelled() {
return event.isCancelled();
}
@Override
public String getFormat() {
return event.getFormat();
}
@Override
public void setFormat(String s) {
event.setFormat(s);
}
@Override
public Player getPlayer() {
return event.getPlayer();
}
}
@@ -7,7 +7,6 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
@@ -17,6 +16,7 @@ import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -50,10 +50,10 @@ public class AnchorManager {
//world:x,y,z:pitch:yaw
Location anchorLocation = plugin.getLocationManipulation().stringToLocation(anchorsSection.getString(key, ""));
if (anchorLocation != null) {
Logging.config("Loading anchor: '%s'...", key);
MultiverseCore.staticLog(Level.INFO, "Loading anchor: '" + key + "'...");
this.anchors.put(key, anchorLocation);
} else {
Logging.warning("The location for anchor '%s' is INVALID.", key);
MultiverseCore.staticLog(Level.WARNING, "The location for anchor '" + key + "' is INVALID.");
}
}
@@ -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,283 @@
/******************************************************************************
* 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 org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Vehicle;
import java.util.logging.Level;
/**
* 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())) {
MultiverseCore.staticLog(Level.FINER, "Error Here (Actual)? ("
+ actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here (upOne)? ("
+ upOne.getBlock().getType() + ")[" + this.isSolidBlock(upOne.getBlock().getType()) + "]");
return false;
}
if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) {
MultiverseCore.staticLog(Level.FINER, "Error Here (downOne)? ("
+ downOne.getBlock().getType() + ")[" + this.isSolidBlock(downOne.getBlock().getType()) + "]");
return false;
}
if (downOne.getBlock().getType() == Material.FIRE) {
MultiverseCore.staticLog(Level.FINER, "There's fire below! ("
+ actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
return false;
}
if (isBlockAboveAir(actual)) {
MultiverseCore.staticLog(Level.FINER, "Is block above air [" + isBlockAboveAir(actual) + "]");
MultiverseCore.staticLog(Level.FINER, "Has 2 blocks of water below [" + 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);
}
}
@@ -7,14 +7,10 @@
package com.onarandombox.MultiverseCore.utils;
import com.onarandombox.MultiverseCore.MultiverseCoreConfiguration;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
@@ -24,13 +20,11 @@ import java.util.logging.Logger;
/**
* The Multiverse debug-logger.
* @deprecated Deprecated in favor of new Logging lib. See {@link com.dumptruckman.minecraft.util.Logging}.
*/
@Deprecated
public class DebugLog extends Logger {
public class DebugLog {
private FileHandler fh;
private Logger standardLog = null;
private String prefix = "[MVCore-Debug] ";
private Logger log;
/**
* Creates a new debug logger.
@@ -39,16 +33,16 @@ public class DebugLog extends Logger {
* @param file The file to log to.
*/
public DebugLog(String logger, String file) {
super(logger, null);
this.log = Logger.getLogger(logger);
try {
this.fh = new FileHandler(file, true);
this.setUseParentHandlers(false);
List<Handler> toRemove = Arrays.asList(this.getHandlers());
for (Handler handler : toRemove) {
this.removeHandler(handler);
this.log.setUseParentHandlers(false);
for (Handler handler : this.log.getHandlers()) {
this.log.removeHandler(handler);
}
this.addHandler(this.fh);
this.setLevel(Level.ALL);
this.log.addHandler(this.fh);
this.log.setLevel(Level.ALL);
this.fh.setFormatter(new LogFormatter());
} catch (SecurityException e) {
e.printStackTrace();
@@ -57,39 +51,14 @@ public class DebugLog extends Logger {
}
}
/**
* Sets the log-tag.
* @param tag The new tag.
*/
public void setTag(String tag) {
this.prefix = tag + " ";
}
/**
* Specifies the logger to use to send debug messages to as the debug logger itself only sends messages to a file.
*
* @param logger Logger to send debug messages to.
*/
public void setStandardLogger(Logger logger) {
this.standardLog = logger;
}
/**
* Log a message at a certain level.
*
* @param level The log-{@link Level}.
* @param msg the message.
*/
@Override
public void log(final Level level, final String msg) {
if (MultiverseCoreConfiguration.isSet() && MultiverseCoreConfiguration.getInstance().getGlobalDebug() > 0) {
// only redirect to standardLog if it's lower than INFO so we don't log that twice!
if ((level.intValue() < Level.INFO.intValue()) && (standardLog != null)) {
standardLog.log(Level.INFO, prefix + msg);
}
super.log(level, prefix + msg);
}
public void log(Level level, String msg) {
this.log.log(level, msg);
}
/**
@@ -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,7 @@
package com.onarandombox.MultiverseCore.utils;
import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
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,96 +24,17 @@ 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);
return true;
} catch (IOException e) {
Logging.warning(e.getMessage());
return false;
}
}
/**
* Used to delete the contents of a folder, without deleting the folder itself.
*
* @param file The folder whose contents to delete.
* @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);
return true;
} catch (IOException e) {
Logging.warning(e.getMessage());
return false;
}
}
/**
* 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);
}
/**
* 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
*
* @return true if it had success
*/
public static boolean copyFolder(File source, File target, List<String> excludeFiles) {
Path sourceDir = source.toPath();
Path targetDir = target.toPath();
try {
Files.walkFileTree(sourceDir, new CopyDirFileVisitor(sourceDir, targetDir, excludeFiles));
return true;
} catch (IOException e) {
Logging.warning("Unable to copy directory", e);
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);
if (file.exists()) {
boolean ret = true;
// If the file exists, and it has more than one file in it.
if (file.isDirectory()) {
for (File f : file.listFiles()) {
ret = ret && deleteFolder(f);
}
}
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;
return ret && file.delete();
} else {
return false;
}
}
}
}
@@ -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,7 +7,6 @@
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;
@@ -48,6 +47,21 @@ public class MVPermissions implements PermissionsInterface {
return p.hasPermission("mv.bypass.gamemode." + w.getName());
}
/**
* Check if a Player can ignore GameMode restrictions for world they travel to.
*
* @param p The {@link Player} to check.
* @param w The {@link MultiverseWorld} the player wants to teleport to.
* @return True if they should bypass restrictions.
*/
public boolean canIgnoreAllowFlightRestriction(Player p, MultiverseWorld w) {
if (p.hasPermission("mv.bypass.allowflight.*")) {
this.plugin.log(Level.FINER, "Player has mv.bypass.allowflight.* they can fly!");
return true;
}
return p.hasPermission("mv.bypass.allowflight." + w.getName());
}
/**
* Check if a Player can teleport to the Destination world from there current world.
*
@@ -77,10 +91,6 @@ public class MVPermissions implements PermissionsInterface {
* @return Whether the {@link CommandSender} can travel to the specified {@link Location}.
*/
public boolean canTravelFromLocation(CommandSender sender, Location location) {
// Now The Bed destination can return null now.
if (location == null) {
return false;
}
if (!(sender instanceof Player)) {
return true;
}
@@ -101,7 +111,7 @@ 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);
@@ -231,7 +241,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 +268,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,17 +7,15 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import java.util.logging.Level;
import com.fernferret.allpay.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;
import org.bukkit.permissions.Permission;
import java.util.logging.Level;
/**
* Utility-class for permissions.
*/
@@ -136,52 +134,26 @@ 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) {
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);
} else {
economist.withdraw(teleporterPlayer, price, currency);
}
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();
String errString = "You need " + bank.getFormattedAmount(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency())
+ " to send " + teleportee + " to " + toWorld.getColoredWorldString();
if (teleportee.equals(teleporter)) {
errString = "You need " + bank.getFormattedAmount(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency())
+ " to enter " + toWorld.getColoredWorldString();
}
if (!bank.hasEnough(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency(), errString)) {
return false;
} else if (pay) {
bank.give(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency());
}
}
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 +168,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()) {
@@ -258,32 +230,6 @@ public class PermissionTools {
return true;
}
/**
* Checks to see if a player can bypass the player limit.
*
* @param toWorld The world travelling to.
* @param teleporter The player that initiated the teleport.
* @param teleportee The player travelling.
* @return True if they can bypass the player limit.
*/
public boolean playerCanBypassPlayerLimit(MultiverseWorld toWorld, CommandSender teleporter, Player teleportee) {
if (teleporter == null) {
teleporter = teleportee;
}
if (!(teleporter instanceof Player)) {
return true;
}
MVPermissions perms = plugin.getMVPerms();
if (perms.hasPermission(teleportee, "mv.bypass.playerlimit." + toWorld.getName(), false)) {
return true;
} else {
teleporter.sendMessage("The world " + toWorld.getColoredWorldString() + " is full");
return false;
}
}
/**
* Checks to see if a player should bypass game mode restrictions.
*
@@ -300,4 +246,21 @@ public class PermissionTools {
return true;
}
}
/**
* Checks to see if a player should bypass allow-flight restrictions.
*
* @param toWorld world travelling to.
* @param teleportee player travelling.
* @return True if they should bypass restrictions
*/
public boolean playerCanIgnoreAllowFlightRestriction(MultiverseWorld toWorld, Player teleportee) {
if (toWorld != null) {
return this.plugin.getMVPerms().canIgnoreAllowFlightRestriction(teleportee, toWorld);
} else {
// TODO: Determine if this value is false because a world didn't exist
// or if it was because a world wasn't imported.
return true;
}
}
}
@@ -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;
}
@@ -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;
}
}
@@ -7,39 +7,23 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.BlockSafety;
import com.onarandombox.MultiverseCore.api.Core;
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 java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
/**
* The default-implementation of {@link BlockSafety}.
*/
public class SimpleBlockSafety implements BlockSafety {
private final Core plugin;
private static final Set<BlockFace> AROUND_BLOCK = EnumSet.noneOf(BlockFace.class);
static {
AROUND_BLOCK.add(BlockFace.NORTH);
AROUND_BLOCK.add(BlockFace.NORTH_EAST);
AROUND_BLOCK.add(BlockFace.EAST);
AROUND_BLOCK.add(BlockFace.SOUTH_EAST);
AROUND_BLOCK.add(BlockFace.SOUTH);
AROUND_BLOCK.add(BlockFace.SOUTH_WEST);
AROUND_BLOCK.add(BlockFace.WEST);
AROUND_BLOCK.add(BlockFace.NORTH_WEST);
}
public SimpleBlockSafety(Core plugin) {
this.plugin = plugin;
@@ -83,89 +67,33 @@ public class SimpleBlockSafety implements BlockSafety {
if (isSolidBlock(world.getBlockAt(actual).getType())
|| isSolidBlock(upOne.getBlock().getType())) {
Logging.finer("Error Here (Actual)? (%s)[%s]", actual.getBlock().getType(),
isSolidBlock(actual.getBlock().getType()));
Logging.finer("Error Here (upOne)? (%s)[%s]", upOne.getBlock().getType(),
isSolidBlock(upOne.getBlock().getType()));
MultiverseCore.staticLog(Level.FINER, "Error Here (Actual)? ("
+ actual.getBlock().getType() + ")[" + isSolidBlock(actual.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here (upOne)? ("
+ upOne.getBlock().getType() + ")[" + isSolidBlock(upOne.getBlock().getType()) + "]");
return false;
}
if (downOne.getBlock().getType() == Material.LAVA) {
Logging.finer("Error Here (downOne)? (%s)[%s]", downOne.getBlock().getType(), isSolidBlock(downOne.getBlock().getType()));
if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) {
MultiverseCore.staticLog(Level.FINER, "Error Here (downOne)? ("
+ downOne.getBlock().getType() + ")[" + isSolidBlock(downOne.getBlock().getType()) + "]");
return false;
}
if (downOne.getBlock().getType() == Material.FIRE) {
Logging.finer("There's fire below! (%s)[%s]", actual.getBlock().getType(), isSolidBlock(actual.getBlock().getType()));
MultiverseCore.staticLog(Level.FINER, "There's fire below! ("
+ actual.getBlock().getType() + ")[" + isSolidBlock(actual.getBlock().getType()) + "]");
return false;
}
if (isBlockAboveAir(actual)) {
Logging.finer("Is block above air [%s]", isBlockAboveAir(actual));
Logging.finer("Has 2 blocks of water below [%s]", this.hasTwoBlocksofWaterBelow(actual));
MultiverseCore.staticLog(Level.FINER, "Is block above air [" + isBlockAboveAir(actual) + "]");
MultiverseCore.staticLog(Level.FINER, "Has 2 blocks of water below [" + this.hasTwoBlocksofWaterBelow(actual) + "]");
return this.hasTwoBlocksofWaterBelow(actual);
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Location getSafeBedSpawn(Location l) {
// The passed location, may be null (if the bed is invalid)
if (l == null) {
return null;
}
final Location trySpawn = this.getSafeSpawnAroundABlock(l);
if (trySpawn != null) {
return trySpawn;
}
Location otherBlock = this.findOtherBedPiece(l);
if (otherBlock == null) {
return null;
}
// Now we have 2 locations, check around each, if the type is bed, skip it.
return this.getSafeSpawnAroundABlock(otherBlock);
}
/**
* Find a safe spawn around a location. (N,S,E,W,NE,NW,SE,SW)
* @param l Location to check around
* @return A safe location, or none if it wasn't found.
*/
private Location getSafeSpawnAroundABlock(Location l) {
Iterator<BlockFace> checkblock = AROUND_BLOCK.iterator();
while (checkblock.hasNext()) {
final BlockFace face = checkblock.next();
if (this.playerCanSpawnHereSafely(l.getBlock().getRelative(face).getLocation())) {
// Don't forget to center the player.
return l.getBlock().getRelative(face).getLocation().add(.5, 0, .5);
}
}
return null;
}
/**
* Find the other bed block.
* @param checkLoc The location to check for the other piece at
* @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)) {
return null;
}
Bed b = (Bed) data;
if (b.getPart() == Bed.Part.HEAD) {
return checkLoc.getBlock().getRelative(b.getFacing().getOppositeFace()).getLocation();
}
// We shouldn't ever be looking at the foot, but here's the code for it.
return checkLoc.getBlock().getRelative(b.getFacing()).getLocation();
}
/**
* {@inheritDoc}
*/
@@ -201,8 +129,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 +200,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 +215,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;
/**
@@ -53,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());
}
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more