1
0
mirror of https://github.com/essentials/Essentials.git synced 2025-09-10 06:30:45 +02:00

Compare commits

..

3 Commits

Author SHA1 Message Date
snowleo
27c84ceaac Remove the restriction of EssEcoApi to not use iConomy or BOSE 2011-06-25 15:35:47 +02:00
snowleo
d67ccd03ca Merge branch 'bukkitupdate' into release 2011-06-25 14:27:30 +02:00
snowleo
96b0f27c51 Fix for Craftbukkit Bug 912 2011-06-12 02:59:34 +02:00
642 changed files with 22313 additions and 58864 deletions

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/bukkit-0.0.1-SNAPSHOT.jar"/>
<classpathentry kind="lib" path="lib/craftbukkit-0.0.1-SNAPSHOT.jar"/>
<classpathentry kind="lib" path="lib/Permissions3.jar"/>
</classpath>

24
.gitignore vendored
View File

@@ -22,26 +22,4 @@
/EssentialsXMPP/dist/
/EssentialsXMPP/build/
/EssentialsProtect/dist/
/EssentialsProtect/build/
/EssentialsPermissionsCommands/nbproject/private/
/EssentialsPermissionsCommands/build/
/EssentialsPermissionsCommands/dist/
/Essentials/nbproject/private/
/Essentials/dist/
/Essentials/build/
/YamlAnnotations/
/EssentialsUpdate/nbproject/private/
/EssentialsRelease/
/EssentialsUpdate/dist/
/EssentialsUpdate/build/
/WebPush/apikey.php
/WebPush/nbproject/private
/.idea
*.iml
/EssentialsSigns/nbproject/private/
/Essentials2Compat/nbproject/private/
/Essentials2Compat/dist/
/Essentials2Compat/build/
/EssentialsGroupManager/bin
/EssentialsGroupManager/.externalToolBuilders
/EssentialsGeoIP/build
/EssentialsProtect/build/

View File

@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Essentials</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -20,10 +20,10 @@ is divided into following sections:
-->
<project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="BuildAll-impl">
<fail message="Please build using Ant 1.8.0 or higher.">
<fail message="Please build using Ant 1.7.1 or higher.">
<condition>
<not>
<antversion atleast="1.8.0"/>
<antversion atleast="1.7.1"/>
</not>
</condition>
</fail>
@@ -223,7 +223,6 @@ is divided into following sections:
<property name="javac.fork" value="${jdkBug6558476}"/>
<property name="jar.index" value="false"/>
<property name="jar.index.metainf" value="${jar.index}"/>
<property name="copylibs.rebase" value="true"/>
<available file="${meta.inf.dir}/persistence.xml" property="has.persistence.xml"/>
</target>
<target name="-post-init">
@@ -410,7 +409,6 @@ is divided into following sections:
<property environment="env"/>
<resolve name="profiler.current.path" value="${profiler.info.pathvar}"/>
<java classname="@{classname}" dir="${profiler.info.dir}" fork="true" jvm="${profiler.info.jvm}">
<jvmarg line="${endorsed.classpath.cmd.line.arg}"/>
<jvmarg value="${profiler.info.jvmargs.agent}"/>
<jvmarg line="${profiler.info.jvmargs}"/>
<env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/>
@@ -541,7 +539,7 @@ is divided into following sections:
</chainedmapper>
</pathconvert>
<taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/>
<copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}">
<copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" runtimeclasspath="${run.classpath.without.build.classes.dir}">
<fileset dir="${build.classes.dir}"/>
<manifest>
<attribute name="Class-Path" value="${jar.classpath}"/>
@@ -652,13 +650,6 @@ is divided into following sections:
<param name="call.target" value="jar"/>
<param name="transfer.built-jar.properties" value="${built-jar.properties}"/>
</antcall>
<antcall target="-maybe-call-dep">
<param name="call.built.properties" value="${built-jar.properties}"/>
<param location="${project.EssentialsXMPP}" name="call.subproject"/>
<param location="${project.EssentialsXMPP}/build.xml" name="call.script"/>
<param name="call.target" value="jar"/>
<param name="transfer.built-jar.properties" value="${built-jar.properties}"/>
</antcall>
</target>
<target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/>
<target depends="init" name="-check-automatic-build">
@@ -922,26 +913,16 @@ is divided into following sections:
-->
<target depends="init" if="have.sources" name="-javadoc-build">
<mkdir dir="${dist.javadoc.dir}"/>
<condition else="" property="javadoc.endorsed.classpath.cmd.line.arg" value="-J${endorsed.classpath.cmd.line.arg}">
<and>
<isset property="endorsed.classpath.cmd.line.arg"/>
<not>
<equals arg1="${endorsed.classpath.cmd.line.arg}" arg2=""/>
</not>
</and>
</condition>
<javadoc additionalparam="${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}">
<classpath>
<path path="${javac.classpath}"/>
</classpath>
<fileset dir="${src.dir}" excludes="*.java,${excludes}" includes="${includes}">
<fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}">
<filename name="**/*.java"/>
</fileset>
<fileset dir="${build.generated.sources.dir}" erroronmissingdir="false">
<include name="**/*.java"/>
<exclude name="*.java"/>
</fileset>
<arg line="${javadoc.endorsed.classpath.cmd.line.arg}"/>
</javadoc>
<copy todir="${dist.javadoc.dir}">
<fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}">
@@ -1154,13 +1135,6 @@ is divided into following sections:
<param name="call.target" value="clean"/>
<param name="transfer.built-clean.properties" value="${built-clean.properties}"/>
</antcall>
<antcall target="-maybe-call-dep">
<param name="call.built.properties" value="${built-clean.properties}"/>
<param location="${project.EssentialsXMPP}" name="call.subproject"/>
<param location="${project.EssentialsXMPP}/build.xml" name="call.script"/>
<param name="call.target" value="clean"/>
<param name="transfer.built-clean.properties" value="${built-clean.properties}"/>
</antcall>
</target>
<target depends="init" name="-do-clean">
<delete dir="${build.dir}"/>

View File

@@ -1,8 +1,8 @@
build.xml.data.CRC32=51b33957
build.xml.data.CRC32=c4188209
build.xml.script.CRC32=7a797370
build.xml.stylesheet.CRC32=28e38971@1.44.1.45
build.xml.stylesheet.CRC32=28e38971@1.43.1.45
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=51b33957
nbproject/build-impl.xml.script.CRC32=c5170bed
nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.1.46
nbproject/build-impl.xml.data.CRC32=c4188209
nbproject/build-impl.xml.script.CRC32=73a4865f
nbproject/build-impl.xml.stylesheet.CRC32=0c01fd8e@1.43.1.45

View File

@@ -3,42 +3,7 @@ annotation.processing.enabled.in.editor=false
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=BuildAll
application.vendor=
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=120
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAnnotationArgs=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineArrayInit=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAssignment=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineBinaryOp=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineCallArgs=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineDisjunctiveCatchTypes=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineFor=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineImplements=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineMethodParams=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineParenthesized=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTernaryOp=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineThrows=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTryResources=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesBeforeClass=2
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.classDeclBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width=4
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.methodDeclBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.otherBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeCatchOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeElseOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeFinallyOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeWhileOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab=4
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size=4
application.vendor=Paul
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
@@ -62,26 +27,27 @@ dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
includes=**
jar.compress=true
jar.compress=false
javac.classpath=\
${reference.Essentials.jar}:\
${reference.EssentialsChat.jar}:\
${reference.EssentialsGroupBridge.jar}:\
${reference.EssentialsGroupManager.jar}:\
${reference.EssentialsProtect.jar}:\
${reference.EssentialsSpawn.jar}:\
${reference.EssentialsGeoIP.jar}:\
${reference.EssentialsGroupBridge.jar}:\
${reference.EssentialsXMPP.jar}:\
${reference.EssentialsGroupManager.jar}
${reference.EssentialsGeoIP.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.source=1.5
javac.target=1.5
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
${build.classes.dir}:\
${libs.junit.classpath}:\
${libs.junit_4.classpath}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
@@ -105,7 +71,6 @@ project.EssentialsGroupBridge=../EssentialsGroupBridge
project.EssentialsGroupManager=../EssentialsGroupManager
project.EssentialsProtect=../EssentialsProtect
project.EssentialsSpawn=../EssentialsSpawn
project.EssentialsXMPP=../EssentialsXMPP
reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar
reference.EssentialsChat.jar=${project.EssentialsChat}/dist/EssentialsChat.jar
reference.EssentialsGeoIP.jar=${project.EssentialsGeoIP}/dist/EssentialsGeoIP.jar
@@ -113,7 +78,6 @@ reference.EssentialsGroupBridge.jar=${project.EssentialsGroupBridge}/dist/Essent
reference.EssentialsGroupManager.jar=${project.EssentialsGroupManager}/dist/EssentialsGroupManager.jar
reference.EssentialsProtect.jar=${project.EssentialsProtect}/dist/EssentialsProtect.jar
reference.EssentialsSpawn.jar=${project.EssentialsSpawn}/dist/EssentialsSpawn.jar
reference.EssentialsXMPP.jar=${project.EssentialsXMPP}/dist/EssentialsXMPP.jar
run.classpath=\
${javac.classpath}:\
${build.classes.dir}

View File

@@ -71,14 +71,6 @@
<clean-target>clean</clean-target>
<id>jar</id>
</reference>
<reference>
<foreign-project>EssentialsXMPP</foreign-project>
<artifact-type>jar</artifact-type>
<script>build.xml</script>
<target>jar</target>
<clean-target>clean</clean-target>
<id>jar</id>
</reference>
</references>
</configuration>
</project>

7
Essentials/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
# NetBeans cruft
/build
/dist
/nbproject/private
# Mac cruft
.DS_Store

View File

@@ -1,84 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="Essentials" default="default" basedir=".">
<description>Builds, tests, and runs the project Essentials.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="Essentials-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
<!--target name="-post-jar">
<jar jarfile="${dist.dir}/Essentials.jar">
<zipfileset src="${dist.jar}" excludes="META-INF/*" />
<zipfileset src="${dist.dir}/lib/Register.jar" excludes="META-INF/*" />
<manifest>
<attribute name="Classpath" value="Essentials.jar"/>
</manifest>
</jar>
</target-->
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="Essentials" default="default" basedir=".">
<description>Builds, tests, and runs the project Essentials.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="Essentials-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
<!--target name="-post-jar">
<jar jarfile="${dist.dir}/Essentials.jar">
<zipfileset src="${dist.jar}" excludes="META-INF/*" />
<zipfileset src="${dist.dir}/lib/Register.jar" excludes="META-INF/*" />
<manifest>
<attribute name="Classpath" value="Essentials.jar"/>
</manifest>
</jar>
</target-->
</project>

View File

@@ -20,10 +20,10 @@ is divided into following sections:
-->
<project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="Essentials-impl">
<fail message="Please build using Ant 1.8.0 or higher.">
<fail message="Please build using Ant 1.7.1 or higher.">
<condition>
<not>
<antversion atleast="1.8.0"/>
<antversion atleast="1.7.1"/>
</not>
</condition>
</fail>
@@ -223,7 +223,6 @@ is divided into following sections:
<property name="javac.fork" value="${jdkBug6558476}"/>
<property name="jar.index" value="false"/>
<property name="jar.index.metainf" value="${jar.index}"/>
<property name="copylibs.rebase" value="true"/>
<available file="${meta.inf.dir}/persistence.xml" property="has.persistence.xml"/>
</target>
<target name="-post-init">
@@ -410,7 +409,6 @@ is divided into following sections:
<property environment="env"/>
<resolve name="profiler.current.path" value="${profiler.info.pathvar}"/>
<java classname="@{classname}" dir="${profiler.info.dir}" fork="true" jvm="${profiler.info.jvm}">
<jvmarg line="${endorsed.classpath.cmd.line.arg}"/>
<jvmarg value="${profiler.info.jvmargs.agent}"/>
<jvmarg line="${profiler.info.jvmargs}"/>
<env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/>
@@ -541,7 +539,7 @@ is divided into following sections:
</chainedmapper>
</pathconvert>
<taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/>
<copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}">
<copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" runtimeclasspath="${run.classpath.without.build.classes.dir}">
<fileset dir="${build.classes.dir}"/>
<manifest>
<attribute name="Class-Path" value="${jar.classpath}"/>
@@ -603,13 +601,6 @@ is divided into following sections:
<propertyfile file="${built-jar.properties}">
<entry key="${basedir}" value=""/>
</propertyfile>
<antcall target="-maybe-call-dep">
<param name="call.built.properties" value="${built-jar.properties}"/>
<param location="${project.EssentialsGroupManager}" name="call.subproject"/>
<param location="${project.EssentialsGroupManager}/build.xml" name="call.script"/>
<param name="call.target" value="jar"/>
<param name="transfer.built-jar.properties" value="${built-jar.properties}"/>
</antcall>
</target>
<target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/>
<target depends="init" name="-check-automatic-build">
@@ -873,26 +864,16 @@ is divided into following sections:
-->
<target depends="init" if="have.sources" name="-javadoc-build">
<mkdir dir="${dist.javadoc.dir}"/>
<condition else="" property="javadoc.endorsed.classpath.cmd.line.arg" value="-J${endorsed.classpath.cmd.line.arg}">
<and>
<isset property="endorsed.classpath.cmd.line.arg"/>
<not>
<equals arg1="${endorsed.classpath.cmd.line.arg}" arg2=""/>
</not>
</and>
</condition>
<javadoc additionalparam="${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}">
<classpath>
<path path="${javac.classpath}"/>
</classpath>
<fileset dir="${src.dir}" excludes="*.java,${excludes}" includes="${includes}">
<fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}">
<filename name="**/*.java"/>
</fileset>
<fileset dir="${build.generated.sources.dir}" erroronmissingdir="false">
<include name="**/*.java"/>
<exclude name="*.java"/>
</fileset>
<arg line="${javadoc.endorsed.classpath.cmd.line.arg}"/>
</javadoc>
<copy todir="${dist.javadoc.dir}">
<fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}">
@@ -1056,13 +1037,6 @@ is divided into following sections:
<propertyfile file="${built-clean.properties}">
<entry key="${basedir}" value=""/>
</propertyfile>
<antcall target="-maybe-call-dep">
<param name="call.built.properties" value="${built-clean.properties}"/>
<param location="${project.EssentialsGroupManager}" name="call.subproject"/>
<param location="${project.EssentialsGroupManager}/build.xml" name="call.script"/>
<param name="call.target" value="clean"/>
<param name="transfer.built-clean.properties" value="${built-clean.properties}"/>
</antcall>
</target>
<target depends="init" name="-do-clean">
<delete dir="${build.dir}"/>

View File

@@ -3,9 +3,9 @@ build.xml.script.CRC32=3233ee78
build.xml.stylesheet.CRC32=28e38971@1.38.2.45
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=a830bc14
nbproject/build-impl.xml.script.CRC32=a9f8842a
nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.1.46
nbproject/build-impl.xml.data.CRC32=4b596d89
nbproject/build-impl.xml.script.CRC32=4926001b
nbproject/build-impl.xml.stylesheet.CRC32=0c01fd8e@1.43.1.45
nbproject/profiler-build-impl.xml.data.CRC32=ab78ce15
nbproject/profiler-build-impl.xml.script.CRC32=abda56ed
nbproject/profiler-build-impl.xml.stylesheet.CRC32=f10cf54c@1.11.1

View File

@@ -1,3 +1 @@
DoNotUseThreads
LongVariable
SignatureDeclareThrowsException

View File

@@ -1,47 +1,9 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=lombok.core.AnnotationProcessor
annotation.processing.run.all.processors=false
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=Essentials
application.vendor=
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=2
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=120
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAnnotationArgs=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineArrayInit=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineAssignment=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineBinaryOp=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineCallArgs=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineDisjunctiveCatchTypes=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineFor=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineImplements=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineMethodParams=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineParenthesized=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTernaryOp=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineThrows=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.alignMultilineTryResources=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesBeforeClass=2
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.classDeclBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder=*
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width=4
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.methodDeclBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.otherBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeCatchOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeElseOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeFinallyOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeWhileOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.separateImportGroups=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab=4
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size=4
application.vendor=Paul
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
@@ -64,53 +26,31 @@ dist.jar=${dist.dir}/Essentials.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
file.reference.BOSEconomy7.jar=../lib/BOSEconomy7.jar
file.reference.bPermissions.jar=../lib/bPermissions.jar
file.reference.bpermissions2.jar=../lib/bpermissions2.jar
file.reference.bukkit.jar=../lib/bukkit.jar
file.reference.craftbukkit.jar=../lib/craftbukkit.jar
file.reference.BOSEconomy.jar=../lib/BOSEconomy.jar
file.reference.craftbukkit-0.0.1-SNAPSHOT.jar=..\\lib\\craftbukkit-0.0.1-SNAPSHOT.jar
file.reference.iCo4.jar=../lib/iCo4.jar
file.reference.iCo5.jar=../lib/iCo5.jar
file.reference.iCo6.jar=../lib/iCo6.jar
file.reference.lombok.jar=../lib/lombok-0.10.8.jar
file.reference.MultiCurrency.jar=../lib/MultiCurrency.jar
file.reference.Permissions3.jar=../lib/Permissions3.jar
file.reference.PermissionsBukkit-1.2.jar=../lib/PermissionsBukkit-1.2.jar
file.reference.PermissionsEx.jar=../lib/PermissionsEx.jar
file.reference.Privileges.jar=..\\lib\\Privileges.jar
file.reference.Vault.jar=../lib/Vault.jar
file.reference.junit-4.5.jar=..\\lib\\junit_4\\junit-4.5.jar
file.reference.Permissions.jar=..\\lib\\Permissions.jar
includes=**
jar.archive.disabled=${jnlp.enabled}
jar.compress=true
jar.index=${jnlp.enabled}
jar.compress=false
javac.classpath=\
${file.reference.Permissions3.jar}:\
${file.reference.Permissions.jar}:\
${file.reference.craftbukkit-0.0.1-SNAPSHOT.jar}:\
${file.reference.BOSEconomy.jar}:\
${file.reference.iCo4.jar}:\
${file.reference.iCo5.jar}:\
${file.reference.iCo6.jar}:\
${file.reference.MultiCurrency.jar}:\
${file.reference.BOSEconomy7.jar}:\
${file.reference.PermissionsEx.jar}:\
${file.reference.bPermissions.jar}:\
${file.reference.PermissionsBukkit-1.2.jar}:\
${file.reference.lombok.jar}:\
${reference.EssentialsGroupManager.jar}:\
${file.reference.bukkit.jar}:\
${file.reference.craftbukkit.jar}:\
${file.reference.Vault.jar}:\
${file.reference.Privileges.jar}:\
${file.reference.bpermissions2.jar}
${file.reference.iCo5.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.source=1.5
javac.target=1.5
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}:\
${libs.junit_4.10.classpath}
${file.reference.junit-4.5.jar}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
@@ -120,25 +60,13 @@ javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.reference.PermissionsEx.jar=../lib/PermissionsEx-javadoc.jar
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=Essentials Docs.
jnlp.codebase.type=no.codebase
jnlp.descriptor=application
jnlp.enabled=false
jnlp.mixed.code=default
jnlp.offline-allowed=false
jnlp.signed=false
jnlp.signing=
jnlp.signing.alias=
jnlp.signing.keystore=
javadoc.windowtitle=
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=true
mkdist.disabled=false
platform.active=default_platform
project.EssentialsGroupManager=../EssentialsGroupManager
reference.EssentialsGroupManager.jar=../EssentialsGroupManager/dist/EssentialsGroupManager.jar
run.classpath=\
${javac.classpath}:\
${build.classes.dir}

View File

@@ -14,15 +14,6 @@
<libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1">
<definitions>../lib/nblibraries.properties</definitions>
</libraries>
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1">
<reference>
<foreign-project>EssentialsGroupManager</foreign-project>
<artifact-type>jar</artifact-type>
<script>build.xml</script>
<target>jar</target>
<clean-target>clean</clean-target>
<id>jar</id>
</reference>
</references>
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1"/>
</configuration>
</project>

View File

@@ -1,153 +1,84 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IBackup;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.ISettings;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import lombok.Cleanup;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer;
public class Backup implements Runnable {
private static final Logger logger = Logger.getLogger("Minecraft");
private final CraftServer server;
private final IEssentials ess;
private boolean running = false;
private int taskId = -1;
private boolean active = false;
public class Backup implements Runnable, IBackup
{
private static final Logger LOGGER = Bukkit.getLogger();
private transient final Server server;
private transient final IEssentials ess;
private transient final AtomicBoolean running = new AtomicBoolean(false);
private transient int taskId = -1;
private transient final AtomicBoolean active = new AtomicBoolean(false);
public Backup(final IEssentials ess)
{
public Backup(IEssentials ess) {
this.ess = ess;
server = ess.getServer();
if (server.getOnlinePlayers().length > 0)
{
server = (CraftServer)ess.getServer();
if (server.getOnlinePlayers().length > 0) {
startTask();
}
}
}
@Override
public final void startTask()
{
if (running.compareAndSet(false, true))
{
@Cleanup
final ISettings settings = ess.getSettings();
settings.acquireReadLock();
final long interval = settings.getData().getGeneral().getBackup().getInterval() * 1200; // minutes -> ticks
if (interval < 1200)
{
running.set(false);
void onPlayerJoin() {
startTask();
}
private void startTask() {
if (!running) {
long interval = ess.getSettings().getBackupInterval()*1200; // minutes -> ticks
if (interval < 1200) {
return;
}
taskId = ess.scheduleSyncRepeatingTask(this, interval, interval);
running = true;
}
}
@Override
public void run()
{
if (!active.compareAndSet(false, true))
{
public void run() {
if (active) return;
active = true;
final String command = ess.getSettings().getBackupCommand();
if (command == null || "".equals(command)) {
return;
}
@Cleanup
final ISettings settings = ess.getSettings();
settings.acquireReadLock();
final String command = settings.getData().getGeneral().getBackup().getCommand();
if (command == null || command.isEmpty())
{
return;
}
LOGGER.log(Level.INFO, _("backupStarted"));
final CommandSender consoleSender = server.getConsoleSender();
server.dispatchCommand(consoleSender, "save-all");
server.dispatchCommand(consoleSender, "save-off");
logger.log(Level.INFO, Util.i18n("backupStarted"));
final CommandSender cs = server.getServer().console;
server.dispatchCommand(cs, "save-all");
server.dispatchCommand(cs, "save-off");
ess.scheduleAsyncDelayedTask(
new Runnable() {
ess.scheduleAsyncDelayedTask(new BackupRunner(command));
}
private class BackupRunner implements Runnable
{
private final transient String command;
public BackupRunner(final String command)
{
this.command = command;
}
@Override
public void run()
{
try
{
final ProcessBuilder childBuilder = new ProcessBuilder(command);
childBuilder.redirectErrorStream(true);
childBuilder.directory(ess.getDataFolder().getParentFile().getParentFile());
final Process child = childBuilder.start();
final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream()));
try
{
public void run() {
try {
Process child = Runtime.getRuntime().exec(command);
child.waitFor();
String line;
do
{
line = reader.readLine();
if (line != null)
{
LOGGER.log(Level.INFO, line);
} catch (InterruptedException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
} finally {
ess.scheduleSyncDelayedTask(
new Runnable() {
public void run() {
server.dispatchCommand(cs, "save-on");
if (server.getOnlinePlayers().length == 0) {
running = false;
if (taskId != -1) {
server.getScheduler().cancelTask(taskId);
}
}
active = false;
logger.log(Level.INFO, Util.i18n("backupFinished"));
}
}
while (line != null);
}
finally
{
reader.close();
});
}
}
catch (InterruptedException ex)
{
LOGGER.log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, null, ex);
}
finally
{
ess.scheduleSyncDelayedTask(new EnableSavingRunner());
}
}
});
}
private class EnableSavingRunner implements Runnable
{
@Override
public void run()
{
server.dispatchCommand(server.getConsoleSender(), "save-on");
if (server.getOnlinePlayers().length == 0)
{
running.set(false);
if (taskId != -1)
{
server.getScheduler().cancelTask(taskId);
}
}
active.set(false);
LOGGER.log(Level.INFO, _("backupFinished"));
}
}
}

View File

@@ -0,0 +1,104 @@
package com.earth2me.essentials;
import org.bukkit.inventory.ItemStack;
public class Charge
{
private final String command;
private final Double costs;
private final ItemStack items;
private final IEssentials ess;
public Charge(String command, IEssentials ess)
{
this(command, null, null, ess);
}
public Charge(double money, IEssentials ess)
{
this(null, money, null, ess);
}
public Charge(ItemStack items, IEssentials ess)
{
this(null, null, items, ess);
}
private Charge(String command, Double money, ItemStack item, IEssentials ess)
{
this.command = command;
this.costs = money;
this.items = item;
this.ess = ess;
}
public void isAffordableFor(IUser user) throws Exception
{
double mon = user.getMoney();
if (costs != null)
{
if (mon < costs && !user.isAuthorized("essentials.eco.loan"))
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
}
if (items != null)
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, items))
{
throw new Exception(Util.format("missingItems", items.getAmount(), items.getType().toString().toLowerCase().replace("_", " ")));
}
}
if (command != null && !command.isEmpty())
{
if (user.isAuthorized("essentials.nocommandcost.all")
|| user.isAuthorized("essentials.nocommandcost." + command))
{
return;
}
double cost = ess.getSettings().getCommandCost(command.startsWith("/") ? command.substring(1) : command);
if (mon < cost && !user.isAuthorized("essentials.eco.loan"))
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
}
}
public void charge(IUser user) throws Exception
{
double mon = user.getMoney();
if (costs != null)
{
if (mon < costs && !user.isAuthorized("essentials.eco.loan"))
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
user.takeMoney(costs);
}
if (items != null)
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, items))
{
throw new Exception(Util.format("missingItems", items.getAmount(), items.getType().toString().toLowerCase().replace("_", " ")));
}
InventoryWorkaround.removeItem(user.getInventory(), true, items);
user.updateInventory();
}
if (command != null && !command.isEmpty())
{
if (user.isAuthorized("essentials.nocommandcost.all")
|| user.isAuthorized("essentials.nocommandcost." + command))
{
return;
}
double cost = ess.getSettings().getCommandCost(command.startsWith("/") ? command.substring(1) : command);
if (mon < cost && !user.isAuthorized("essentials.eco.loan"))
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
user.takeMoney(cost);
}
}
}

View File

@@ -1,33 +1,34 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IReplyTo;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer;
public final class Console implements IReplyTo
{
public final class Console implements IReplyTo {
private static Console instance = new Console();
private CommandSender replyTo;
public final static String NAME = "Console";
private Console()
{
private Console() {
}
public static CommandSender getCommandSender(Server server) throws Exception {
if (! (server instanceof CraftServer)) {
throw new Exception(Util.i18n("invalidServer"));
}
return ((CraftServer)server).getServer().console;
}
@Override
public void setReplyTo(final CommandSender user)
{
public void setReplyTo(CommandSender user) {
replyTo = user;
}
@Override
public CommandSender getReplyTo()
{
public CommandSender getReplyTo() {
return replyTo;
}
public static Console getConsoleReplyTo()
{
public static Console getConsoleReplyTo() {
return instance;
}
}

View File

@@ -1,295 +0,0 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* This utility class is used for converting between the ingame
* time in ticks to ingame time as a friendly string.
* Note that the time is INGAME.
*
* http://www.minecraftwiki.net/wiki/Day/night_cycle
*
* @author Olof Larsson
*/
public final class DescParseTickFormat
{
public static final Map<String, Integer> nameToTicks = new LinkedHashMap<String, Integer>();
public static final Set<String> resetAliases = new HashSet<String>();
public static final int ticksAtMidnight = 18000;
public static final int ticksPerDay = 24000;
public static final int ticksPerHour = 1000;
public static final double ticksPerMinute = 1000d / 60d;
public static final double ticksPerSecond = 1000d / 60d / 60d;
private static final SimpleDateFormat SDFTwentyFour = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
private static final SimpleDateFormat SDFTwelve = new SimpleDateFormat("h:mmaa", Locale.ENGLISH);
static
{
SDFTwentyFour.setTimeZone(TimeZone.getTimeZone("GMT"));
SDFTwelve.setTimeZone(TimeZone.getTimeZone("GMT"));
nameToTicks.put("sunrise", 23000);
nameToTicks.put("dawn", 23000);
nameToTicks.put("daystart", 0);
nameToTicks.put("day", 0);
nameToTicks.put("morning", 1000);
nameToTicks.put("midday", 6000);
nameToTicks.put("noon", 6000);
nameToTicks.put("afternoon", 9000);
nameToTicks.put("sunset", 12000);
nameToTicks.put("dusk", 12000);
nameToTicks.put("sundown", 12000);
nameToTicks.put("nightfall", 12000);
nameToTicks.put("nightstart", 14000);
nameToTicks.put("night", 14000);
nameToTicks.put("midnight", 18000);
resetAliases.add("reset");
resetAliases.add("normal");
resetAliases.add("default");
}
private DescParseTickFormat()
{
}
// ============================================
// PARSE. From describing String to int
// --------------------------------------------
public static long parse(String desc) throws NumberFormatException
{
// Only look at alphanumeric and lowercase and : for 24:00
desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^A-Za-z0-9:]", "");
// Detect ticks format
try
{
return parseTicks(desc);
}
catch (Exception e)
{
}
// Detect 24-hour format
try
{
return parse24(desc);
}
catch (Exception e)
{
}
// Detect 12-hour format
try
{
return parse12(desc);
}
catch (Exception e)
{
}
// Detect aliases
try
{
return parseAlias(desc);
}
catch (Exception e)
{
}
// Well we failed to understand...
throw new NumberFormatException();
}
public static long parseTicks(String desc) throws NumberFormatException
{
if (!desc.matches("^[0-9]+ti?c?k?s?$"))
{
throw new NumberFormatException();
}
desc = desc.replaceAll("[^0-9]", "");
return Long.parseLong(desc) % 24000;
}
public static long parse24(String desc) throws NumberFormatException
{
if (!desc.matches("^[0-9]{2}[^0-9]?[0-9]{2}$"))
{
throw new NumberFormatException();
}
desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", "");
if (desc.length() != 4)
{
throw new NumberFormatException();
}
final int hours = Integer.parseInt(desc.substring(0, 2));
final int minutes = Integer.parseInt(desc.substring(2, 4));
return hoursMinutesToTicks(hours, minutes);
}
public static long parse12(String desc) throws NumberFormatException
{
if (!desc.matches("^[0-9]{1,2}([^0-9]?[0-9]{2})?(pm|am)$"))
{
throw new NumberFormatException();
}
int hours = 0;
int minutes = 0;
desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", "");
if (desc.length() > 4)
{
throw new NumberFormatException();
}
if (desc.length() == 4)
{
hours += Integer.parseInt(desc.substring(0, 2));
minutes += Integer.parseInt(desc.substring(2, 4));
}
else if (desc.length() == 3)
{
hours += Integer.parseInt(desc.substring(0, 1));
minutes += Integer.parseInt(desc.substring(1, 3));
}
else if (desc.length() == 2)
{
hours += Integer.parseInt(desc.substring(0, 2));
}
else if (desc.length() == 1)
{
hours += Integer.parseInt(desc.substring(0, 1));
}
else
{
throw new NumberFormatException();
}
if (desc.endsWith("pm") && hours != 12)
{
hours += 12;
}
if (desc.endsWith("am") && hours == 12)
{
hours -= 12;
}
return hoursMinutesToTicks(hours, minutes);
}
public static long hoursMinutesToTicks(final int hours, final int minutes)
{
long ret = ticksAtMidnight;
ret += (hours) * ticksPerHour;
ret += (minutes / 60.0) * ticksPerHour;
ret %= ticksPerDay;
return ret;
}
public static long parseAlias(final String desc) throws NumberFormatException
{
final Integer ret = nameToTicks.get(desc);
if (ret == null)
{
throw new NumberFormatException();
}
return ret;
}
public static boolean meansReset(final String desc)
{
return resetAliases.contains(desc);
}
// ============================================
// FORMAT. From int to describing String
// --------------------------------------------
public static String format(final long ticks)
{
return _("timeFormat", format24(ticks), format12(ticks), formatTicks(ticks));
}
public static String formatTicks(final long ticks)
{
return (ticks % ticksPerDay) + "ticks";
}
public static String format24(final long ticks)
{
synchronized (SDFTwentyFour)
{
return formatDateFormat(ticks, SDFTwentyFour);
}
}
public static String format12(final long ticks)
{
synchronized (SDFTwelve)
{
return formatDateFormat(ticks, SDFTwelve);
}
}
public static String formatDateFormat(final long ticks, final SimpleDateFormat format)
{
final Date date = ticksToDate(ticks);
return format.format(date);
}
public static Date ticksToDate(long ticks)
{
// Assume the server time starts at 0. It would start on a day.
// But we will simulate that the server started with 0 at midnight.
ticks = ticks - ticksAtMidnight + ticksPerDay;
// How many ingame days have passed since the server start?
final long days = ticks / ticksPerDay;
ticks = ticks - days * ticksPerDay;
// How many hours on the last day?
final long hours = ticks / ticksPerHour;
ticks = ticks - hours * ticksPerHour;
// How many minutes on the last day?
final long minutes = (long)Math.floor(ticks / ticksPerMinute);
final double dticks = ticks - minutes * ticksPerMinute;
// How many seconds on the last day?
final long seconds = (long)Math.floor(dticks / ticksPerSecond);
// Now we create an english GMT calendar (We wan't no daylight savings)
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH);
cal.setLenient(true);
// And we set the time to 0! And append the time that passed!
cal.set(0, Calendar.JANUARY, 1, 0, 0, 0);
cal.add(Calendar.DAY_OF_YEAR, (int)days);
cal.add(Calendar.HOUR_OF_DAY, (int)hours);
cal.add(Calendar.MINUTE, (int)minutes);
cal.add(Calendar.SECOND, (int)seconds + 1); // To solve rounding errors.
return cal.getTime();
}
}

View File

@@ -1,207 +0,0 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.*;
import com.earth2me.essentials.perm.Permissions;
import com.earth2me.essentials.settings.MoneyHolder;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class Economy implements IEconomy
{
private final IEssentials ess;
private final MoneyHolder npcs;
public Economy(IEssentials ess)
{
this.ess = ess;
this.npcs = new MoneyHolder(ess);
}
private double getNPCBalance(String name) throws UserDoesNotExistException
{
npcs.acquireReadLock();
try
{
Map<String, Double> balances = npcs.getData().getBalances();
if (balances == null)
{
throw new UserDoesNotExistException(name);
}
Double balance = npcs.getData().getBalances().get(name.toLowerCase(Locale.ENGLISH));
if (balance == null)
{
throw new UserDoesNotExistException(name);
}
return balance;
}
finally
{
npcs.unlock();
}
}
private void setNPCBalance(String name, double balance, boolean checkExistance) throws UserDoesNotExistException
{
npcs.acquireWriteLock();
try
{
Map<String, Double> balances = npcs.getData().getBalances();
if (balances == null)
{
balances = new HashMap<String, Double>();
npcs.getData().setBalances(balances);
}
if (checkExistance && !balances.containsKey(name.toLowerCase(Locale.ENGLISH)))
{
throw new UserDoesNotExistException(name);
}
balances.put(name.toLowerCase(Locale.ENGLISH), balance);
}
finally
{
npcs.unlock();
}
}
private double getStartingBalance()
{
double startingBalance = 0;
ISettings settings = ess.getSettings();
settings.acquireReadLock();
try
{
startingBalance = settings.getData().getEconomy().getStartingBalance();
}
finally
{
settings.unlock();
}
return startingBalance;
}
@Override
public void onReload()
{
this.npcs.onReload(false);
}
@Override
public double getMoney(String name) throws UserDoesNotExistException
{
IUser user = ess.getUser(name);
if (user == null)
{
return getNPCBalance(name);
}
return user.getMoney();
}
@Override
public void setMoney(String name, double balance) throws NoLoanPermittedException, UserDoesNotExistException
{
IUser user = ess.getUser(name);
if (user == null)
{
setNPCBalance(name, balance, true);
return;
}
if (balance < 0.0 && !Permissions.ECO_LOAN.isAuthorized(user))
{
throw new NoLoanPermittedException();
}
user.setMoney(balance);
}
@Override
public void resetBalance(String name) throws NoLoanPermittedException, UserDoesNotExistException
{
setMoney(name, getStartingBalance());
}
@Override
public String format(double amount)
{
return Util.formatCurrency(amount, ess);
}
@Override
public boolean playerExists(String name)
{
try
{
getMoney(name);
return true;
}
catch (UserDoesNotExistException ex)
{
return false;
}
}
@Override
public boolean isNPC(String name) throws UserDoesNotExistException
{
boolean result = ess.getUser(name) == null;
if (result)
{
getNPCBalance(name);
}
return result;
}
@Override
public boolean createNPC(String name)
{
try
{
if (isNPC(name))
{
setNPCBalance(name, getStartingBalance(), false);
return true;
}
}
catch (UserDoesNotExistException ex)
{
try
{
setNPCBalance(name, getStartingBalance(), false);
return true;
}
catch (UserDoesNotExistException ex1)
{
//This should never happen!
}
}
return false;
}
@Override
public void removeNPC(String name) throws UserDoesNotExistException
{
npcs.acquireWriteLock();
try
{
Map<String, Double> balances = npcs.getData().getBalances();
if (balances == null)
{
balances = new HashMap<String, Double>();
npcs.getData().setBalances(balances);
}
if (balances.containsKey(name.toLowerCase(Locale.ENGLISH)))
{
balances.remove(name.toLowerCase(Locale.ENGLISH));
}
else
{
throw new UserDoesNotExistException(name);
}
}
finally
{
npcs.unlock();
}
}
}

View File

@@ -1,88 +0,0 @@
package com.earth2me.essentials;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import org.bukkit.enchantments.Enchantment;
public final class Enchantments
{
private Enchantments()
{
}
private static final transient Pattern NUMPATTERN = Pattern.compile("\\d+");
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>();
static
{
ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD);
ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD);
ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED);
ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED);
ENCHANTMENTS.put("durability", Enchantment.DURABILITY);
ENCHANTMENTS.put("dura", Enchantment.DURABILITY);
ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY);
ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT);
ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT);
ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK);
ENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS);
ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS);
ENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("oxygen", Enchantment.OXYGEN);
ENCHANTMENTS.put("respiration", Enchantment.OXYGEN);
ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL);
ENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL);
ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE);
ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE);
ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE);
ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE);
ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH);
ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER);
ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER);
ENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE);
ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE);
ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK);
ENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK);
ENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE);
ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE);
}
public static Enchantment getByName(final String name) {
Enchantment enchantment;
if (NUMPATTERN.matcher(name).matches()) {
enchantment = Enchantment.getById(Integer.parseInt(name));
} else {
enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH));
}
if (enchantment == null)
{
enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH));
}
return enchantment;
}
public static Set<Entry<String, Enchantment>> entrySet()
{
return ENCHANTMENTS.entrySet();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,388 @@
package com.earth2me.essentials;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.block.CraftSign;
import org.bukkit.event.block.*;
import org.bukkit.inventory.ItemStack;
public class EssentialsBlockListener extends BlockListener
{
private final IEssentials ess;
private static final Logger logger = Logger.getLogger("Minecraft");
public final static List<Material> protectedBlocks = new ArrayList<Material>(4);
static
{
protectedBlocks.add(Material.CHEST);
protectedBlocks.add(Material.BURNING_FURNACE);
protectedBlocks.add(Material.FURNACE);
protectedBlocks.add(Material.DISPENSER);
}
public EssentialsBlockListener(IEssentials ess)
{
this.ess = ess;
}
@Override
public void onBlockBreak(BlockBreakEvent event)
{
if (event.isCancelled()) return;
if (ess.getSettings().areSignsDisabled()) return;
User user = ess.getUser(event.getPlayer());
if (protectedBlocks.contains(event.getBlock().getType()) && !user.isAuthorized("essentials.signs.protection.override"))
{
if (isBlockProtected(event.getBlock(), user))
{
event.setCancelled(true);
user.sendMessage(Util.format("noDestroyPermission", event.getBlock().getType().toString().toLowerCase()));
return;
}
}
if (checkProtectionSign(event.getBlock(), user) != NOSIGN &&
checkProtectionSign(event.getBlock(), user) != OWNER)
{
event.setCancelled(true);
user.sendMessage(Util.format("noDestroyPermission", event.getBlock().getType().toString().toLowerCase()));
}
}
@Override
public void onSignChange(SignChangeEvent event)
{
if (event.isCancelled()) return;
if (ess.getSettings().areSignsDisabled()) return;
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
try
{
if (event.getLine(0).equalsIgnoreCase("[Protection]"))
{
Block block = event.getBlock();
if (user.isAuthorized("essentials.signs.protection.create") && hasAdjacentChest(block) && !isBlockProtected(block, user))
event.setLine(0, "§1[Protection]");
else
event.setLine(0, "§4[Protection]");
event.setLine(3, username);
return;
}
if (event.getLine(0).equalsIgnoreCase("[Disposal]"))
{
if (user.isAuthorized("essentials.signs.disposal.create"))
event.setLine(0, "§1[Disposal]");
else
event.setLine(0, "§4[Disposal]");
return;
}
if (event.getLine(0).equalsIgnoreCase("[Heal]"))
{
event.setLine(0, "§4[Heal]");
if (user.isAuthorized("essentials.signs.heal.create"))
{
if (!event.getLine(1).isEmpty())
{
String[] l1 = event.getLine(1).split("[ :-]+", 2);
boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
if (q1 < 1 || (!m1 && (int)q1 < 1)) throw new Exception(Util.i18n("moreThanZero"));
if (!m1) ItemDb.get(l1[1]);
event.setLine(1, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1]));
}
event.setLine(0, "§1[Heal]");
}
return;
}
if (event.getLine(0).equalsIgnoreCase("[Free]"))
{
event.setLine(0, "§4[Free]");
ItemDb.get(event.getLine(1));
if (user.isAuthorized("essentials.signs.free.create"))
event.setLine(0, "§1[Free]");
return;
}
if (event.getLine(0).equalsIgnoreCase("[Mail]"))
{
if (user.isAuthorized("essentials.signs.mail.create"))
event.setLine(0, "§1[Mail]");
else
event.setLine(0, "§4[Mail]");
return;
}
if (event.getLine(0).equalsIgnoreCase("[Balance]"))
{
if (user.isAuthorized("essentials.signs.balance.create"))
event.setLine(0, "§1[Balance]");
else
event.setLine(0, "§4[Balance]");
return;
}
if (event.getLine(0).equalsIgnoreCase("[Warp]"))
{
event.setLine(0, "§4[Warp]");
if (user.isAuthorized("essentials.signs.warp.create")) {
if (!event.getLine(3).isEmpty())
{
String[] l1 = event.getLine(3).split("[ :-]+", 2);
boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+");
if (!m1 && l1.length != 2)
{
throw new Exception(Util.format("invalidSignLine", 4));
}
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
if ((int)q1 < 1) throw new Exception(Util.i18n("moreThanZero"));
if (!m1) ItemDb.get(l1[1]);
event.setLine(3, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1]));
}
if (event.getLine(1).isEmpty()) {
event.setLine(1, "§dWarp name!");
return;
} else {
ess.getWarps().getWarp(event.getLine(1));
if (event.getLine(2).equalsIgnoreCase("Everyone")) {
event.setLine(2, "§2Everyone");
}
event.setLine(0, "§1[Warp]");
}
}
return;
}
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
@Override
public void onBlockPlace(BlockPlaceEvent event)
{
if (event.isCancelled()) return;
Block signBlock = event.getBlockAgainst();
if (signBlock.getType() == Material.WALL_SIGN || signBlock.getType() == Material.SIGN_POST)
{
Sign sign = new CraftSign(signBlock);
if (sign.getLine(0).matches("§1\\[[a-zA-Z]+\\]"))
{
event.setCancelled(true);
return;
}
}
final User user = ess.getUser(event.getPlayer());
// Do not rely on getItemInHand();
// http://leaky.bukkit.org/issues/663
final ItemStack is = new ItemStack(event.getBlockPlaced().getType(), 1, (short)0, event.getBlockPlaced().getData());
switch(is.getType()) {
case WOODEN_DOOR:
is.setType(Material.WOOD_DOOR);
is.setDurability((short)0);
break;
case IRON_DOOR_BLOCK:
is.setType(Material.IRON_DOOR);
is.setDurability((short)0);
break;
case SIGN_POST:
case WALL_SIGN:
is.setType(Material.SIGN);
is.setDurability((short)0);
break;
case CROPS:
is.setType(Material.SEEDS);
is.setDurability((short)0);
break;
case CAKE_BLOCK:
is.setType(Material.CAKE);
is.setDurability((short)0);
break;
case BED_BLOCK:
is.setType(Material.BED);
is.setDurability((short)0);
break;
case REDSTONE_WIRE:
is.setType(Material.REDSTONE);
is.setDurability((short)0);
break;
case REDSTONE_TORCH_OFF:
case REDSTONE_TORCH_ON:
is.setType(Material.REDSTONE_TORCH_ON);
is.setDurability((short)0);
break;
case DIODE_BLOCK_OFF:
case DIODE_BLOCK_ON:
is.setType(Material.DIODE);
is.setDurability((short)0);
break;
case DOUBLE_STEP:
is.setType(Material.STEP);
break;
case TORCH:
case RAILS:
case LADDER:
case WOOD_STAIRS:
case COBBLESTONE_STAIRS:
case LEVER:
case STONE_BUTTON:
case FURNACE:
case DISPENSER:
case PUMPKIN:
case JACK_O_LANTERN:
case WOOD_PLATE:
case STONE_PLATE:
is.setDurability((short)0);
break;
}
boolean unlimitedForUser = user.hasUnlimited(is);
if (unlimitedForUser) {
ess.scheduleSyncDelayedTask(
new Runnable() {
public void run() {
user.getInventory().addItem(is);
user.updateInventory();
}
});
}
}
public boolean hasAdjacentChest(Block block)
{
Block[] faces = getAdjacentBlocks(block);
for (Block b : faces)
{
if (protectedBlocks.contains(b.getType()))
{
return true;
}
}
return false;
}
private static final int NOT_ALLOWED = 0;
private static final int ALLOWED = 1;
private static final int NOSIGN = 2;
private static final int OWNER = 3;
private int checkProtectionSign(Block block, User user)
{
String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length());
if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)
{
Sign sign = new CraftSign(block);
if (sign.getLine(0).equalsIgnoreCase("§1[Protection]") && !user.isAuthorized("essentials.signs.protection.override"))
{
for (int i = 1; i <= 2; i++) {
String line = sign.getLine(i);
if (line.startsWith("(") && line.endsWith(")")) {
line = line.substring(1, line.length() - 1);
if (user.inGroup(line)) {
return ALLOWED;
}
} else if (line.equalsIgnoreCase(username)) {
return ALLOWED;
}
}
if (sign.getLine(3).equalsIgnoreCase(username))
{
return OWNER;
}
return NOT_ALLOWED;
}
}
return NOSIGN;
}
private static Block[] getAdjacentBlocks(Block block)
{
return new Block[]
{
block.getFace(BlockFace.NORTH),
block.getFace(BlockFace.SOUTH),
block.getFace(BlockFace.EAST),
block.getFace(BlockFace.WEST),
block.getFace(BlockFace.DOWN),
block.getFace(BlockFace.UP)
};
}
public boolean isBlockProtected(Block block, User user)
{
Block[] faces = getAdjacentBlocks(block);
boolean protect = false;
for (Block b : faces)
{
int check = checkProtectionSign(b, user);
if (check == NOT_ALLOWED)
{
protect = true;
}
if (check == ALLOWED || check == OWNER)
{
return false;
}
if (protectedBlocks.contains(b.getType()))
{
Block[] faceChest = getAdjacentBlocks(b);
for (Block a : faceChest)
{
check = checkProtectionSign(a, user);
if (check == NOT_ALLOWED)
{
protect = true;
}
if (check == ALLOWED || check == OWNER)
{
return false;
}
}
}
}
return protect;
}
public static boolean isBlockProtected(Block block)
{
Block[] faces = getAdjacentBlocks(block);
for (Block b : faces)
{
if (b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN)
{
Sign sign = new CraftSign(b);
if (sign.getLine(0).equalsIgnoreCase("§1[Protection]"))
{
return true;
}
}
if (protectedBlocks.contains(b.getType()))
{
Block[] faceChest = getAdjacentBlocks(b);
for (Block a : faceChest)
{
if (a.getType() == Material.SIGN_POST || a.getType() == Material.WALL_SIGN)
{
Sign sign = new CraftSign(a);
if (sign.getLine(0).equalsIgnoreCase("§1[Protection]"))
{
return true;
}
}
}
}
}
return false;
}
}

View File

@@ -1,316 +0,0 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.*;
import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.PluginCommandYamlParser;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class EssentialsCommandHandler implements ICommandHandler
{
private final transient ClassLoader classLoader;
private final transient String commandPath;
private final transient String permissionPrefix;
private final transient IEssentialsModule module;
private static final transient Logger LOGGER = Bukkit.getLogger();
private final transient Map<String, List<PluginCommand>> altcommands = new HashMap<String, List<PluginCommand>>();
private final transient Map<String, String> disabledList = new HashMap<String, String>();
private final transient Map<String, IEssentialsCommand> commands = new HashMap<String, IEssentialsCommand>();
private final transient IEssentials ess;
public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentials ess)
{
this(classLoader, commandPath, permissionPrefix, null, ess);
}
public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module, IEssentials ess)
{
this.classLoader = classLoader;
this.commandPath = commandPath;
this.permissionPrefix = permissionPrefix;
this.module = module;
this.ess = ess;
for (Plugin plugin : ess.getServer().getPluginManager().getPlugins())
{
if (plugin.isEnabled())
{
addPlugin(plugin);
}
}
}
@Override
public boolean handleCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args)
{
boolean disabled = false;
boolean overridden = false;
ISettings settings = ess.getSettings();
settings.acquireReadLock();
try
{
disabled = settings.getData().getCommands().isDisabled(command.getName());
overridden = !disabled || settings.getData().getCommands().isOverridden(command.getName());
}
finally
{
settings.unlock();
}
// Allow plugins to override the command via onCommand
if (!overridden && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName())))
{
final PluginCommand pc = getAlternative(commandLabel);
if (pc != null)
{
executed(commandLabel, pc.getLabel());
try
{
return pc.execute(sender, commandLabel, args);
}
catch (final Exception ex)
{
final ArrayList<StackTraceElement> elements = new ArrayList<StackTraceElement>(Arrays.asList(ex.getStackTrace()));
elements.remove(0);
final ArrayList<StackTraceElement> toRemove = new ArrayList<StackTraceElement>();
for (final StackTraceElement e : elements)
{
if (e.getClassName().equals("com.earth2me.essentials.Essentials"))
{
toRemove.add(e);
}
}
elements.removeAll(toRemove);
final StackTraceElement[] trace = elements.toArray(new StackTraceElement[elements.size()]);
ex.setStackTrace(trace);
ex.printStackTrace();
sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command");
return true;
}
}
}
try
{
IUser user = null;
if (sender instanceof Player)
{
user = ess.getUser((Player)sender);
LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)));
}
// Check for disabled commands
if (disabled)
{
return true;
}
final String commandName = command.getName().toLowerCase(Locale.ENGLISH);
IEssentialsCommand cmd = commands.get(commandName);
if (cmd == null)
{
try
{
cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + commandName).newInstance();
cmd.init(ess, commandName);
cmd.setEssentialsModule(module);
commands.put(commandName, cmd);
}
catch (Exception ex)
{
sender.sendMessage(_("commandNotLoaded", commandName));
LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandName), ex);
return true;
}
}
// Check authorization
if (sender != null && cmd.isAuthorized(sender))
{
LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName()));
user.sendMessage(_("noAccessCommand"));
return true;
}
// Run the command
try
{
if (user == null)
{
cmd.run(sender, command, commandLabel, args);
}
else
{
user.acquireReadLock();
try
{
cmd.run(user, command, commandLabel, args);
}
finally
{
user.unlock();
}
}
return true;
}
catch (NoChargeException ex)
{
return true;
}
catch (NotEnoughArgumentsException ex)
{
sender.sendMessage(command.getDescription());
sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel));
if (!ex.getMessage().isEmpty())
{
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (Throwable ex)
{
showCommandError(sender, commandLabel, ex);
return true;
}
}
catch (Throwable ex)
{
LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex);
return true;
}
}
@Override
public void showCommandError(final CommandSender sender, final String commandLabel, final Throwable exception)
{
sender.sendMessage(_("errorWithMessage", exception.getMessage()));
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception);
}
}
@Override
public void onReload()
{
}
public final void addPlugin(final Plugin plugin)
{
if (plugin.getDescription().getMain().contains("com.earth2me.essentials"))
{
return;
}
final List<Command> commands = PluginCommandYamlParser.parse(plugin);
final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH);
for (Command command : commands)
{
final PluginCommand pc = (PluginCommand)command;
final List<String> labels = new ArrayList<String>(pc.getAliases());
labels.add(pc.getName());
PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH));
if (reg == null)
{
reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH));
}
if (reg == null || !reg.getPlugin().equals(plugin))
{
continue;
}
for (String label : labels)
{
List<PluginCommand> plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH));
if (plugincommands == null)
{
plugincommands = new ArrayList<PluginCommand>();
altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands);
}
boolean found = false;
for (PluginCommand pc2 : plugincommands)
{
if (pc2.getPlugin().equals(plugin))
{
found = true;
}
}
if (!found)
{
plugincommands.add(reg);
}
}
}
}
public void removePlugin(final Plugin plugin)
{
final Iterator<Map.Entry<String, List<PluginCommand>>> iterator = altcommands.entrySet().iterator();
while (iterator.hasNext())
{
final Map.Entry<String, List<PluginCommand>> entry = iterator.next();
final Iterator<PluginCommand> pcIterator = entry.getValue().iterator();
while (pcIterator.hasNext())
{
final PluginCommand pc = pcIterator.next();
if (pc.getPlugin() == null || pc.getPlugin().equals(plugin))
{
pcIterator.remove();
}
}
if (entry.getValue().isEmpty())
{
iterator.remove();
}
}
}
public PluginCommand getAlternative(final String label)
{
final List<PluginCommand> commands = altcommands.get(label);
if (commands == null || commands.isEmpty())
{
return null;
}
if (commands.size() == 1)
{
return commands.get(0);
}
// return the first command that is not an alias
for (PluginCommand command : commands)
{
if (command.getName().equalsIgnoreCase(label))
{
return command;
}
}
// return the first alias
return commands.get(0);
}
public void executed(final String label, final String otherLabel)
{
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + otherLabel);
}
disabledList.put(label, otherLabel);
}
public Map<String, String> disabledCommands()
{
return disabledList;
}
}

View File

@@ -0,0 +1,239 @@
package com.earth2me.essentials;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.config.Configuration;
public class EssentialsConf extends Configuration
{
private static final Logger logger = Logger.getLogger("Minecraft");
private File configFile;
private String templateName = null;
private Class<?> resourceClass = EssentialsConf.class;
public EssentialsConf(File configFile)
{
super(configFile);
this.configFile = configFile;
if (this.root == null)
{
this.root = new HashMap<String, Object>();
}
}
@Override
public void load()
{
configFile = configFile.getAbsoluteFile();
if (!configFile.getParentFile().exists())
{
if (!configFile.getParentFile().mkdirs())
{
logger.log(Level.SEVERE, Util.format("failedToCreateConfig", configFile.toString()));
}
}
if (!configFile.exists())
{
if (templateName != null)
{
logger.log(Level.INFO, Util.format("creatingConfigFromTemplate", configFile.toString()));
createFromTemplate();
}
else
{
try
{
logger.log(Level.INFO, Util.format("creatingEmptyConfig", configFile.toString()));
if (!configFile.createNewFile())
{
logger.log(Level.SEVERE, Util.format("failedToCreateConfig", configFile.toString()));
}
}
catch (IOException ex)
{
logger.log(Level.SEVERE, Util.format("failedToCreateConfig", configFile.toString()), ex);
}
}
}
super.load();
if (this.root == null)
{
this.root = new HashMap<String, Object>();
}
}
private void createFromTemplate()
{
InputStream istr = null;
OutputStream ostr = null;
try
{
istr = resourceClass.getResourceAsStream(templateName);
if (istr == null)
{
logger.log(Level.SEVERE, Util.format("couldNotFindTemplate", templateName));
return;
}
ostr = new FileOutputStream(configFile);
byte[] buffer = new byte[1024];
int length = 0;
length = istr.read(buffer);
while (length > 0)
{
ostr.write(buffer, 0, length);
length = istr.read(buffer);
}
}
catch (IOException ex)
{
logger.log(Level.SEVERE, Util.format("failedToWriteConfig", configFile.toString()), ex);
return;
}
finally
{
try
{
if (istr != null)
{
istr.close();
}
}
catch (IOException ex)
{
Logger.getLogger(EssentialsConf.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
if (ostr != null)
{
ostr.close();
}
}
catch (IOException ex)
{
logger.log(Level.SEVERE, Util.format("failedToCloseConfig", configFile.toString()), ex);
}
}
}
public void setTemplateName(String templateName)
{
this.templateName = templateName;
}
public File getFile()
{
return configFile;
}
public void setTemplateName(String templateName, Class<?> resClass)
{
this.templateName = templateName;
this.resourceClass = resClass;
}
public boolean hasProperty(String path)
{
return getProperty(path) != null;
}
public Location getLocation(String path, Server server)
{
String worldName = getString((path != null ? path + "." : "") + "world");
if (worldName == null || worldName.isEmpty())
{
return null;
}
World world = server.getWorld(worldName);
if (world == null)
{
return null;
}
return new Location(world,
getDouble((path != null ? path + "." : "") + "x", 0),
getDouble((path != null ? path + "." : "") + "y", 0),
getDouble((path != null ? path + "." : "") + "z", 0),
(float)getDouble((path != null ? path + "." : "") + "yaw", 0),
(float)getDouble((path != null ? path + "." : "") + "pitch", 0));
}
public void setProperty(String path, Location loc)
{
setProperty((path != null ? path + "." : "") + "world", loc.getWorld().getName());
setProperty((path != null ? path + "." : "") + "x", loc.getX());
setProperty((path != null ? path + "." : "") + "y", loc.getY());
setProperty((path != null ? path + "." : "") + "z", loc.getZ());
setProperty((path != null ? path + "." : "") + "yaw", loc.getYaw());
setProperty((path != null ? path + "." : "") + "pitch", loc.getPitch());
}
public ItemStack getItemStack(String path)
{
return new ItemStack(
Material.valueOf(getString(path + ".type", "AIR")),
getInt(path + ".amount", 1),
(short)getInt(path + ".damage", 0)/*,
(byte)getInt(path + ".data", 0)*/);
}
public void setProperty(String path, ItemStack stack)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", stack.getType().toString());
map.put("amount", stack.getAmount());
map.put("damage", stack.getDurability());
// getData().getData() is broken
//map.put("data", stack.getDurability());
setProperty(path, map);
}
public long getLong(String path, long def)
{
Number num;
try
{
num = (Number)getProperty(path);
}
catch(ClassCastException ex)
{
return def;
}
if (num == null)
{
return def;
}
return num.longValue();
}
@Override
public double getDouble(String path, double def)
{
Number num;
try
{
num = (Number)getProperty(path);
}
catch(ClassCastException ex)
{
return def;
}
if (num == null)
{
return def;
}
return num.doubleValue();
}
}

View File

@@ -0,0 +1,250 @@
package com.earth2me.essentials;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.block.CraftSign;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.inventory.ItemStack;
public class EssentialsEcoBlockListener extends BlockListener
{
private final IEssentials ess;
private static final Logger logger = Logger.getLogger("Minecraft");
public EssentialsEcoBlockListener(Essentials ess)
{
this.ess = ess;
}
@Override
public void onBlockBreak(BlockBreakEvent event)
{
if (event.isCancelled())
{
return;
}
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST)
{
return;
}
Sign sign = new CraftSign(event.getBlock());
if (sign.getLine(0).equals("§1[Trade]"))
{
if (!sign.getLine(3).substring(2).equals(username))
{
if (!user.isOp())
{
event.setCancelled(true);
}
return;
}
try
{
String[] l1 = sign.getLines()[1].split("[ :-]+");
String[] l2 = sign.getLines()[2].split("[ :-]+");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
double r1 = Double.parseDouble(l1[m1 ? 1 : 2]);
double r2 = Double.parseDouble(l2[m2 ? 1 : 2]);
if ((!m1 & q1 < 1) || (!m2 & q2 < 1))
{
throw new Exception(Util.i18n("moreThanZero"));
}
ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], (int)r1);
ItemStack i2 = m2 || r2 <= 0 ? null : ItemDb.get(l2[1], (int)r2);
if (m1)
{
user.giveMoney(r1);
}
else if (i1 != null)
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i1);
for (ItemStack itemStack : leftOver.values())
{
InventoryWorkaround.dropItem(user.getLocation(), itemStack);
}
}
if (m2)
{
user.giveMoney(r2);
}
else if (i2 != null)
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i2);
for (ItemStack itemStack : leftOver.values())
{
InventoryWorkaround.dropItem(user.getLocation(), itemStack);
}
}
user.updateInventory();
sign.setType(Material.AIR);
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return;
}
}
@Override
public void onSignChange(SignChangeEvent event)
{
if (ess.getSettings().areSignsDisabled())
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
if ((event.getLine(0).equalsIgnoreCase("[Buy]") || event.getLine(0).equalsIgnoreCase("#1[Buy]")) && user.isAuthorized("essentials.signs.buy.create"))
{
try
{
event.setLine(0, "§1[Buy]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Don't sell air.");
}
double price = Double.parseDouble(event.getLine(3).replaceAll("[^0-9\\.]", ""));
event.setLine(3, Util.formatCurrency(price));
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Buy]");
event.setLine(1, "#");
event.setLine(2, "Item");
event.setLine(3, "$Price");
}
return;
}
if ((event.getLine(0).equalsIgnoreCase("[Sell]") || event.getLine(0).equalsIgnoreCase("#1[Sell]")) && user.isAuthorized("essentials.signs.sell.create"))
{
try
{
event.setLine(0, "§1[Sell]");
event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1))));
ItemStack is = ItemDb.get(event.getLine(2));
if (is.getTypeId() == 0 || Math.abs(Integer.parseInt(event.getLine(1))) == 0)
{
throw new Exception("Can't buy air.");
}
double price = Double.parseDouble(event.getLine(3).replaceAll("[^0-9\\.]", ""));
event.setLine(3, Util.formatCurrency(price));
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Sell]");
event.setLine(1, "#");
event.setLine(2, "Item");
event.setLine(3, "$Price");
}
return;
}
if ((event.getLine(0).equalsIgnoreCase("[Trade]") || event.getLine(0).equalsIgnoreCase("#1[Trade]")) && user.isAuthorized("essentials.signs.trade.create"))
{
try
{
String[] l1 = event.getLine(1).split("[ :-]+");
String[] l2 = event.getLine(2).split("[ :-]+");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
if (m1 ? l1.length != 1 : l1.length != 2)
{
throw new Exception(Util.format("invalidSignLine", 2));
}
if (m2 ? l2.length != 2 : l2.length != 3)
{
throw new Exception(Util.format("invalidSignLine", 3));
}
double r2 = Double.parseDouble(l2[m2 ? 1 : 2]);
r2 = m2 ? r2 : r2 - r2 % q2;
if ((!m1 & q1 < 1) || (!m2 & q2 < 1) || r2 < 1)
{
throw new Exception(Util.i18n("moreThanZero"));
}
if (!m1)
{
ItemDb.get(l1[1]);
}
if (m2)
{
if (user.getMoney() < r2)
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
user.takeMoney(r2);
//user.sendMessage("r2: " + r2 + " q2: " + q2);
}
else
{
ItemStack i2 = ItemDb.get(l2[1], (int)r2);
if (!InventoryWorkaround.containsItem(user.getInventory(), true, i2))
{
throw new Exception(Util.format("missingItems", (int)r2, l2[1]));
}
InventoryWorkaround.removeItem(user.getInventory(), true, i2);
user.updateInventory();
}
event.setLine(0, "§1[Trade]");
event.setLine(1, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1]) + ":0");
event.setLine(2, (m2 ? Util.formatCurrency(q2) : (int)q2 + " " + l2[1]) + ":" + (m2 ? Util.roundDouble(r2) : "" + (int)r2));
event.setLine(3, "§8" + username);
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
event.setLine(0, "§4[Trade]");
event.setLine(1, "# ItemOr" + ess.getSettings().getCurrencySymbol());
event.setLine(2, "# ItemOr" + ess.getSettings().getCurrencySymbol() + ":#");
event.setLine(3, "§8" + username);
}
return;
}
}
}

View File

@@ -0,0 +1,211 @@
package com.earth2me.essentials;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.block.CraftSign;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.inventory.ItemStack;
public class EssentialsEcoPlayerListener extends PlayerListener
{
private final IEssentials ess;
private static final Logger logger = Logger.getLogger("Minecraft");
EssentialsEcoPlayerListener(IEssentials ess)
{
this.ess = ess;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
if (ess.getSettings().areSignsDisabled())
{
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
{
return;
}
User user = ess.getUser(event.getPlayer());
String username = user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
{
return;
}
Sign sign = new CraftSign(event.getClickedBlock());
if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use"))
{
try
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
double cost = Double.parseDouble(sign.getLine(3).substring(1));
if (user.getMoney() < cost)
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
user.takeMoney(cost);
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(item);
for (ItemStack itemStack : leftOver.values())
{
InventoryWorkaround.dropItem(user.getLocation(), itemStack);
}
user.updateInventory();
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return;
}
if (sign.getLine(0).equals("§1[Sell]") && user.isAuthorized("essentials.signs.sell.use"))
{
try
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
double cost = Double.parseDouble(sign.getLine(3).substring(1));
if (!InventoryWorkaround.containsItem(user.getInventory(), true, item))
{
throw new Exception(Util.format("missingItems", amount, sign.getLine(2)));
}
user.giveMoney(cost);
InventoryWorkaround.removeItem(user.getInventory(), true, item);
user.updateInventory();
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return;
}
if (sign.getLine(0).equals("§1[Trade]") && user.isAuthorized("essentials.signs.trade.use"))
{
try
{
String[] l1 = sign.getLine(1).split("[ :-]+");
String[] l2 = sign.getLine(2).split("[ :-]+");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
double r1 = Double.parseDouble(l1[m1 ? 1 : 2]);
double r2 = Double.parseDouble(l2[m2 ? 1 : 2]);
r1 = m1 ? r1 : r1 - r1 % q1;
r2 = m2 ? r2 : r2 - r2 % q2;
if ((!m1 & q1 < 1) || (!m2 & q2 < 1))
{
throw new Exception(Util.i18n("moreThanZero"));
}
ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], (int)r1);
ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], (int)q1);
ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], (int)q2);
if (username.equals(sign.getLine(3).substring(2)))
{
if (m1)
{
user.giveMoney(r1);
}
else if (i1 != null)
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(i1);
for (ItemStack itemStack : leftOver.values())
{
InventoryWorkaround.dropItem(user.getLocation(), itemStack);
}
user.updateInventory();
}
r1 = 0;
sign.setLine(1, (m1 ? Util.formatCurrency(q1) : ((int)q1) + " " + l1[1]) + ":0");
sign.update();
}
else
{
if (m1)
{
if (user.getMoney() < q1)
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
}
else
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, qi1))
{
throw new Exception(Util.format("missingItems", (int)q1, l1[1]));
}
}
if (r2 < q2)
{
throw new Exception(Util.i18n("tradeSignEmpty"));
}
if (m1)
{
user.takeMoney(q1);
}
else
{
InventoryWorkaround.removeItem(user.getInventory(), true, qi1);
}
if (m2)
{
user.giveMoney(q2);
}
else
{
Map<Integer, ItemStack> leftOver = user.getInventory().addItem(qi2);
for (ItemStack itemStack : leftOver.values())
{
InventoryWorkaround.dropItem(user.getLocation(), itemStack);
}
}
user.updateInventory();
r1 += q1;
r2 -= q2;
sign.setLine(0, "§1[Trade]");
sign.setLine(1, (m1 ? Util.formatCurrency(q1) : ((int)q1) + " " + l1[1]) + ":" + (m1 ? Util.roundDouble(r1) : "" + (int)r1));
sign.setLine(2, (m2 ? Util.formatCurrency(q2) : ((int)q2) + " " + l2[1]) + ":" + (m2 ? Util.roundDouble(r2) : "" + (int)r2));
sign.update();
user.sendMessage(Util.i18n("tradeCompleted"));
}
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return;
}
}
}

View File

@@ -0,0 +1,82 @@
package com.earth2me.essentials;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageByProjectileEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.inventory.ItemStack;
public class EssentialsEntityListener extends EntityListener
{
private final IEssentials ess;
public EssentialsEntityListener(IEssentials ess)
{
this.ess = ess;
}
@Override
public void onEntityDamage(EntityDamageEvent event)
{
if (event instanceof EntityDamageByEntityEvent)
{
EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event;
Entity eAttack = edEvent.getDamager();
Entity eDefend = edEvent.getEntity();
if (eDefend instanceof Player && eAttack instanceof Player)
{
User defender = ess.getUser(eDefend);
User attacker = ess.getUser(eAttack);
ItemStack is = attacker.getItemInHand();
String command = attacker.getPowertool(is);
if (command != null && !command.isEmpty())
{
attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", defender.getName()));
event.setCancelled(true);
return;
}
}
}
if (event instanceof EntityDamageEvent || event instanceof EntityDamageByBlockEvent || event instanceof EntityDamageByProjectileEvent)
{
if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled())
{
CraftPlayer player = (CraftPlayer)event.getEntity();
player.getHandle().fireTicks = 0;
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
}
}
}
@Override
public void onEntityCombust(EntityCombustEvent event)
{
if (event.getEntity() instanceof Player && ess.getUser(event.getEntity()).isGodModeEnabled())
{
event.setCancelled(true);
}
}
@Override
public void onEntityDeath(EntityDeathEvent event)
{
if (event.getEntity() instanceof Player)
{
User user = ess.getUser(event.getEntity());
if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back"))
{
user.setLastLocation();
user.sendMessage(Util.i18n("backAfterDeath"));
}
}
}
}

View File

@@ -0,0 +1,128 @@
package com.earth2me.essentials;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
class EssentialsErrorHandler extends Handler
{
private final Map<BigInteger, String> errors = new HashMap<BigInteger, String>();
private final List<LogRecord> records = new LinkedList<LogRecord>();
public EssentialsErrorHandler()
{
}
@Override
public void publish(LogRecord lr)
{
if (lr.getThrown() == null || lr.getLevel().intValue() < Level.WARNING.intValue())
{
return;
}
synchronized (records)
{
records.add(lr);
}
}
@Override
public void flush()
{
synchronized (records)
{
sortRecords();
}
}
@Override
public void close() throws SecurityException
{
synchronized (records)
{
sortRecords();
}
}
private void sortRecords()
{
for (LogRecord lr : records)
{
try
{
if (lr.getThrown() == null)
{
return;
}
Throwable tr = lr.getThrown();
StackTraceElement[] elements = tr.getStackTrace();
if (elements == null || elements.length <= 0)
{
return;
}
boolean essentialsFound = false;
for (StackTraceElement stackTraceElement : elements)
{
if (stackTraceElement.getClassName().contains("com.earth2me.essentials"))
{
essentialsFound = true;
break;
}
}
if (!essentialsFound && tr.getCause() != null)
{
Throwable cause = tr.getCause();
StackTraceElement[] elements2 = cause.getStackTrace();
if (elements2 != null)
{
for (StackTraceElement stackTraceElement : elements2)
{
if (stackTraceElement.getClassName().contains("com.earth2me.essentials"))
{
essentialsFound = true;
break;
}
}
}
}
StringBuilder sb = new StringBuilder();
sb.append("[").append(lr.getLevel().getName()).append("] ").append(lr.getMessage()).append("\n");
sb.append(tr.getMessage()).append("\n");
for (StackTraceElement stackTraceElement : tr.getStackTrace())
{
sb.append(stackTraceElement.toString()).append("\n");
}
if (tr.getCause() != null && tr.getCause().getStackTrace() != null)
{
sb.append(tr.getCause().getMessage()).append("\n");
for (StackTraceElement stackTraceElement : tr.getCause().getStackTrace())
{
sb.append(stackTraceElement.toString()).append("\n");
}
}
String errorReport = sb.toString();
byte[] bytesOfMessage = errorReport.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
BigInteger bi = new BigInteger(md.digest(bytesOfMessage));
errors.put(bi, errorReport);
}
catch (Throwable t)
{
//Ignore all exceptions inside the exception handler
}
}
records.clear();
}
Map<BigInteger, String> getErrors()
{
return errors;
}
}

View File

@@ -0,0 +1,596 @@
package com.earth2me.essentials;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.InventoryPlayer;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.block.CraftSign;
import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.event.player.PlayerAnimationType;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerEggThrowEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.inventory.ItemStack;
public class EssentialsPlayerListener extends PlayerListener
{
private static final Logger logger = Logger.getLogger("Minecraft");
private final Server server;
private final IEssentials ess;
private final EssentialsBlockListener essBlockListener;
public EssentialsPlayerListener(IEssentials parent)
{
this.ess = parent;
this.server = parent.getServer();
essBlockListener = new EssentialsBlockListener(parent);
}
@Override
public void onPlayerRespawn(PlayerRespawnEvent event)
{
User user = ess.getUser(event.getPlayer());
user.setDisplayName(user.getNick());
updateCompass(user);
if (user.isJailed() && user.getJail() != null && !user.getJail().isEmpty()) {
try
{
event.setRespawnLocation(ess.getJail().getJail(user.getJail()));
}
catch (Exception ex)
{
}
}
}
@Override
public void onPlayerChat(PlayerChatEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.isMuted())
{
event.setCancelled(true);
logger.info(Util.format("mutedUserSpeaks", user.getName()));
}
Iterator<Player> it = event.getRecipients().iterator();
while (it.hasNext())
{
User u = ess.getUser(it.next());
if (u.isIgnoredPlayer(user.getName()))
{
it.remove();
}
}
}
@Override
public void onPlayerMove(PlayerMoveEvent event)
{
if (event.isCancelled())
{
return;
}
final User user = ess.getUser(event.getPlayer());
if (!ess.getSettings().getNetherPortalsEnabled())
{
return;
}
final Block block = event.getPlayer().getWorld().getBlockAt(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ());
List<World> worlds = server.getWorlds();
if (block.getType() == Material.PORTAL && worlds.size() > 1 && user.isAuthorized("essentials.portal"))
{
if (user.getJustPortaled())
{
return;
}
Location loc = event.getTo();
World nether = server.getWorld(ess.getSettings().getNetherName());
if (nether == null) {
for (World world : worlds)
{
if (world.getEnvironment() == World.Environment.NETHER) {
nether = world;
break;
}
}
if (nether == null) {
return;
}
}
final World world = user.getWorld() == nether ? worlds.get(0) : nether;
double factor;
if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL)
{
factor = ess.getSettings().getNetherRatio();
}
else if (user.getWorld().getEnvironment() != world.getEnvironment())
{
factor = 1.0 / ess.getSettings().getNetherRatio();
}
else
{
factor = 1.0;
}
int x = loc.getBlockX();
int y = loc.getBlockY();
int z = loc.getBlockZ();
if (user.getWorld().getBlockAt(x, y, z - 1).getType() == Material.PORTAL)
{
z--;
}
if (user.getWorld().getBlockAt(x - 1, y, z).getType() == Material.PORTAL)
{
x--;
}
x = (int)(x * factor);
z = (int)(z * factor);
loc = new Location(world, x + .5, y, z + .5);
Block dest = world.getBlockAt(x, y, z);
NetherPortal portal = NetherPortal.findPortal(dest);
if (portal == null)
{
if (world.getEnvironment() == World.Environment.NETHER || ess.getSettings().getGenerateExitPortals())
{
portal = NetherPortal.createPortal(dest);
logger.info(Util.format("userCreatedPortal", event.getPlayer().getName()));
user.sendMessage(Util.i18n("generatingPortal"));
loc = portal.getSpawn();
}
}
else
{
logger.info(Util.format("userUsedPortal", event.getPlayer().getName()));
user.sendMessage(Util.i18n("usingPortal"));
loc = portal.getSpawn();
}
event.setFrom(loc);
event.setTo(loc);
try
{
user.getTeleport().now(loc, new Charge("portal", ess));
}
catch (Exception ex)
{
user.sendMessage(ex.getMessage());
}
user.setJustPortaled(true);
user.sendMessage(Util.i18n("teleportingPortal"));
event.setCancelled(true);
return;
}
user.setJustPortaled(false);
}
@Override
public void onPlayerQuit(PlayerQuitEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.getSavedInventory() != null)
{
user.getInventory().setContents(user.getSavedInventory());
user.setSavedInventory(null);
}
if (!ess.getSettings().getReclaimSetting())
{
return;
}
user.dispose();
Thread thread = new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(1000);
Runtime rt = Runtime.getRuntime();
double mem = rt.freeMemory();
rt.runFinalization();
rt.gc();
mem = rt.freeMemory() - mem;
mem /= 1024 * 1024;
logger.log(Level.INFO, Util.format("freedMemory", mem));
}
catch (InterruptedException ex)
{
return;
}
}
});
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
@Override
public void onPlayerJoin(PlayerJoinEvent event)
{
ess.getBackup().onPlayerJoin();
User user = ess.getUser(event.getPlayer());
//we do not know the ip address on playerlogin so we need to do this here.
if (user.isIpBanned())
{
String banReason = user.getBanReason();
user.kickPlayer(banReason != null && !banReason.isEmpty() ? banReason : Util.i18n("defaultBanReason"));
return;
}
user.setDisplayName(user.getNick());
if (!ess.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd"))
{
for (String m : ess.getMotd(user, null))
{
if (m == null)
{
continue;
}
user.sendMessage(m);
}
}
if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail"))
{
List<String> mail = user.getMails();
if (mail.isEmpty())
{
user.sendMessage(Util.i18n("noNewMail"));
}
else
{
user.sendMessage(Util.format("youHaveNewMail", mail.size()));
}
}
}
@Override
public void onPlayerLogin(PlayerLoginEvent event)
{
if (event.getResult() != Result.ALLOWED)
{
return;
}
User user = ess.getUser(event.getPlayer());
user.setNPC(false);
if (user.isBanned())
{
String banReason = user.getBanReason();
event.disallow(Result.KICK_BANNED, banReason != null && !banReason.isEmpty() ? banReason : Util.i18n("defaultBanReason"));
return;
}
if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !user.isAuthorized("essentials.joinfullserver"))
{
event.disallow(Result.KICK_FULL, Util.i18n("serverFull"));
return;
}
user.setLastLogin(System.currentTimeMillis());
updateCompass(user);
}
private void updateCompass(User user)
{
try
{
user.setCompassTarget(user.getHome(user.getLocation()));
}
catch (Exception ex)
{
}
}
@Override
public void onPlayerTeleport(PlayerTeleportEvent event)
{
if (event.isCancelled())
{
return;
}
User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
{
return;
}
try
{
event.setTo(ess.getJail().getJail(user.getJail()));
}
catch (Exception ex)
{
logger.log(Level.WARNING, Util.i18n("returnPlayerToJailError"), ex);
}
user.sendMessage(Util.i18n("jailMessage"));
}
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
if (event.isCancelled())
{
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
{
return;
}
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
return;
}
if (!ess.getSettings().areSignsDisabled() && EssentialsBlockListener.protectedBlocks.contains(event.getClickedBlock().getType()))
{
if (!user.isAuthorized("essentials.signs.protection.override"))
{
if (essBlockListener.isBlockProtected(event.getClickedBlock(), user))
{
event.setCancelled(true);
user.sendMessage(Util.format("noAccessPermission", event.getClickedBlock().getType().toString().toLowerCase()));
return;
}
}
}
if (ess.getSettings().getBedSetsHome() && event.getClickedBlock().getType() == Material.BED_BLOCK)
{
try
{
user.setHome();
user.sendMessage(Util.i18n("homeSetToBed"));
}
catch (Throwable ex)
{
}
}
if (ess.getSettings().areSignsDisabled())
{
return;
}
if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST)
{
return;
}
Sign sign = new CraftSign(event.getClickedBlock());
try
{
if (sign.getLine(0).equals("§1[Free]") && user.isAuthorized("essentials.signs.free.use"))
{
ItemStack item = ItemDb.get(sign.getLine(1));
CraftInventoryPlayer inv = new CraftInventoryPlayer(new InventoryPlayer(user.getHandle()));
inv.clear();
item.setAmount(9 * 4 * 64);
inv.addItem(item);
user.showInventory(inv);
return;
}
if (sign.getLine(0).equals("§1[Disposal]") && user.isAuthorized("essentials.signs.disposal.use"))
{
CraftInventoryPlayer inv = new CraftInventoryPlayer(new InventoryPlayer(user.getHandle()));
inv.clear();
user.showInventory(inv);
return;
}
if (sign.getLine(0).equals("§1[Heal]") && user.isAuthorized("essentials.signs.heal.use"))
{
if (!sign.getLine(1).isEmpty())
{
String[] l1 = sign.getLine(1).split("[ :-]+");
boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
if (!m1 && (int)q1 < 1)
{
throw new Exception(Util.i18n("moreThanZero"));
}
if (m1)
{
if (user.getMoney() < q1)
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
user.takeMoney(q1);
user.sendMessage(Util.format("moneyTaken", Util.formatCurrency(q1)));
}
else
{
ItemStack i = ItemDb.get(l1[1], (int)q1);
if (!InventoryWorkaround.containsItem(user.getInventory(), true, i))
{
throw new Exception(Util.format("missingItems", (int)q1, l1[1]));
}
InventoryWorkaround.removeItem(user.getInventory(), true, i);
user.updateInventory();
}
}
user.setHealth(20);
user.sendMessage(Util.i18n("youAreHealed"));
return;
}
if (sign.getLine(0).equals("§1[Mail]") && user.isAuthorized("essentials.signs.mail.use") && user.isAuthorized("essentials.mail"))
{
List<String> mail = user.getMails();
if (mail.isEmpty())
{
user.sendMessage(Util.i18n("noNewMail"));
return;
}
for (String s : mail)
{
user.sendMessage(s);
}
user.sendMessage(Util.i18n("markMailAsRead"));
return;
}
if (sign.getLine(0).equals("§1[Balance]") && user.isAuthorized("essentials.signs.balance.use"))
{
user.sendMessage(Util.format("balance", user.getMoney()));
return;
}
if (sign.getLine(0).equals("§1[Warp]"))
{
if (!sign.getLine(2).isEmpty())
{
if (sign.getLine(2).equals("§2Everyone"))
{
Charge charge = chargeUserForWarp(sign, user);
user.getTeleport().warp(sign.getLine(1), charge);
return;
}
if (user.inGroup(sign.getLine(2)))
{
Charge charge = chargeUserForWarp(sign, user);
user.getTeleport().warp(sign.getLine(1), charge);
return;
}
}
if (user.isAuthorized("essentials.signs.warp.use")
&& (!ess.getSettings().getPerWarpPermission() || user.isAuthorized("essentials.warp." + sign.getLine(1))))
{
Charge charge = chargeUserForWarp(sign, user);
user.getTeleport().warp(sign.getLine(1), charge);
}
return;
}
}
catch (Throwable ex)
{
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
private Charge chargeUserForWarp(Sign sign, User user) throws Exception
{
if (!sign.getLine(3).isEmpty())
{
String[] l1 = sign.getLine(3).split("[ :-]+");
boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
if (!m1 && (int)q1 < 1)
{
throw new Exception(Util.i18n("moreThanZero"));
}
if (m1)
{
return new Charge(q1, ess);
}
else
{
ItemStack i = ItemDb.get(l1[1], (int)q1);
return new Charge(i, ess);
}
}
return new Charge("warpsign", ess);
}
@Override
public void onPlayerEggThrow(PlayerEggThrowEvent event)
{
User user = ess.getUser(event.getPlayer());
ItemStack is = new ItemStack(Material.EGG, 1);
if (user.hasUnlimited(is))
{
user.getInventory().addItem(is);
user.updateInventory();
}
}
@Override
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.hasUnlimited(new ItemStack(event.getBucket())))
{
event.getItemStack().setType(event.getBucket());
ess.scheduleSyncDelayedTask(new Runnable()
{
public void run()
{
user.updateInventory();
}
});
}
}
@Override
public void onPlayerAnimation(PlayerAnimationEvent event)
{
usePowertools(event);
}
private void usePowertools(PlayerAnimationEvent event)
{
if (event.getAnimationType() != PlayerAnimationType.ARM_SWING)
{
return;
}
User user = ess.getUser(event.getPlayer());
ItemStack is = user.getItemInHand();
if (is == null || is.getType() == Material.AIR)
{
return;
}
String command = user.getPowertool(is);
if (command == null || command.isEmpty())
{
return;
}
if (command.matches(".*\\{player\\}.*"))
{
//user.sendMessage("Click a player to use this command");
return;
}
if (command.startsWith("c:"))
{
for (Player p : server.getOnlinePlayers())
{
p.sendMessage(user.getDisplayName() + ":" + command.substring(2));
}
}
else
{
user.getServer().dispatchCommand(user, command);
}
}
}

View File

@@ -0,0 +1,45 @@
package com.earth2me.essentials;
import com.earth2me.essentials.register.payment.Methods;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.ServerListener;
public class EssentialsPluginListener extends ServerListener
{
private final Methods methods;
private static final Logger logger = Logger.getLogger("Minecraft");
public EssentialsPluginListener(Methods methods)
{
this.methods = methods;
}
@Override
public void onPluginEnable(PluginEnableEvent event)
{
if (!methods.hasMethod())
{
if (methods.setMethod(event.getPlugin()))
{
logger.log(Level.INFO, "[Essentials] Payment method found (" + methods.getMethod().getName() + " version: " + methods.getMethod().getVersion() + ")");
}
}
}
@Override
public void onPluginDisable(PluginDisableEvent event)
{
// Check to see if the plugin thats being disabled is the one we are using
if (methods != null && methods.hasMethod())
{
if (methods.checkDisabled(event.getPlugin()))
{
logger.log(Level.INFO, "[Essentials] Payment method was disabled. No longer accepting payments.");
}
}
}
}

View File

@@ -1,82 +1,81 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.ISettings;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.perm.Permissions;
import com.earth2me.essentials.user.UserData.TimestampType;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.Player;
public class EssentialsTimer implements Runnable
public class EssentialsTimer implements Runnable, IConf
{
private final transient IEssentials ess;
private final transient Set<IUser> onlineUsers = new HashSet<IUser>();
EssentialsTimer(final IEssentials ess)
private final IEssentials ess;
private final Set<User> allUsers = new HashSet<User>();
EssentialsTimer(IEssentials ess)
{
this.ess = ess;
}
@Override
public void run()
{
final long currentTime = System.currentTimeMillis();
for (Player player : ess.getServer().getOnlinePlayers())
{
try
{
final IUser user = ess.getUser(player);
onlineUsers.add(user);
user.setLastOnlineActivity(currentTime);
user.checkActivity();
boolean mailDisabled = false;
ISettings settings = ess.getSettings();
settings.acquireReadLock();
try
{
mailDisabled = settings.getData().getCommands().isDisabled("mail");
}
finally
{
settings.unlock();
}
// New mail notification
if (user != null && !mailDisabled && Permissions.MAIL.isAuthorized(user) && !user.gotMailInfo())
{
final List<String> mail = user.getMails();
if (mail != null && !mail.isEmpty())
{
user.sendMessage(_("youHaveNewMail", mail.size()));
}
}
}
catch (Exception e)
{
ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e);
}
File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
final Iterator<IUser> iterator = onlineUsers.iterator();
while (iterator.hasNext())
for (String string : userdir.list())
{
final IUser user = iterator.next();
if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getTimestamp(TimestampType.LOGOUT))
{
user.setTimestamp(TimestampType.LOGOUT, user.getLastOnlineActivity());
iterator.remove();
if (!string.endsWith(".yml")) {
continue;
}
user.checkMuteTimeout(currentTime);
user.checkJailTimeout(currentTime);
String name = string.substring(0, string.length()-4);
User u = ess.getUser(new OfflinePlayer(name));
allUsers.add(u);
}
}
public void run()
{
long currentTime = System.currentTimeMillis();
for (Player player : ess.getServer().getOnlinePlayers())
{
User u = ess.getUser(player);
allUsers.add(u);
u.setLastActivity(currentTime);
}
for (User user: allUsers) {
if (user.getBanTimeout() > 0 && user.getBanTimeout() < currentTime) {
user.setBanTimeout(0);
((CraftServer)ess.getServer()).getHandle().b(user.getName());
ess.loadBanList();
}
if (user.getMuteTimeout() > 0 && user.getMuteTimeout() < currentTime && user.isMuted()) {
user.setMuteTimeout(0);
user.sendMessage(Util.i18n("canTalkAgain"));
user.setMuted(false);
}
if (user.getJailTimeout() > 0 && user.getJailTimeout() < currentTime && user.isJailed()) {
user.setJailTimeout(0);
user.setJailed(false);
user.sendMessage(Util.i18n("haveBeenReleased"));
user.setJail(null);
try
{
user.getTeleport().back();
}
catch (Exception ex)
{
}
}
if (user.getLastActivity() < currentTime && user.getLastActivity() > user.getLastLogout()) {
user.setLastLogout(user.getLastActivity());
}
}
}
public void reloadConfig()
{
for (User user : allUsers)
{
user.reloadConfig();
}
}
}

View File

@@ -0,0 +1,68 @@
package com.earth2me.essentials;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
class EssentialsUpdateTimer implements Runnable
{
private URL url;
private final Essentials ess;
private static final Logger logger = Logger.getLogger("Minecraft");
public EssentialsUpdateTimer(Essentials ess)
{
this.ess = ess;
try
{
url = new URL("http://127.0.0.1:8080/check");
}
catch (MalformedURLException ex)
{
logger.log(Level.SEVERE, "Invalid url!", ex);
}
}
public void run()
{
try
{
StringBuilder sb = new StringBuilder();
sb.append("v=").append(URLEncoder.encode(ess.getDescription().getVersion(),"UTF-8"));
sb.append("&b=").append(URLEncoder.encode(ess.getServer().getVersion(),"UTF-8"));
sb.append("&jv=").append(URLEncoder.encode(System.getProperty("java.version"),"UTF-8"));
sb.append("&l=").append(URLEncoder.encode(Util.getCurrentLocale().toString(),"UTF-8"));
sb.append("&on=").append(URLEncoder.encode(System.getProperty("os.name"),"UTF-8"));
sb.append("&ov=").append(URLEncoder.encode(System.getProperty("os.version"),"UTF-8"));
for (BigInteger bigInteger : ess.getErrors().keySet())
{
sb.append("&e[]=").append(bigInteger.toString(36));
}
URLConnection conn = url.openConnection();
conn.setConnectTimeout(10000);
conn.setDoOutput(true);
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String ret = br.readLine();
wr.close();
br.close();
logger.log(Level.INFO, ret);
}
catch (IOException ex)
{
logger.log(Level.SEVERE, "Failed to open connection", ex);
}
}
}

View File

@@ -0,0 +1,420 @@
package com.earth2me.essentials;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.inventory.ItemStack;
public class EssentialsUpgrade
{
private static boolean alreadyRun = false;
private final static Logger logger = Logger.getLogger("Minecraft");
private final IEssentials ess;
EssentialsUpgrade(String version, IEssentials essentials)
{
ess = essentials;
if (alreadyRun)
{
return;
}
alreadyRun = true;
}
private void moveWorthValuesToWorthYml()
{
try
{
File configFile = new File(ess.getDataFolder(), "config.yml");
if (!configFile.exists())
{
return;
}
EssentialsConf conf = new EssentialsConf(configFile);
conf.load();
Worth w = new Worth(ess.getDataFolder());
boolean found = false;
for (Material mat : Material.values())
{
int id = mat.getId();
double value = conf.getDouble("worth-" + id, Double.NaN);
if (!Double.isNaN(value))
{
found = true;
w.setPrice(new ItemStack(mat, 1, (short)0, (byte)0), value);
}
}
if (found)
{
removeLinesFromConfig(configFile, "\\s*#?\\s*worth-[0-9]+.*", "# Worth values have been moved to worth.yml");
}
}
catch (Throwable e)
{
logger.log(Level.SEVERE, Util.i18n("upgradingFilesError"), e);
}
}
private void removeLinesFromConfig(File file, String regex, String info) throws Exception
{
boolean needUpdate = false;
BufferedReader br = new BufferedReader(new FileReader(file));
File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder());
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
do
{
String line = br.readLine();
if (line == null)
{
break;
}
if (line.matches(regex))
{
if (!needUpdate && info != null)
{
bw.write(info, 0, info.length());
bw.newLine();
}
needUpdate = true;
}
else
{
if (line.endsWith("\r\n"))
{
bw.write(line, 0, line.length() - 2);
}
else if (line.endsWith("\r") || line.endsWith("\n"))
{
bw.write(line, 0, line.length() - 1);
}
else
{
bw.write(line, 0, line.length());
}
bw.newLine();
}
}
while (true);
br.close();
bw.close();
if (needUpdate)
{
if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup"))))
{
throw new Exception(Util.i18n("configFileMoveError"));
}
if (!tempFile.renameTo(file))
{
throw new Exception(Util.i18n("configFileRenameError"));
}
} else {
tempFile.delete();
}
}
private void updateUsersToNewDefaultHome()
{
File userdataFolder = new File(ess.getDataFolder(), "userdata");
if (!userdataFolder.exists() || !userdataFolder.isDirectory())
{
return;
}
File[] userFiles = userdataFolder.listFiles();
for (File file : userFiles)
{
if (!file.isFile() || !file.getName().endsWith(".yml"))
{
continue;
}
EssentialsConf config = new EssentialsConf(file);
try
{
config.load();
if (config.hasProperty("home") && !config.hasProperty("home.default"))
{
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>)config.getProperty("home");
if (vals == null) {
continue;
}
World world = ess.getServer().getWorlds().get(0);
if (vals.size() > 5)
{
world = ess.getServer().getWorld((String)vals.get(5));
}
if (world != null)
{
Location loc = new Location(
world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
String worldName = world.getName().toLowerCase();
if (worldName != null && !worldName.isEmpty())
{
config.removeProperty("home");
config.setProperty("home.default", worldName);
config.setProperty("home.worlds." + worldName, loc);
config.save();
}
}
}
}
catch (RuntimeException ex)
{
logger.log(Level.INFO, "File: "+file.toString());
throw ex;
}
}
}
private void moveUsersDataToUserdataFolder()
{
File usersFile = new File(ess.getDataFolder(), "users.yml");
if (!usersFile.exists())
{
return;
}
EssentialsConf usersConfig = new EssentialsConf(usersFile);
usersConfig.load();
for (String username : usersConfig.getKeys(null))
{
User user = new User(new OfflinePlayer(username), ess);
String nickname = usersConfig.getString(username + ".nickname");
if (nickname != null && !nickname.isEmpty() && !nickname.equals(username))
{
user.setNickname(nickname);
}
List<String> mails = usersConfig.getStringList(username + ".mail", null);
if (mails != null && !mails.isEmpty())
{
user.setMails(mails);
}
if (!user.hasHome())
{
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>)usersConfig.getProperty(username + ".home");
if (vals != null) {
World world = ess.getServer().getWorlds().get(0);
if (vals.size() > 5)
{
world = getFakeWorld((String)vals.get(5));
}
if (world != null)
{
user.setHome(new Location(world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue()), true);
}
}
}
}
usersFile.renameTo(new File(usersFile.getAbsolutePath() + ".old"));
}
private void convertWarps()
{
File warpsFolder = new File(ess.getDataFolder(), "warps");
if (!warpsFolder.exists())
{
warpsFolder.mkdirs();
}
File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1)
{
for (int i = 0; i < listOfFiles.length; i++)
{
String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".dat"))
{
try
{
BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i]));
double x, y, z;
float yaw, pitch;
String worldName;
try
{
if (!rx.ready()) continue;
x = Double.parseDouble(rx.readLine().trim());
if (!rx.ready()) continue;
y = Double.parseDouble(rx.readLine().trim());
if (!rx.ready()) continue;
z = Double.parseDouble(rx.readLine().trim());
if (!rx.ready()) continue;
yaw = Float.parseFloat(rx.readLine().trim());
if (!rx.ready()) continue;
pitch = Float.parseFloat(rx.readLine().trim());
worldName = rx.readLine();
}
finally {
rx.close();
}
World w = null;
for (World world : ess.getServer().getWorlds())
{
if (world.getEnvironment() != World.Environment.NETHER)
{
w = world;
break;
}
}
if (worldName != null)
{
worldName = worldName.trim();
World w1 = null;
w1 = getFakeWorld(worldName);
if (w1 != null)
{
w = w1;
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
ess.getWarps().setWarp(filename.substring(0, filename.length() - 4), loc);
if (!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old")))
{
throw new Exception(Util.format("fileRenameError", filename));
}
}
catch (Exception ex)
{
logger.log(Level.SEVERE, null, ex);
}
}
}
}
File warpFile = new File(ess.getDataFolder(), "warps.txt");
if (warpFile.exists())
{
try
{
BufferedReader rx = new BufferedReader(new FileReader(warpFile));
try
{
for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":"))
{
if (parts.length < 6)
{
continue;
}
String name = parts[0];
double x = Double.parseDouble(parts[1].trim());
double y = Double.parseDouble(parts[2].trim());
double z = Double.parseDouble(parts[3].trim());
float yaw = Float.parseFloat(parts[4].trim());
float pitch = Float.parseFloat(parts[5].trim());
if (name.isEmpty())
{
continue;
}
World w = null;
for (World world : ess.getServer().getWorlds())
{
if (world.getEnvironment() != World.Environment.NETHER)
{
w = world;
break;
}
}
Location loc = new Location(w, x, y, z, yaw, pitch);
ess.getWarps().setWarp(name, loc);
if (!warpFile.renameTo(new File(ess.getDataFolder(), "warps.txt.old")))
{
throw new Exception(Util.format("fileRenameError", "warps.txt"));
}
}
}
finally
{
rx.close();
}
}
catch (Exception ex)
{
logger.log(Level.SEVERE, null, ex);
}
}
}
private void sanitizeAllUserFilenames()
{
File usersFolder = new File(ess.getDataFolder(), "userdata");
if (!usersFolder.exists())
{
return;
}
File[] listOfFiles = usersFolder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
String filename = listOfFiles[i].getName();
if (!listOfFiles[i].isFile() || !filename.endsWith(".yml"))
{
continue;
}
String sanitizedFilename = Util.sanitizeFileName(filename.substring(0, filename.length() - 4)) + ".yml";
if (sanitizedFilename.equals(filename))
{
continue;
}
File tmpFile = new File(listOfFiles[i].getParentFile(), sanitizedFilename + ".tmp");
File newFile = new File(listOfFiles[i].getParentFile(), sanitizedFilename);
if (!listOfFiles[i].renameTo(tmpFile)) {
logger.log(Level.WARNING, Util.format("userdataMoveError", filename, sanitizedFilename));
continue;
}
if (newFile.exists())
{
logger.log(Level.WARNING, Util.format("duplicatedUserdata", filename, sanitizedFilename));
continue;
}
if (!tmpFile.renameTo(newFile)) {
logger.log(Level.WARNING, Util.format("userdataMoveBackError", sanitizedFilename, sanitizedFilename));
}
}
}
private World getFakeWorld(String name)
{
File bukkitDirectory = ess.getDataFolder().getParentFile().getParentFile();
File worldDirectory = new File(bukkitDirectory, name);
if (worldDirectory.exists() && worldDirectory.isDirectory())
{
return new FakeWorld(worldDirectory.getName(), World.Environment.NORMAL);
}
return null;
}
public void beforeSettings()
{
if (!ess.getDataFolder().exists())
{
ess.getDataFolder().mkdirs();
}
moveWorthValuesToWorthYml();
}
public void afterSettings()
{
sanitizeAllUserFilenames();
updateUsersToNewDefaultHome();
moveUsersDataToUserdataFolder();
convertWarps();
}
}

View File

@@ -1,89 +0,0 @@
package com.earth2me.essentials;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ExecuteTimer
{
private final transient List<ExecuteRecord> times;
private final transient DecimalFormat decimalFormat = new DecimalFormat("#0.000", DecimalFormatSymbols.getInstance(Locale.US));
public ExecuteTimer()
{
times = new ArrayList<ExecuteRecord>();
}
public void start()
{
times.clear();
mark("start");
}
public void mark(final String label)
{
if (!times.isEmpty() || "start".equals(label))
{
times.add(new ExecuteRecord(label, System.nanoTime()));
}
}
public String end()
{
final StringBuilder output = new StringBuilder();
output.append("execution time: ");
String mark;
long time0 = 0;
long time1 = 0;
long time2 = 0;
double duration;
for (ExecuteRecord pair : times)
{
mark = (String)pair.getMark();
time2 = (Long)pair.getTime();
if (time1 > 0)
{
duration = (time2 - time1)/1000000.0;
output.append(mark).append(": ").append(decimalFormat.format(duration)).append("ms - ");
}
else
{
time0 = time2;
}
time1 = time2;
}
duration = (time1 - time0)/1000000.0;
output.append("Total: ").append(decimalFormat.format(duration)).append("ms");
times.clear();
return output.toString();
}
static private class ExecuteRecord
{
private final String mark;
private final long time;
public ExecuteRecord(final String mark, final long time)
{
this.mark = mark;
this.time = time;
}
public String getMark()
{
return mark;
}
public long getTime()
{
return time;
}
}
}

View File

@@ -1,587 +1,395 @@
package com.earth2me.essentials.craftbukkit;
package com.earth2me.essentials;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.BlockChangeDelegate;
import org.bukkit.Chunk;
import org.bukkit.ChunkSnapshot;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.TreeType;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Boat;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.LightningStrike;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.entity.PoweredMinecart;
import org.bukkit.entity.StorageMinecart;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.Vector;
public class FakeWorld implements World
{
private final String name;
private final Environment env;
public FakeWorld(String string, Environment environment)
FakeWorld(String string, Environment environment)
{
this.name = string;
this.env = environment;
}
@Override
public Block getBlockAt(int i, int i1, int i2)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Block getBlockAt(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getBlockTypeIdAt(int i, int i1, int i2)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getBlockTypeIdAt(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getHighestBlockYAt(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getHighestBlockYAt(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Chunk getChunkAt(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Chunk getChunkAt(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Chunk getChunkAt(Block block)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isChunkLoaded(Chunk chunk)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Chunk[] getLoadedChunks()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void loadChunk(Chunk chunk)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isChunkLoaded(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void loadChunk(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean loadChunk(int i, int i1, boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean unloadChunk(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean unloadChunk(int i, int i1, boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean unloadChunk(int i, int i1, boolean bln, boolean bln1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean unloadChunkRequest(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean unloadChunkRequest(int i, int i1, boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean regenerateChunk(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean refreshChunk(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Item dropItem(Location lctn, ItemStack is)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Item dropItemNaturally(Location lctn, ItemStack is)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Arrow spawnArrow(Location lctn, Vector vector, float f, float f1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean generateTree(Location lctn, TreeType tt)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean generateTree(Location lctn, TreeType tt, BlockChangeDelegate bcd)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Minecart spawnMinecart(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public StorageMinecart spawnStorageMinecart(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public PoweredMinecart spawnPoweredMinecart(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public Boat spawnBoat(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public LivingEntity spawnCreature(Location lctn, CreatureType ct)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public LightningStrike strikeLightning(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public LightningStrike strikeLightningEffect(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Entity> getEntities()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<LivingEntity> getLivingEntities()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Player> getPlayers()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getName()
{
return name;
}
@Override
public long getId()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public Location getSpawnLocation()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean setSpawnLocation(int i, int i1, int i2)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getTime()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setTime(long l)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getFullTime()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setFullTime(long l)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasStorm()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setStorm(boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getWeatherDuration()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setWeatherDuration(int i)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isThundering()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setThundering(boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getThunderDuration()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setThunderDuration(int i)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Environment getEnvironment()
{
return env;
}
@Override
public long getSeed()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getPVP()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setPVP(boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void save()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean createExplosion(double d, double d1, double d2, float f)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean createExplosion(Location lctn, float f)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ChunkGenerator getGenerator()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<BlockPopulator> getPopulators()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void playEffect(Location lctn, Effect effect, int i)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void playEffect(Location lctn, Effect effect, int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean createExplosion(double d, double d1, double d2, float f, boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean createExplosion(Location lctn, float f, boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T extends Entity> T spawn(Location lctn, Class<T> type) throws IllegalArgumentException
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ChunkSnapshot getEmptyChunkSnapshot(int i, int i1, boolean bln, boolean bln1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setSpawnFlags(boolean bln, boolean bln1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getAllowAnimals()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getAllowMonsters()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public UUID getUID()
{
return UUID.randomUUID();
}
@Override
public Block getHighestBlockAt(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Block getHighestBlockAt(Location lctn)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Biome getBiome(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public double getTemperature(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public double getHumidity(int i, int i1)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean unloadChunk(Chunk chunk)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getMaxHeight()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getKeepSpawnInMemory()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setKeepSpawnInMemory(boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isAutoSave()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setAutoSave(boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Difficulty getDifficulty()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setDifficulty(Difficulty difficulty)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getSeaLevel()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public File getWorldFolder()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T extends Entity> Collection<T> getEntitiesByClass(Class<T>... types)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public WorldType getWorldType()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void sendPluginMessage(Plugin plugin, String string, byte[] bytes)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Set<String> getListeningPluginChannels()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean canGenerateStructures()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getTicksPerAnimalSpawns()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setTicksPerAnimalSpawns(int i)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getTicksPerMonsterSpawns()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setTicksPerMonsterSpawns(int i)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T extends Entity> Collection<T> getEntitiesByClass(Class<T> type)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Collection<Entity> getEntitiesByClasses(Class<?>... types)
{
throw new UnsupportedOperationException("Not supported yet.");
}
}

View File

@@ -1,177 +0,0 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.II18n;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class I18n implements II18n
{
private static I18n instance;
private static final String MESSAGES = "messages";
private final transient Locale defaultLocale = Locale.getDefault();
private transient Locale currentLocale = defaultLocale;
private transient ResourceBundle customBundle;
private transient ResourceBundle localeBundle;
private final transient ResourceBundle defaultBundle;
private final transient Map<String, MessageFormat> messageFormatCache = new HashMap<String, MessageFormat>();
private final transient IEssentials ess;
public I18n(final IEssentials ess)
{
this.ess = ess;
customBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
localeBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale);
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH);
}
public void onEnable()
{
instance = this;
}
public void onDisable()
{
instance = null;
}
@Override
public Locale getCurrentLocale()
{
return currentLocale;
}
public String translate(final String string)
{
try
{
try
{
return customBundle.getString(string);
}
catch (MissingResourceException ex)
{
return localeBundle.getString(string);
}
}
catch (MissingResourceException ex)
{
Logger.getLogger("Minecraft").log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString()), ex);
return defaultBundle.getString(string);
}
}
public static String _(final String string, final Object... objects)
{
if (instance == null) {
return "";
}
if (objects.length == 0)
{
return instance.translate(string);
}
else
{
return instance.format(string, objects);
}
}
public String format(final String string, final Object... objects)
{
final String format = translate(string);
MessageFormat messageFormat = messageFormatCache.get(format);
if (messageFormat == null)
{
messageFormat = new MessageFormat(format);
messageFormatCache.put(format, messageFormat);
}
return messageFormat.format(objects);
}
public void updateLocale(final String loc)
{
if (loc == null || loc.isEmpty())
{
return;
}
final String[] parts = loc.split("[_\\.]");
if (parts.length == 1)
{
currentLocale = new Locale(parts[0]);
}
if (parts.length == 2)
{
currentLocale = new Locale(parts[0], parts[1]);
}
if (parts.length == 3)
{
currentLocale = new Locale(parts[0], parts[1], parts[2]);
}
Logger.getLogger("Minecraft").log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale);
}
public static String capitalCase(final String input)
{
return input == null || input.length() == 0
? input
: input.toUpperCase(Locale.ENGLISH).charAt(0)
+ input.toLowerCase(Locale.ENGLISH).substring(1);
}
private static class FileResClassLoader extends ClassLoader
{
private final transient File dataFolder;
public FileResClassLoader(final ClassLoader classLoader, final IEssentials ess)
{
super(classLoader);
this.dataFolder = ess.getDataFolder();
}
@Override
public URL getResource(final String string)
{
final File file = new File(dataFolder, string);
if (file.exists())
{
try
{
return file.toURI().toURL();
}
catch (MalformedURLException ex)
{
}
}
return super.getResource(string);
}
@Override
public InputStream getResourceAsStream(final String string)
{
final File file = new File(dataFolder, string);
if (file.exists())
{
try
{
return new FileInputStream(file);
}
catch (FileNotFoundException ex)
{
}
}
return super.getResourceAsStream(string);
}
}
}

View File

@@ -0,0 +1,5 @@
package com.earth2me.essentials;
public interface IConf {
public void reloadConfig();
}

View File

@@ -0,0 +1,68 @@
package com.earth2me.essentials;
import com.earth2me.essentials.register.payment.Methods;
import java.io.File;
import java.util.List;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.scheduler.CraftScheduler;
import org.bukkit.plugin.PluginDescriptionFile;
public interface IEssentials
{
void addReloadListener(IConf listener);
void reload();
boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath);
User getUser(Object base);
User getOfflineUser(String name);
World getWorld(String name);
int broadcastMessage(String name, String message);
Settings getSettings();
CraftScheduler getScheduler();
String[] getMotd(CommandSender sender, String def);
String[] getLines(CommandSender sender, String node, String def);
Jail getJail();
Warps getWarps();
Worth getWorth();
Backup getBackup();
Spawn getSpawn();
void loadBanList();
public boolean isRegisterFallbackEnabled();
public Methods getPaymentMethod();
Server getServer();
File getDataFolder();
PluginDescriptionFile getDescription();
int scheduleAsyncDelayedTask(Runnable run);
int scheduleSyncDelayedTask(Runnable run);
int scheduleSyncRepeatingTask(final Runnable run, long delay, long period);
List<String> getBans();
List<String> getBannedIps();
}

View File

@@ -0,0 +1,9 @@
package com.earth2me.essentials;
import org.bukkit.command.CommandSender;
public interface IReplyTo {
public void setReplyTo(CommandSender user);
public CommandSender getReplyTo();
}

View File

@@ -0,0 +1,51 @@
package com.earth2me.essentials;
import com.earth2me.essentials.commands.IEssentialsCommand;
import java.net.InetSocketAddress;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;
public interface IUser
{
int getHealth();
Location getLocation();
boolean isOnline();
void sendMessage(String string);
long getLastTeleportTimestamp();
boolean isAuthorized(String node);
boolean isAuthorized(IEssentialsCommand cmd);
void setLastTeleportTimestamp(long time);
Location getLastLocation();
Player getBase();
double getMoney();
void takeMoney(double value);
PlayerInventory getInventory();
void updateInventory();
String getGroup();
void setLastLocation();
Location getHome(Location location);
String getName();
InetSocketAddress getAddress();
String getDisplayName();
}

View File

@@ -0,0 +1,192 @@
package com.earth2me.essentials;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.entity.Item;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
/*
* This class can be removed when
* https://github.com/Bukkit/CraftBukkit/pull/193
* is accepted to CraftBukkit
*/
public final class InventoryWorkaround
{
private InventoryWorkaround()
{
}
public static int first(Inventory ci, ItemStack item, boolean forceDurability, boolean forceAmount)
{
return next(ci, item, 0, forceDurability, forceAmount);
}
public static int next(Inventory ci, ItemStack item, int start, boolean forceDurability, boolean forceAmount)
{
ItemStack[] inventory = ci.getContents();
for (int i = start; i < inventory.length; i++)
{
ItemStack cItem = inventory[i];
if (cItem == null)
{
continue;
}
if (item.getTypeId() == cItem.getTypeId() && (!forceAmount || item.getAmount() == cItem.getAmount()) && (!forceDurability || cItem.getDurability() == item.getDurability()))
{
return i;
}
}
return -1;
}
public static HashMap<Integer, ItemStack> removeItem(Inventory ci, boolean forceDurability, ItemStack... items)
{
HashMap<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
// TODO: optimization
for (int i = 0; i < items.length; i++)
{
ItemStack item = items[i];
if (item == null)
{
continue;
}
int toDelete = item.getAmount();
while (true)
{
// Bail when done
if (toDelete <= 0)
{
break;
}
// get first Item, ignore the amount
int first = first(ci, item, forceDurability, false);
// Drat! we don't have this type in the inventory
if (first == -1)
{
item.setAmount(toDelete);
leftover.put(i, item);
break;
}
else
{
ItemStack itemStack = ci.getItem(first);
int amount = itemStack.getAmount();
if (amount <= toDelete)
{
toDelete -= amount;
// clear the slot, all used up
ci.clear(first);
}
else
{
// split the stack and store
itemStack.setAmount(amount - toDelete);
ci.setItem(first, itemStack);
toDelete = 0;
}
}
}
}
return leftover;
}
public static boolean containsItem(Inventory ci, boolean forceDurability, ItemStack... items)
{
HashMap<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
// TODO: optimization
// combine items
ItemStack[] combined = new ItemStack[items.length];
for (int i = 0; i < items.length; i++)
{
if (items[i] == null)
{
continue;
}
for (int j = 0; j < combined.length; j++)
{
if (combined[j] == null)
{
combined[j] = new ItemStack(items[i].getType(), items[i].getAmount(), items[i].getDurability());
break;
}
if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()))
{
combined[j].setAmount(combined[j].getAmount() + items[i].getAmount());
break;
}
}
}
for (int i = 0; i < combined.length; i++)
{
ItemStack item = combined[i];
if (item == null)
{
continue;
}
int mustHave = item.getAmount();
int position = 0;
while (true)
{
// Bail when done
if (mustHave <= 0)
{
break;
}
int slot = next(ci, item, position, forceDurability, false);
// Drat! we don't have this type in the inventory
if (slot == -1)
{
leftover.put(i, item);
break;
}
else
{
ItemStack itemStack = ci.getItem(slot);
int amount = itemStack.getAmount();
if (amount <= mustHave)
{
mustHave -= amount;
}
else
{
mustHave = 0;
}
position = slot + 1;
}
}
}
return leftover.isEmpty();
}
public static Item[] dropItem(Location loc, ItemStack itm)
{
int maxStackSize = itm.getType().getMaxStackSize();
int stacks = itm.getAmount() / maxStackSize;
int leftover = itm.getAmount() % maxStackSize;
Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)];
for (int i = 0; i < stacks; i++) {
itemStacks[i] = loc.getWorld().dropItem(loc, new ItemStack(itm.getType(), maxStackSize, itm.getDurability()));
}
if (leftover > 0) {
itemStacks[stacks] = loc.getWorld().dropItem(loc, new ItemStack(itm.getType(), leftover, itm.getDurability()));
}
return itemStacks;
}
}

View File

@@ -1,100 +1,114 @@
package com.earth2me.essentials;
import com.earth2me.essentials.storage.ManagedFile;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.IItemDb;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.perm.Permissions;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import lombok.Cleanup;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.logging.Logger;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class ItemDb implements IItemDb
public final class ItemDb
{
private final transient IEssentials ess;
public ItemDb(final IEssentials ess)
private ItemDb()
{
this.ess = ess;
file = new ManagedFile("items.csv", ess);
}
private final transient Map<String, Long> items = new HashMap<String, Long>();
private final transient ManagedFile file;
private static final Pattern SPLIT = Pattern.compile("[^a-zA-Z0-9]");
private final static Logger logger = Logger.getLogger("Minecraft");
private static Map<String, Integer> items = new HashMap<String, Integer>();
private static Map<String, Short> durabilities = new HashMap<String, Short>();
@Override
public void onReload()
public static void load(File folder, String fname) throws IOException
{
final List<String> lines = file.getLines();
folder.mkdirs();
File file = new File(folder, fname);
if (lines.isEmpty())
if (!file.exists())
{
return;
file.createNewFile();
InputStream res = ItemDb.class.getResourceAsStream("/items.csv");
FileWriter tx = null;
try
{
tx = new FileWriter(file);
for (int i = 0; (i = res.read()) > 0;)
{
tx.write(i);
}
tx.flush();
}
finally
{
try
{
res.close();
}
catch (Exception ex)
{
}
try
{
if (tx != null)
{
tx.close();
}
}
catch (Exception ex)
{
}
}
}
items.clear();
for (String line : lines)
BufferedReader rx = new BufferedReader(new FileReader(file));
try
{
line = line.trim();
if (line.length() > 0 && line.charAt(0) == '#')
items.clear();
for (int i = 0; rx.ready(); i++)
{
continue;
try
{
String line = rx.readLine().trim().toLowerCase();
if (line.startsWith("#"))
{
continue;
}
String[] parts = line.split("[^a-z0-9]");
if (parts.length < 2)
{
continue;
}
int numeric = Integer.parseInt(parts[1]);
durabilities.put(parts[0].toLowerCase(), parts.length > 2 && !parts[2].equals("0") ? Short.parseShort(parts[2]) : 0);
items.put(parts[0].toLowerCase(), numeric);
}
catch (Exception ex)
{
logger.warning(Util.format("parseError", fname, i));
}
}
final String[] parts = SPLIT.split(line);
if (parts.length < 2)
{
continue;
}
final long numeric = Integer.parseInt(parts[1]);
final long durability = parts.length > 2 && !(parts[2].length() == 1 && parts[2].charAt(0) == '0') ? Short.parseShort(parts[2]) : 0;
items.put(parts[0].toLowerCase(Locale.ENGLISH), numeric | (durability << 32));
}
finally
{
rx.close();
}
}
public ItemStack get(final String id, final IUser user) throws Exception
public static ItemStack get(String id, int quantity) throws Exception
{
final ItemStack stack = get(id.toLowerCase(Locale.ENGLISH));
@Cleanup
com.earth2me.essentials.api.ISettings settings = ess.getSettings();
settings.acquireReadLock();
final int defaultStackSize = settings.getData().getGeneral().getDefaultStacksize();
if (defaultStackSize > 0)
{
stack.setAmount(defaultStackSize);
}
else
{
final int oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize();
if (oversizedStackSize > 0 && Permissions.OVERSIZEDSTACKS.isAuthorized(user))
{
stack.setAmount(oversizedStackSize);
}
}
return stack;
}
public ItemStack get(final String id, final int quantity) throws Exception
{
final ItemStack retval = get(id.toLowerCase(Locale.ENGLISH));
ItemStack retval = get(id.toLowerCase());
retval.setAmount(quantity);
return retval;
}
public ItemStack get(final String id) throws Exception
public static ItemStack get(String id) throws Exception
{
int itemid = 0;
String itemname = null;
@@ -110,43 +124,37 @@ public class ItemDb implements IItemDb
}
else if (id.matches("^[^:+',;.]+[:+',;.]\\d+$"))
{
itemname = id.split("[:+',;.]")[0].toLowerCase(Locale.ENGLISH);
itemname = id.split("[:+',;.]")[0].toLowerCase();
metaData = Short.parseShort(id.split("[:+',;.]")[1]);
}
else
else
{
itemname = id.toLowerCase(Locale.ENGLISH);
itemname = id.toLowerCase();
}
if (itemname != null)
{
if (items.containsKey(itemname))
{
long item = items.get(itemname);
itemid = (int)(item & 0xffffffffL);
if (metaData == 0)
itemid = items.get(itemname);
if (durabilities.containsKey(itemname) && metaData == 0)
{
metaData = (short)((item >> 32) & 0xffffL);
metaData = durabilities.get(itemname);
}
}
else if (Material.getMaterial(itemname) != null)
{
itemid = Material.getMaterial(itemname).getId();
metaData = 0;
}
else
{
throw new Exception(_("unknownItemName", id));
throw new Exception(Util.format("unknownItemName", id));
}
}
final Material mat = Material.getMaterial(itemid);
Material mat = Material.getMaterial(itemid);
if (mat == null)
{
throw new Exception(_("unknownItemId", itemid));
throw new Exception(Util.format("unknownItemId", itemid));
}
final ItemStack retval = new ItemStack(mat);
retval.setAmount(mat.getMaxStackSize());
ItemStack retval = new ItemStack(mat);
retval.setAmount(Essentials.getStatic().getSettings().getDefaultStackSize());
retval.setDurability(metaData);
return retval;
}

View File

@@ -0,0 +1,94 @@
package com.earth2me.essentials;
import java.io.File;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPlaceEvent;
public class Jail extends BlockListener implements IConf
{
private static final Logger logger = Logger.getLogger("Minecraft");
private final EssentialsConf config;
private final IEssentials ess;
public Jail(IEssentials ess)
{
this.ess = ess;
config = new EssentialsConf(new File(ess.getDataFolder(), "jail.yml"));
config.load();
}
public void setJail(Location loc, String jailName) throws Exception
{
config.setProperty(jailName.toLowerCase(), loc);
config.save();
}
public Location getJail(String jailName) throws Exception
{
if (config.getProperty(jailName.toLowerCase()) == null)
{
throw new Exception(Util.i18n("jailNotExist"));
}
Location loc = config.getLocation(jailName.toLowerCase(), ess.getServer());
return loc;
}
public void sendToJail(User user, String jail) throws Exception
{
user.getTeleport().now(getJail(jail));
user.setJail(jail);
}
public void delJail(String jail) throws Exception
{
config.removeProperty(jail.toLowerCase());
config.save();
}
public List<String> getJails() throws Exception
{
return config.getKeys(null);
}
public void reloadConfig()
{
config.load();
}
@Override
public void onBlockBreak(BlockBreakEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
@Override
public void onBlockPlace(BlockPlaceEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
@Override
public void onBlockDamage(BlockDamageEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
}

View File

@@ -0,0 +1,25 @@
package com.earth2me.essentials;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;
public class JailPlayerListener extends PlayerListener
{
private final IEssentials ess;
public JailPlayerListener(IEssentials parent)
{
this.ess = parent;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event)
{
User user = ess.getUser(event.getPlayer());
if (user.isJailed())
{
event.setCancelled(true);
}
}
}

View File

@@ -1,301 +0,0 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.IJails;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.storage.AsyncStorageObjectHolder;
import java.io.File;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import lombok.Cleanup;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.plugin.PluginManager;
public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Jails> implements IJails
{
private static final transient Logger LOGGER = Bukkit.getLogger();
public Jails(final IEssentials ess)
{
super(ess, com.earth2me.essentials.settings.Jails.class);
onReload();
registerListeners();
}
private void registerListeners()
{
final PluginManager pluginManager = ess.getServer().getPluginManager();
final JailBlockListener blockListener = new JailBlockListener();
final JailPlayerListener playerListener = new JailPlayerListener();
pluginManager.registerEvents(blockListener, ess);
pluginManager.registerEvents(playerListener, ess);
}
@Override
public File getStorageFile()
{
return new File(ess.getDataFolder(), "jail.yml");
}
@Override
public Location getJail(final String jailName) throws Exception
{
acquireReadLock();
try
{
if (getData().getJails() == null || jailName == null
|| !getData().getJails().containsKey(jailName.toLowerCase(Locale.ENGLISH)))
{
throw new Exception(_("jailNotExist"));
}
Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH)).getBukkitLocation();
if (loc == null || loc.getWorld() == null)
{
throw new Exception(_("jailNotExist"));
}
return loc;
}
finally
{
unlock();
}
}
@Override
public Collection<String> getList() throws Exception
{
acquireReadLock();
try
{
if (getData().getJails() == null)
{
return Collections.emptyList();
}
return new ArrayList<String>(getData().getJails().keySet());
}
finally
{
unlock();
}
}
@Override
public void removeJail(final String jail) throws Exception
{
acquireWriteLock();
try
{
if (getData().getJails() == null)
{
return;
}
getData().getJails().remove(jail.toLowerCase(Locale.ENGLISH));
}
finally
{
unlock();
}
}
@Override
public void sendToJail(final IUser user, final String jail) throws Exception
{
acquireReadLock();
try
{
if (!(user.isOnline()))
{
Location loc = getJail(jail);
user.getTeleport().now(loc, false, TeleportCause.COMMAND);
}
user.acquireWriteLock();
try
{
user.getData().setJail(jail);
}
finally
{
unlock();
}
}
finally
{
unlock();
}
}
@Override
public void setJail(final String jailName, final Location loc) throws Exception
{
acquireWriteLock();
try
{
if (getData().getJails() == null)
{
getData().setJails(new HashMap<String, com.earth2me.essentials.storage.Location>());
}
getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), new com.earth2me.essentials.storage.Location(loc));
}
finally
{
unlock();
}
}
private class JailBlockListener implements Listener
{
@EventHandler(priority = EventPriority.LOW)
public void onBlockBreak(final BlockBreakEvent event)
{
@Cleanup
final IUser user = ess.getUser(event.getPlayer());
user.acquireReadLock();
if (user.getData().isJailed())
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockPlace(final BlockPlaceEvent event)
{
@Cleanup
final IUser user = ess.getUser(event.getPlayer());
user.acquireReadLock();
if (user.getData().isJailed())
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockDamage(final BlockDamageEvent event)
{
@Cleanup
final IUser user = ess.getUser(event.getPlayer());
user.acquireReadLock();
if (user.getData().isJailed())
{
event.setCancelled(true);
}
}
}
private class JailPlayerListener implements Listener
{
@EventHandler(priority = EventPriority.LOW)
public void onPlayerInteract(final PlayerInteractEvent event)
{
@Cleanup
final IUser user = ess.getUser(event.getPlayer());
user.acquireReadLock();
if (user.getData().isJailed())
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerRespawn(final PlayerRespawnEvent event)
{
@Cleanup
final IUser user = ess.getUser(event.getPlayer());
user.acquireReadLock();
if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty())
{
return;
}
try
{
event.setRespawnLocation(getJail(user.getData().getJail()));
}
catch (Exception ex)
{
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
}
else
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerTeleport(final PlayerTeleportEvent event)
{
@Cleanup
final IUser user = ess.getUser(event.getPlayer());
user.acquireReadLock();
if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty())
{
return;
}
try
{
event.setTo(getJail(user.getData().getJail()));
}
catch (Exception ex)
{
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
}
else
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
}
}
user.sendMessage(_("jailMessage"));
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerJoin(final PlayerJoinEvent event)
{
@Cleanup
final IUser user = ess.getUser(event.getPlayer());
user.acquireReadLock();
if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty())
{
return;
}
try
{
sendToJail(user, user.getData().getJail());
}
catch (Exception ex)
{
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
}
else
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
}
}
user.sendMessage(_("jailMessage"));
}
}
}

View File

@@ -1,90 +0,0 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.IKits;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.settings.Kit;
import com.earth2me.essentials.storage.AsyncStorageObjectHolder;
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.bukkit.inventory.ItemStack;
public class Kits extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Kits> implements IKits
{
public Kits(final IEssentials ess)
{
super(ess, com.earth2me.essentials.settings.Kits.class);
onReload();
}
@Override
public File getStorageFile() throws IOException
{
return new File(ess.getDataFolder(), "kits.yml");
}
@Override
public Kit getKit(String kitName) throws Exception
{
acquireReadLock();
try
{
if (getData().getKits() == null || kitName == null
|| !getData().getKits().containsKey(kitName.toLowerCase(Locale.ENGLISH)))
{
throw new Exception(_("kitError2"));
}
final Kit kit = getData().getKits().get(kitName.toLowerCase(Locale.ENGLISH));
if (kit == null)
{
throw new Exception(_("kitError2"));
}
return kit;
}
finally
{
unlock();
}
}
@Override
public void sendKit(IUser user, String kitName) throws Exception
{
final Kit kit = getKit(kitName);
sendKit(user, kit);
}
@Override
public void sendKit(IUser user, Kit kit) throws Exception
{
final List<ItemStack> itemList = kit.getItems();
user.giveItems(itemList, true);
}
@Override
public Collection<String> getList() throws Exception
{
acquireReadLock();
try
{
if (getData().getKits() == null)
{
return Collections.emptyList();
}
return new ArrayList<String>(getData().getKits().keySet());
}
finally
{
unlock();
}
}
@Override
public boolean isEmpty()
{
return getData().getKits().isEmpty();
}
}

View File

@@ -1,88 +1,103 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import net.minecraft.server.Entity;
import net.minecraft.server.WorldServer;
import org.bukkit.Server;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.craftbukkit.entity.CraftEntity;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.Player;
public enum Mob
{
CHICKEN("Chicken", Enemies.FRIENDLY, CreatureType.CHICKEN),
COW("Cow", Enemies.FRIENDLY, CreatureType.COW),
CREEPER("Creeper", Enemies.ENEMY, CreatureType.CREEPER),
GHAST("Ghast", Enemies.ENEMY, CreatureType.GHAST),
GIANT("Giant", Enemies.ENEMY, CreatureType.GIANT),
PIG("Pig", Enemies.FRIENDLY, CreatureType.PIG),
PIGZOMB("PigZombie", Enemies.NEUTRAL, CreatureType.PIG_ZOMBIE),
SHEEP("Sheep", Enemies.FRIENDLY, "", CreatureType.SHEEP),
SKELETON("Skeleton", Enemies.ENEMY, CreatureType.SKELETON),
SLIME("Slime", Enemies.ENEMY, CreatureType.SLIME),
SPIDER("Spider", Enemies.ENEMY, CreatureType.SPIDER),
SQUID("Squid", Enemies.FRIENDLY, CreatureType.SQUID),
ZOMBIE("Zombie", Enemies.ENEMY, CreatureType.ZOMBIE),
WOLF("Wolf", Enemies.NEUTRAL, CreatureType.WOLF),
CAVESPIDER("CaveSpider", Enemies.ENEMY, CreatureType.CAVE_SPIDER),
ENDERMAN("Enderman", Enemies.ENEMY, "", CreatureType.ENDERMAN),
SILVERFISH("Silverfish", Enemies.ENEMY, "", CreatureType.SILVERFISH),
ENDERDRAGON("EnderDragon", Enemies.ENEMY, CreatureType.ENDER_DRAGON),
VILLAGER("Villager", Enemies.FRIENDLY, CreatureType.VILLAGER),
BLAZE("Blaze", Enemies.ENEMY, CreatureType.BLAZE),
MUSHROOMCOW("MushroomCow", Enemies.FRIENDLY, CreatureType.MUSHROOM_COW),
MAGMACUBE("MagmaCube", Enemies.ENEMY, CreatureType.MAGMA_CUBE),
SNOWMAN("Snowman", Enemies.FRIENDLY, "", CreatureType.SNOWMAN);
CHICKEN("Chicken", Enemies.FRIENDLY),
COW("Cow", Enemies.FRIENDLY),
CREEPER("Creeper", Enemies.ENEMY),
GHAST("Ghast", Enemies.ENEMY),
GIANT("Giant", "GiantZombie", Enemies.ENEMY),
PIG("Pig", Enemies.FRIENDLY),
PIGZOMB("PigZombie", Enemies.NEUTRAL),
SHEEP("Sheep", Enemies.FRIENDLY, ""),
SKELETON("Skeleton", Enemies.ENEMY),
SLIME("Slime", Enemies.ENEMY),
SPIDER("Spider", Enemies.ENEMY),
SQUID("Squid", Enemies.FRIENDLY),
ZOMBIE("Zombie", Enemies.ENEMY),
MONSTER("Monster", Enemies.ENEMY),
WOLF("Wolf", Enemies.NEUTRAL);
public static final Logger logger = Logger.getLogger("Minecraft");
private Mob(String n, Enemies en, String s, CreatureType type)
private Mob(String n, Enemies en, String s)
{
this.suffix = s;
this.s = s;
this.name = n;
this.craftClass = n;
this.entityClass = n;
this.type = en;
this.bukkitType = type;
}
private Mob(String n, Enemies en, CreatureType type)
private Mob(String n, Enemies en)
{
this.name = n;
this.craftClass = n;
this.entityClass = n;
this.type = en;
this.bukkitType = type;
}
public String suffix = "s";
final public String name;
final public Enemies type;
final private CreatureType bukkitType;
private Mob(String n, String ec, Enemies en)
{
this.name = n;
this.craftClass = n;
this.entityClass = ec;
this.type = en;
}
private Mob(String n, String ec, String cc, Enemies en)
{
this.name = n;
this.entityClass = ec;
this.craftClass = cc;
this.type = en;
}
public String s = "s";
public String name;
public Enemies type;
private String entityClass;
private String craftClass;
private static final Map<String, Mob> hashMap = new HashMap<String, Mob>();
static
{
for (Mob mob : Mob.values())
{
hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob);
hashMap.put(mob.name, mob);
}
}
public static Set<String> getMobList() {
return hashMap.keySet();
}
public LivingEntity spawn(final Player player, final Server server, final Location loc) throws MobException
@SuppressWarnings(
{
final LivingEntity entity = player.getWorld().spawn(loc, (Class<? extends LivingEntity>)this.bukkitType.getEntityClass());
if (entity == null)
"unchecked", "CallToThreadDumpStack"
})
public CraftEntity spawn(Player player, Server server) throws MobException
{
try
{
logger.log(Level.WARNING, _("unableToSpawnMob"));
throw new MobException();
WorldServer world = ((org.bukkit.craftbukkit.CraftWorld)player.getWorld()).getHandle();
Constructor<CraftEntity> craft = (Constructor<CraftEntity>)ClassLoader.getSystemClassLoader().loadClass("org.bukkit.craftbukkit.entity.Craft" + craftClass).getConstructors()[0];
Constructor<Entity> entity = (Constructor<Entity>)ClassLoader.getSystemClassLoader().loadClass("net.minecraft.server.Entity" + entityClass).getConstructors()[0];
return craft.newInstance((CraftServer)server, entity.newInstance(world));
}
catch (Exception ex)
{
logger.log(Level.WARNING, Util.i18n("unableToSpawnMob"), ex);
throw new MobException(ex);
}
return entity;
}
@@ -92,26 +107,26 @@ public enum Mob
NEUTRAL("neutral"),
ENEMY("enemy");
private Enemies(final String type)
private Enemies(String t)
{
this.type = type;
this.type = t;
}
final protected String type;
}
public CreatureType getType()
{
return bukkitType;
}
public static Mob fromName(final String name)
{
return hashMap.get(name.toLowerCase(Locale.ENGLISH));
protected String type;
}
public static class MobException extends Exception
{
private static final long serialVersionUID = 1L;
private MobException(Exception ex)
{
super(ex);
}
}
public static Mob fromName(String n)
{
return hashMap.get(n);
}
}

View File

@@ -0,0 +1,167 @@
/**
* @author SpaceManiac
* @licent MIT
* @origin https://github.com/SpaceManiac/Nether/blob/master/org/innectis/Nether/NetherPortal.java
*/
package com.earth2me.essentials;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.Location;
import org.bukkit.Material;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NetherPortal
{
private Block block;
public NetherPortal(Block b)
{
block = b;
}
public Block getBlock()
{
return block;
}
public void setBlock(Block b)
{
block = b;
}
// Return a random spawnable location
public Location getSpawn()
{
if (block.getWorld().getBlockAt(block.getX() + 1, block.getY(), block.getZ()).getType().equals(Material.PORTAL)
|| block.getWorld().getBlockAt(block.getX() - 1, block.getY(), block.getZ()).getType().equals(Material.PORTAL))
{
// portal is in X direction
return new Location(block.getWorld(), block.getX() + 1,
block.getY(), block.getZ() + 1 - 2 * Math.round(Math.random()));
}
else
{
// portal is in Z direction
return new Location(block.getWorld(), block.getX() + 1 - 2 * Math.round(Math.random()),
block.getY(), block.getZ() + 1);
}
}
// ==============================
// Find a nearby portal within 16 blocks of the given block
// Not guaranteed to be the nearest
public static NetherPortal findPortal(Block dest)
{
World world = dest.getWorld();
// Get list of columns in a circle around the block
ArrayList<Block> columns = new ArrayList<Block>();
for (int x = dest.getX() - 16; x <= dest.getX() + 16; ++x)
{
for (int z = dest.getZ() - 16; z <= dest.getZ() + 16; ++z)
{
int dx = dest.getX() - x, dz = dest.getZ() - z;
if (dx * dx + dz * dz <= 256)
{
columns.add(world.getBlockAt(x, 0, z));
}
}
}
// For each column try to find a portal block
for (Block col : columns)
{
for (int y = 127; y >= 0; --y)
{
Block b = world.getBlockAt(col.getX(), y, col.getZ());
if (b.getType().equals(Material.PORTAL) && Math.abs(dest.getY() - y) <= 16)
{
// Huzzah!
return new NetherPortal(b);
}
}
}
// Nope!
return null;
}
// Create a new portal at the specified block, fudging position if needed
// Will occasionally end up making portals in bad places, but let's hope not
public static NetherPortal createPortal(Block dest)
{
World world = dest.getWorld();
// Try not to spawn within water or lava
Material m = dest.getType();
while (((m.equals(Material.LAVA) || m.equals(Material.WATER) || m.equals(Material.STATIONARY_LAVA)
|| m.equals(Material.STATIONARY_WATER) || m.equals(Material.SAND) || m.equals(Material.GRAVEL))) &&
dest.getY() < 120)
{
dest = world.getBlockAt(dest.getX(), dest.getY() + 4, dest.getZ());
m = dest.getType();
}
// Not too high or too low overall
if (dest.getY() > 120)
{
dest = world.getBlockAt(dest.getX(), 120, dest.getZ());
}
else if (dest.getY() < 8)
{
dest = world.getBlockAt(dest.getX(), 8, dest.getZ());
}
// Create the physical portal
// For now, don't worry about direction
int x = dest.getX(), y = dest.getY(), z = dest.getZ();
Logger.getLogger("Minecraft").log(Level.INFO, Util.format("creatingPortal", x, y, z));
// Clear area around portal
ArrayList<Block> columns = new ArrayList<Block>();
for (int x2 = x - 4; x2 <= x + 4; ++x2)
{
for (int z2 = z - 4; z2 <= z + 4; ++z2)
{
double dx = x + 0.5f - x2, dz = z - z2;
if (dx * dx + dz * dz <= 13)
{
columns.add(world.getBlockAt(x2, 0, z2));
}
}
}
// Clear area around portal
for (Block col : columns)
{
// Stone platform
world.getBlockAt(col.getX(), y - 1, col.getZ()).setType(Material.STONE);
for (int yd = 0; yd < 4; ++yd)
{
world.getBlockAt(col.getX(), y + yd, col.getZ()).setType(Material.AIR);
}
}
// Build obsidian frame
for (int xd = -1; xd < 3; ++xd)
{
for (int yd = -1; yd < 4; ++yd)
{
if (xd == -1 || yd == -1 || xd == 2 || yd == 3)
{
world.getBlockAt(x + xd, y + yd, z).setType(Material.OBSIDIAN);
}
}
}
// Set it alight!
dest.setType(Material.FIRE);
return new NetherPortal(dest);
}
}

View File

@@ -0,0 +1,512 @@
package com.earth2me.essentials;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import org.bukkit.Achievement;
import org.bukkit.Effect;
import org.bukkit.Instrument;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Note;
import org.bukkit.Server;
import org.bukkit.Statistic;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Egg;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Snowball;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.util.Vector;
public class OfflinePlayer implements Player
{
private final String name;
private Location location = new Location(null, 0, 0, 0, 0, 0);
private World world = null;
private UUID uniqueId = UUID.randomUUID();
public OfflinePlayer(String name)
{
this.name = name;
}
public boolean isOnline()
{
return false;
}
public boolean isOp()
{
return false;
}
public void sendMessage(String string)
{
}
public String getDisplayName()
{
return name;
}
public void setDisplayName(String string)
{
}
public void setCompassTarget(Location lctn)
{
}
public InetSocketAddress getAddress()
{
return null;
}
public void kickPlayer(String string)
{
}
public String getName()
{
return name;
}
public PlayerInventory getInventory()
{
return null;
}
public ItemStack getItemInHand()
{
return null;
}
public void setItemInHand(ItemStack is)
{
}
public int getHealth()
{
return 0;
}
public void setHealth(int i)
{
}
public Egg throwEgg()
{
return null;
}
public Snowball throwSnowball()
{
return null;
}
public Arrow shootArrow()
{
return null;
}
public boolean isInsideVehicle()
{
return false;
}
public boolean leaveVehicle()
{
return false;
}
public Vehicle getVehicle()
{
return null;
}
public Location getLocation()
{
return location;
}
public World getWorld()
{
return world;
}
public void setLocation(Location loc)
{
location = loc;
world = loc.getWorld();
}
public void teleportTo(Location lctn)
{
}
public void teleportTo(Entity entity)
{
}
public int getEntityId()
{
return -1;
}
public boolean performCommand(String string)
{
return false;
}
public boolean isPlayer()
{
return false;
}
public int getRemainingAir()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setRemainingAir(int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public int getMaximumAir()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setMaximumAir(int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean isSneaking()
{
return false;
}
public void setSneaking(boolean bln)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void updateInventory()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void chat(String string)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public double getEyeHeight()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public double getEyeHeight(boolean bln)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public List<Block> getLineOfSight(HashSet<Byte> hs, int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public Block getTargetBlock(HashSet<Byte> hs, int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public List<Block> getLastTwoTargetBlocks(HashSet<Byte> hs, int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public int getFireTicks()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public int getMaxFireTicks()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setFireTicks(int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void remove()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public Server getServer()
{
return Essentials.getStatic() == null ? null : Essentials.getStatic().getServer();
}
public Vector getMomentum()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setMomentum(Vector vector)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setVelocity(Vector vector)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public Vector getVelocity()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void damage(int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void damage(int i, Entity entity)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public Location getEyeLocation()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void sendRawMessage(String string) {
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public Location getCompassTarget()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public int getMaximumNoDamageTicks()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setMaximumNoDamageTicks(int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public int getLastDamage()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setLastDamage(int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public int getNoDamageTicks()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setNoDamageTicks(int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean teleport(Location lctn)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean teleport(Entity entity)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public Entity getPassenger()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean setPassenger(Entity entity)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean isEmpty()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean eject()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void saveData()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void loadData()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean isSleeping()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public int getSleepTicks()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public List<Entity> getNearbyEntities(double d, double d1, double d2)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean isDead()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public float getFallDistance()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setFallDistance(float f)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setSleepingIgnored(boolean bln)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean isSleepingIgnored()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void awardAchievement(Achievement a)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void incrementStatistic(Statistic ststc)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void incrementStatistic(Statistic ststc, int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void incrementStatistic(Statistic ststc, Material mtrl)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void incrementStatistic(Statistic ststc, Material mtrl, int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void playNote(Location lctn, byte b, byte b1)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void sendBlockChange(Location lctn, Material mtrl, byte b)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void sendBlockChange(Location lctn, int i, byte b)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void setLastDamageCause(EntityDamageEvent ede)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public EntityDamageEvent getLastDamageCause()
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public void playEffect(Location lctn, Effect effect, int i)
{
throw new UnsupportedOperationException(Util.i18n("notSupportedYet"));
}
public boolean sendChunkChange(Location lctn, int i, int i1, int i2, byte[] bytes)
{
return true;
}
public UUID getUniqueId()
{
return uniqueId;
}
public void playNote(Location lctn, Instrument i, Note note)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public void setPlayerTime(long l, boolean bln)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public long getPlayerTime()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public long getPlayerTimeOffset()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean isPlayerTimeRelative()
{
throw new UnsupportedOperationException("Not supported yet.");
}
public void resetPlayerTime()
{
throw new UnsupportedOperationException("Not supported yet.");
}
}

View File

@@ -0,0 +1,99 @@
package com.earth2me.essentials;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import net.minecraft.server.EntityPlayer;
import net.minecraft.server.IInventory;
import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer;
import org.bukkit.entity.Player;
public class PlayerExtension extends PlayerWrapper
{
protected final IEssentials ess;
public PlayerExtension(Player base, IEssentials ess)
{
super(base);
this.ess = ess;
}
public boolean isBanned()
{
return ess.getBans().contains(getName());
}
public boolean isIpBanned()
{
return ess.getBannedIps().contains(getAddress().getAddress().toString().replace("/", ""));
}
public float getCorrectedYaw()
{
float angle = (getLocation().getYaw() - 90.0f) % 360.0f;
if (angle < 0) {
angle += 360.0f;
}
return angle;
}
public void showInventory(IInventory inventory)
{
getHandle().a(inventory);
}
public void showInventory(CraftInventoryPlayer inventory)
{
showInventory((IInventory)inventory.getInventory());
}
public TargetBlock getTarget()
{
return new TargetBlock(getBase());
}
public String getGroup()
{
try
{
return com.nijikokun.bukkit.Permissions.Permissions.Security.getGroup(getWorld().getName(), getName());
}
catch (Throwable ex)
{
return "default";
}
}
public boolean inGroup(String group)
{
try
{
return com.nijikokun.bukkit.Permissions.Permissions.Security.inGroup(getWorld().getName(), getName(), group);
}
catch (Throwable ex)
{
return false;
}
}
public boolean canBuild()
{
try
{
return isOp() || com.nijikokun.bukkit.Permissions.Permissions.Security.canGroupBuild(getWorld().getName(), getGroup());
}
catch (Throwable ex)
{
return true;
}
}
public EntityPlayer getHandle()
{
return getCraftPlayer().getHandle();
}
public CraftPlayer getCraftPlayer()
{
return (CraftPlayer)base;
}
}

View File

@@ -0,0 +1,563 @@
package com.earth2me.essentials;
import java.net.InetSocketAddress;
import java.util.*;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.inventory.*;
import org.bukkit.util.Vector;
public class PlayerWrapper implements Player
{
protected Player base;
public PlayerWrapper(Player base)
{
this.base = base;
}
public final Player getBase()
{
return base;
}
public final Player setBase(Player base)
{
return this.base = base;
}
@Override
public void setDisplayName(String string)
{
base.setDisplayName(string);
}
@Override
public void setCompassTarget(Location lctn)
{
base.setCompassTarget(lctn);
}
@Override
public InetSocketAddress getAddress()
{
return base.getAddress();
}
@Override
public void kickPlayer(String string)
{
base.kickPlayer(string);
}
@Override
public String getName()
{
return base.getName();
}
@Override
public PlayerInventory getInventory()
{
return base.getInventory();
}
@Override
public ItemStack getItemInHand()
{
return base.getItemInHand();
}
@Override
public void setItemInHand(ItemStack is)
{
base.setItemInHand(is);
}
@Override
public int getHealth()
{
return base.getHealth();
}
@Override
public void setHealth(int i)
{
base.setHealth(i);
}
@Override
public Egg throwEgg()
{
return base.throwEgg();
}
@Override
public Snowball throwSnowball()
{
return base.throwSnowball();
}
@Override
public Arrow shootArrow()
{
return base.shootArrow();
}
@Override
public boolean isInsideVehicle()
{
return base.isInsideVehicle();
}
@Override
public boolean leaveVehicle()
{
return base.leaveVehicle();
}
@Override
public Vehicle getVehicle()
{
return base.getVehicle();
}
@Override
public Location getLocation()
{
return base.getLocation();
}
@Override
public World getWorld()
{
return base.getWorld();
}
@Override
public Server getServer()
{
return base.getServer();
}
@Override
public boolean isOnline()
{
return base.isOnline();
}
@Override
public boolean isOp()
{
return base.isOp();
}
@Override
public boolean teleport(Location lctn)
{
return base.teleport(lctn);
}
@Override
public boolean teleport(Entity entity)
{
return base.teleport(entity);
}
@Override
public void sendMessage(String string)
{
base.sendMessage(string);
}
@Override
public void setVelocity(Vector vector)
{
base.setVelocity(vector);
}
@Override
public Vector getVelocity()
{
return base.getVelocity();
}
@Override
public double getEyeHeight()
{
return base.getEyeHeight();
}
@Override
public double getEyeHeight(boolean bln)
{
return base.getEyeHeight(bln);
}
@Override
public List<Block> getLineOfSight(HashSet<Byte> hs, int i)
{
return base.getLineOfSight(hs, i);
}
@Override
public Block getTargetBlock(HashSet<Byte> hs, int i)
{
return base.getTargetBlock(hs, i);
}
@Override
public List<Block> getLastTwoTargetBlocks(HashSet<Byte> hs, int i)
{
return base.getLastTwoTargetBlocks(hs, i);
}
@Override
public int getFireTicks()
{
return base.getFireTicks();
}
@Override
public int getMaxFireTicks()
{
return base.getMaxFireTicks();
}
@Override
public void setFireTicks(int i)
{
base.setFireTicks(i);
}
@Override
public void remove()
{
base.remove();
}
/**
* This is not deprecated because the underlying method isn't really deprecated; rather, it's just "imperfect". By
* We will continue to use this method even after the underlying CraftBukkit method is changed, so do not deprecate
* it. Chances are Bukkit will also choose to un-deprecate this method at some point.
*/
@Override
public void updateInventory()
{
base.updateInventory();
}
@Override
public void chat(String string)
{
base.chat(string);
}
@Override
public boolean isSneaking()
{
return base.isSneaking();
}
@Override
public void setSneaking(boolean bln)
{
base.setSneaking(bln);
}
@Override
public int getEntityId()
{
return base.getEntityId();
}
@Override
public boolean performCommand(String string)
{
return base.performCommand(string);
}
@Override
public int getRemainingAir()
{
return base.getRemainingAir();
}
@Override
public void setRemainingAir(int i)
{
base.setRemainingAir(i);
}
@Override
public int getMaximumAir()
{
return base.getMaximumAir();
}
@Override
public void setMaximumAir(int i)
{
base.setMaximumAir(i);
}
@Override
public String getDisplayName()
{
if (base.getDisplayName() != null)
return base.getDisplayName();
else
return base.getName();
}
@Override
public void damage(int i)
{
base.damage(i);
}
@Override
public void damage(int i, Entity entity)
{
base.damage(i, entity);
}
@Override
public Location getEyeLocation()
{
return base.getEyeLocation();
}
@Override
public void sendRawMessage(String string) {
base.sendRawMessage(string);
}
@Override
public Location getCompassTarget()
{
return base.getCompassTarget();
}
@Override
public int getMaximumNoDamageTicks()
{
return base.getMaximumNoDamageTicks();
}
@Override
public void setMaximumNoDamageTicks(int i)
{
base.setMaximumNoDamageTicks(i);
}
@Override
public int getLastDamage()
{
return base.getLastDamage();
}
@Override
public void setLastDamage(int i)
{
base.setLastDamage(i);
}
@Override
public int getNoDamageTicks()
{
return base.getNoDamageTicks();
}
@Override
public void setNoDamageTicks(int i)
{
base.setNoDamageTicks(i);
}
@Override
public Entity getPassenger()
{
return base.getPassenger();
}
@Override
public boolean setPassenger(Entity entity)
{
return base.setPassenger(entity);
}
@Override
public boolean isEmpty()
{
return base.isEmpty();
}
@Override
public boolean eject()
{
return base.eject();
}
@Override
@Deprecated
public void teleportTo(Location lctn)
{
base.teleportTo(lctn);
}
@Override
@Deprecated
public void teleportTo(Entity entity)
{
base.teleportTo(entity);
}
public void saveData()
{
base.saveData();
}
public void loadData()
{
base.loadData();
}
public boolean isSleeping()
{
return base.isSleeping();
}
public int getSleepTicks()
{
return base.getSleepTicks();
}
public List<Entity> getNearbyEntities(double d, double d1, double d2)
{
return base.getNearbyEntities(d, d1, d2);
}
public boolean isDead()
{
return base.isDead();
}
public float getFallDistance()
{
return base.getFallDistance();
}
public void setFallDistance(float f)
{
base.setFallDistance(f);
}
public void setSleepingIgnored(boolean bln)
{
base.setSleepingIgnored(bln);
}
public boolean isSleepingIgnored()
{
return base.isSleepingIgnored();
}
public void awardAchievement(Achievement a)
{
base.awardAchievement(a);
}
public void incrementStatistic(Statistic ststc)
{
base.incrementStatistic(ststc);
}
public void incrementStatistic(Statistic ststc, int i)
{
base.incrementStatistic(ststc, i);
}
public void incrementStatistic(Statistic ststc, Material mtrl)
{
base.incrementStatistic(ststc, mtrl);
}
public void incrementStatistic(Statistic ststc, Material mtrl, int i)
{
base.incrementStatistic(ststc, mtrl, i);
}
public void playNote(Location lctn, byte b, byte b1)
{
base.playNote(lctn, b, b1);
}
public void sendBlockChange(Location lctn, Material mtrl, byte b)
{
base.sendBlockChange(lctn, mtrl, b);
}
public void sendBlockChange(Location lctn, int i, byte b)
{
base.sendBlockChange(lctn, i, b);
}
public void setLastDamageCause(EntityDamageEvent ede)
{
base.setLastDamageCause(ede);
}
public EntityDamageEvent getLastDamageCause()
{
return base.getLastDamageCause();
}
public void playEffect(Location lctn, Effect effect, int i)
{
base.playEffect(lctn, effect, i);
}
public boolean sendChunkChange(Location lctn, int i, int i1, int i2, byte[] bytes)
{
return base.sendChunkChange(lctn, i, i1, i2, bytes);
}
public UUID getUniqueId()
{
return base.getUniqueId();
}
public void playNote(Location lctn, Instrument i, Note note)
{
base.playNote(lctn, i, note);
}
public void setPlayerTime(long l, boolean bln)
{
base.setPlayerTime(l, bln);
}
public long getPlayerTime()
{
return base.getPlayerTime();
}
public long getPlayerTimeOffset()
{
return base.getPlayerTimeOffset();
}
public boolean isPlayerTimeRelative()
{
return base.isPlayerTimeRelative();
}
public void resetPlayerTime()
{
base.resetPlayerTime();
}
}

View File

@@ -0,0 +1,519 @@
package com.earth2me.essentials;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import com.earth2me.essentials.commands.IEssentialsCommand;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.entity.CreatureType;
import org.bukkit.inventory.ItemStack;
public class Settings implements IConf
{
private final EssentialsConf config;
private final static Logger logger = Logger.getLogger("Minecraft");
public Settings(File dataFolder)
{
config = new EssentialsConf(new File(dataFolder, "config.yml"));
config.setTemplateName("/config.yml");
config.load();
}
public boolean getRespawnAtHome()
{
return config.getBoolean("respawn-at-home", false);
}
public boolean getBedSetsHome()
{
return config.getBoolean("bed-sethome", false);
}
public int getChatRadius()
{
return config.getInt("chat.radius", config.getInt("chat-radius", 0));
}
public double getTeleportDelay()
{
return config.getDouble("teleport-delay", 0);
}
public int getDefaultStackSize()
{
return config.getInt("default-stack-size", 64);
}
public int getStartingBalance()
{
return config.getInt("starting-balance", 0);
}
public boolean getNetherPortalsEnabled()
{
return isNetherEnabled() && config.getBoolean("nether.portals-enabled", false);
}
public boolean isCommandDisabled(final IEssentialsCommand cmd)
{
return isCommandDisabled(cmd.getName());
}
public boolean isCommandDisabled(String label)
{
for (String c : config.getStringList("disabled-commands", new ArrayList<String>(0)))
{
if (!c.equalsIgnoreCase(label)) continue;
return true;
}
return config.getBoolean("disable-" + label.toLowerCase(), false);
}
public boolean isCommandRestricted(IEssentialsCommand cmd)
{
return isCommandRestricted(cmd.getName());
}
public boolean isCommandRestricted(String label)
{
for (String c : config.getStringList("restricted-commands", new ArrayList<String>(0)))
{
if (!c.equalsIgnoreCase(label)) continue;
return true;
}
return config.getBoolean("restrict-" + label.toLowerCase(), false);
}
public boolean isCommandOverridden(String name)
{
List<String> defaultList = new ArrayList<String>(1);
defaultList.add("god");
for (String c : config.getStringList("overridden-commands", defaultList))
{
if (!c.equalsIgnoreCase(name))
continue;
return true;
}
return config.getBoolean("override-" + name.toLowerCase(), false);
}
public double getCommandCost(IEssentialsCommand cmd)
{
return getCommandCost(cmd.getName());
}
public double getCommandCost(String label)
{
double cost = config.getDouble("command-costs." + label, 0.0);
if (cost == 0.0)
cost = config.getDouble("cost-" + label, 0.0);
return cost;
}
public String getCommandPrefix()
{
return config.getString("command-prefix", "");
}
public String getNicknamePrefix()
{
return config.getString("nickname-prefix", "~");
}
public double getTeleportCooldown()
{
return config.getDouble("teleport-cooldown", 60);
}
public double getHealCooldown()
{
return config.getDouble("heal-cooldown", 60);
}
public Object getKit(String name)
{
Map<String, Object> kits = (Map<String, Object>)config.getProperty("kits");
for (Map.Entry<String, Object> entry : kits.entrySet())
{
if (entry.getKey().equalsIgnoreCase(name.replace('.', '_').replace('/', '_'))) {
return entry.getValue();
}
}
return null;
}
public Map<String, Object> getKits()
{
return (Map<String, Object>)config.getProperty("kits");
}
public ChatColor getOperatorColor() throws Exception
{
String colorName = config.getString("ops-name-color", null);
if (colorName == null)
return ChatColor.RED;
if("none".equalsIgnoreCase(colorName) || colorName.isEmpty())
throw new Exception();
try
{
return ChatColor.valueOf(colorName.toUpperCase());
}
catch (IllegalArgumentException ex)
{
}
return ChatColor.getByCode(Integer.parseInt(colorName, 16));
}
public boolean getReclaimSetting()
{
return config.getBoolean("reclaim-onlogout", true);
}
public String getNetherName()
{
return config.getString("nether.folder", "nether");
}
public boolean isNetherEnabled()
{
return config.getBoolean("nether.enabled", true);
}
public int getSpawnMobLimit()
{
return config.getInt("spawnmob-limit", 10);
}
public boolean showNonEssCommandsInHelp()
{
return config.getBoolean("non-ess-in-help", true);
}
public Map<String, Boolean> getEpSettings()
{
Map<String, Boolean> epSettings = new HashMap<String, Boolean>();
epSettings.put("protect.protect.signs", config.getBoolean("protect.protect.signs", true));
epSettings.put("protect.protect.rails", config.getBoolean("protect.protect.rails", true));
epSettings.put("protect.protect.block-below", config.getBoolean("protect.protect.block-below", true));
epSettings.put("protect.protect.prevent-block-on-rails", config.getBoolean("protect.protect.prevent-block-on-rails", false));
return epSettings;
}
public Map<String, String> getEpDBSettings()
{
Map<String, String> epSettings = new HashMap<String, String>();
epSettings.put("protect.datatype", config.getString("protect.datatype", "sqlite"));
epSettings.put("protect.username", config.getString("protect.username", "root"));
epSettings.put("protect.password", config.getString("protect.password", "root"));
epSettings.put("protect.mysqlDb", config.getString("protect.mysqlDb", "jdbc:mysql://localhost:3306/minecraft"));
return epSettings;
}
public List<Integer> getEpAlertOnPlacement()
{
final List<Integer> epAlertPlace = new ArrayList<Integer>();
for (String itemName : config.getString("protect.alert.on-placement", "").split(",")) {
itemName = itemName.trim();
if (itemName.isEmpty()) {
continue;
}
ItemStack is;
try {
is = ItemDb.get(itemName);
epAlertPlace.add(is.getTypeId());
} catch (Exception ex) {
logger.log(Level.SEVERE, Util.format("unknownItemInList", itemName, "alert.on-placement"));
}
}
return epAlertPlace;
}
public List<Integer> getEpAlertOnUse()
{
final List<Integer> epAlertUse = new ArrayList<Integer>();
for (String itemName : config.getString("protect.alert.on-use", "").split(",")) {
itemName = itemName.trim();
if (itemName.isEmpty()) {
continue;
}
ItemStack is;
try {
is = ItemDb.get(itemName);
epAlertUse.add(is.getTypeId());
} catch (Exception ex) {
logger.log(Level.SEVERE, Util.format("unknownItemInList", itemName, "alert.on-use"));
}
}
return epAlertUse;
}
public List<Integer> getEpAlertOnBreak()
{
final List<Integer> epAlertPlace = new ArrayList<Integer>();
for (String itemName : config.getString("protect.alert.on-break", "").split(",")) {
itemName = itemName.trim();
if (itemName.isEmpty()) {
continue;
}
ItemStack is;
try {
is = ItemDb.get(itemName);
epAlertPlace.add(is.getTypeId());
} catch (Exception ex) {
logger.log(Level.SEVERE, Util.format("unknownItemInList", itemName, "alert.on-break"));
}
}
return epAlertPlace;
}
public List<Integer> epBlackListPlacement()
{
final List<Integer> epBlacklistPlacement = new ArrayList<Integer>();
for (String itemName : config.getString("protect.blacklist.placement", "").split(",")) {
itemName = itemName.trim();
if (itemName.isEmpty()) {
continue;
}
ItemStack is;
try {
is = ItemDb.get(itemName);
epBlacklistPlacement.add(is.getTypeId());
} catch (Exception ex) {
logger.log(Level.SEVERE, Util.format("unknownItemInList", itemName, "blacklist.placement"));
}
}
return epBlacklistPlacement;
}
public List<Integer> epBlackListUsage()
{
final List<Integer> epBlackListUsage = new ArrayList<Integer>();
for (String itemName : config.getString("protect.blacklist.usage", "").split(",")) {
itemName = itemName.trim();
if (itemName.isEmpty()) {
continue;
}
ItemStack is;
try {
is = ItemDb.get(itemName);
epBlackListUsage.add(is.getTypeId());
} catch (Exception ex) {
logger.log(Level.SEVERE, Util.format("unknownItemInList", itemName, "blacklist.usage"));
}
}
return epBlackListUsage;
}
public Map<String, Boolean> getEpGuardSettings()
{
final Map<String, Boolean> epSettings = new HashMap<String, Boolean>();
epSettings.put("protect.prevent.lava-flow", config.getBoolean("protect.prevent.lava-flow", false));
epSettings.put("protect.prevent.water-flow", config.getBoolean("protect.prevent.water-flow", false));
epSettings.put("protect.prevent.water-bucket-flow", config.getBoolean("protect.prevent.water-bucket-flow", false));
epSettings.put("protect.prevent.fire-spread", config.getBoolean("protect.prevent.fire-spread", true));
epSettings.put("protect.prevent.flint-fire", config.getBoolean("protect.prevent.flint-fire", false));
epSettings.put("protect.prevent.portal-creation", config.getBoolean("protect.prevent.portal-creation", false));
epSettings.put("protect.prevent.lava-fire-spread", config.getBoolean("protect.prevent.lava-fire-spread", true));
epSettings.put("protect.prevent.tnt-explosion", config.getBoolean("protect.prevent.tnt-explosion", false));
epSettings.put("protect.prevent.creeper-explosion", config.getBoolean("protect.prevent.creeper-explosion", false));
epSettings.put("protect.prevent.creeper-playerdamage", config.getBoolean("protect.prevent.creeper-playerdamage", false));
epSettings.put("protect.prevent.creeper-blockdamage", config.getBoolean("protect.prevent.creeper-blockdamage", false));
epSettings.put("protect.prevent.entitytarget", config.getBoolean("protect.prevent.entitytarget", false));
for (CreatureType ct : CreatureType.values()) {
final String name = ct.toString().toLowerCase();
epSettings.put("protect.prevent.spawn."+name, config.getBoolean("protect.prevent.spawn."+name, false));
}
epSettings.put("protect.prevent.lightning-fire-spread", config.getBoolean("protect.prevent.lightning-fire-spread", true));
return epSettings;
}
public Map<String, Boolean> getEpPlayerSettings()
{
final Map<String, Boolean> epPlayerSettings = new HashMap<String, Boolean>();
epPlayerSettings.put("protect.disable.fall", config.getBoolean("protect.disable.fall", false));
epPlayerSettings.put("protect.disable.pvp", config.getBoolean("protect.disable.pvp", false));
epPlayerSettings.put("protect.disable.drown", config.getBoolean("protect.disable.drown", false));
epPlayerSettings.put("protect.disable.suffocate", config.getBoolean("protect.disable.suffocate", false));
epPlayerSettings.put("protect.disable.lavadmg", config.getBoolean("protect.disable.lavadmg", false));
epPlayerSettings.put("protect.disable.projectiles", config.getBoolean("protect.disable.projectiles", false));
epPlayerSettings.put("protect.disable.contactdmg", config.getBoolean("protect.disable.contactdmg", false));
epPlayerSettings.put("protect.disable.firedmg", config.getBoolean("protect.disable.firedmg", false));
epPlayerSettings.put("protect.disable.build", config.getBoolean("protect.disable.build", false));
epPlayerSettings.put("protect.disable.lightning", config.getBoolean("protect.disable.lightning", false));
epPlayerSettings.put("protect.disable.weather.lightning", config.getBoolean("protect.disable.weather.lightning", false));
epPlayerSettings.put("protect.disable.weather.storm", config.getBoolean("protect.disable.weather.storm", false));
epPlayerSettings.put("protect.disable.weather.thunder", config.getBoolean("protect.disable.weather.thunder", false));
return epPlayerSettings;
}
public int getEpCreeperMaxHeight()
{
return config.getInt("protect.creeper.max-height", -1);
}
public boolean areSignsDisabled()
{
return config.getBoolean("signs-disabled", false);
}
public long getBackupInterval()
{
return config.getInt("backup.interval", 1440); // 1440 = 24 * 60
}
public String getBackupCommand()
{
return config.getString("backup.command", null);
}
public String getChatFormat(String group)
{
return config.getString("chat.group-formats." + (group == null ? "Default" : group),
config.getString("chat.format", "&7[{GROUP}]&f {DISPLAYNAME}&7:&f {MESSAGE}"));
}
public boolean getGenerateExitPortals()
{
return config.getBoolean("nether.generate-exit-portals", true);
}
public boolean getAnnounceNewPlayers()
{
return !config.getString("newbies.announce-format", "-").isEmpty();
}
public String getAnnounceNewPlayerFormat(IUser user)
{
return format(config.getString("newbies.announce-format", "&dWelcome {DISPLAYNAME} to the server!"), user);
}
public String format(String format, IUser user)
{
return format.replace('&', '§').replace("§§", "&").replace("{PLAYER}", user.getDisplayName()).replace("{DISPLAYNAME}", user.getDisplayName()).replace("{GROUP}", user.getGroup()).replace("{USERNAME}", user.getName()).replace("{ADDRESS}", user.getAddress().toString());
}
public String getNewbieSpawn()
{
return config.getString("newbies.spawnpoint", "default");
}
public boolean getPerWarpPermission()
{
return config.getBoolean("per-warp-permission", false);
}
public boolean getSortListByGroups()
{
return config.getBoolean("sort-list-by-groups", true);
}
public void reloadConfig() {
config.load();
}
public ArrayList<Integer> itemSpawnBlacklist()
{
ArrayList<Integer> epItemSpwn = new ArrayList<Integer>();
for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) {
itemName = itemName.trim();
if (itemName.isEmpty()) {
continue;
}
ItemStack is;
try {
is = ItemDb.get(itemName);
epItemSpwn.add(is.getTypeId());
} catch (Exception ex) {
logger.log(Level.SEVERE, Util.format("unknownItemInList", itemName, "item-spawn-blacklist"));
}
}
return epItemSpwn;
}
public ArrayList<Integer> epBlockBreakingBlacklist()
{
ArrayList<Integer> epBreakList = new ArrayList<Integer>();
for (String itemName : config.getString("protect.blacklist.break", "").split(",")) {
itemName = itemName.trim();
if (itemName.isEmpty()) {
continue;
}
ItemStack is;
try {
is = ItemDb.get(itemName);
epBreakList.add(is.getTypeId());
} catch (Exception ex) {
logger.log(Level.SEVERE, Util.format("unknownItemInList", itemName, "blacklist.break"));
}
}
return epBreakList;
}
public boolean spawnIfNoHome()
{
return config.getBoolean("spawn-if-no-home", false);
}
public boolean warnOnBuildDisallow()
{
return config.getBoolean("protect.disable.warn-on-build-disallow", false);
}
public boolean use1to1RatioInNether()
{
return config.getBoolean("nether.use-1to1-ratio", false);
}
public double getNetherRatio()
{
if (config.getBoolean("nether.use-1to1-ratio", false)) {
return 1.0;
}
return config.getDouble("nether.ratio", 16.0);
}
public boolean isDebug()
{
return config.getBoolean("debug", false);
}
public boolean warnOnSmite()
{
return config.getBoolean("warn-on-smite" ,true);
}
public boolean permissionBasedItemSpawn()
{
return config.getBoolean("permission-based-item-spawn", false);
}
public String getLocale()
{
return config.getString("locale", "");
}
public String getCurrencySymbol()
{
return config.getString("currency-symbol", "$").substring(0, 1).replaceAll("[0-9]", "$");
}
public boolean isTradeInStacks(int id)
{
return config.getBoolean("trade-in-stacks-" + id, false);
}
public boolean isEcoDisabled()
{
return config.getBoolean("disable-eco", false);
}
}

View File

@@ -0,0 +1,87 @@
package com.earth2me.essentials;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.World.Environment;
public class Spawn implements IConf {
private static final Logger logger = Logger.getLogger("Minecraft");
private final EssentialsConf config;
private final Server server;
public Spawn(Server server, File dataFolder) {
File configFile = new File(dataFolder, "spawn.yml");
this.server = server;
config = new EssentialsConf(configFile);
config.load();
}
public void setSpawn(Location loc, String group) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("world", loc.getWorld().getName());
map.put("x", loc.getX());
map.put("y", loc.getY());
map.put("z", loc.getZ());
map.put("yaw", loc.getYaw());
map.put("pitch", loc.getPitch());
config.setProperty(group, map);
config.save();
if ("default".equals(group)) {
loc.getWorld().setSpawnLocation(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
}
public Location getSpawn(String group) {
if (config.getProperty(group) == null) {
group = "default";
}
if (config.getProperty(group) == null) {
for (World w : server.getWorlds()) {
if (w.getEnvironment() != Environment.NORMAL) {
continue;
}
return w.getSpawnLocation();
}
}
String worldId = config.getString(group + ".world", "");
World world = server.getWorlds().get(server.getWorlds().size() > 1 ? 1 : 0);
for (World w : server.getWorlds()) {
if (w.getEnvironment() != Environment.NORMAL) {
continue;
}
world = w;
break;
}
for (World w : server.getWorlds()) {
if (!w.getName().equals(worldId)) {
continue;
}
world = w;
break;
}
double x = config.getDouble(group + ".x", config.getDouble("default.x", 0));
double y = config.getDouble(group + ".y", config.getDouble("default.y", 0));
double z = config.getDouble(group + ".z", config.getDouble("default.z", 0));
float yaw = (float) config.getDouble(group + ".yaw", config.getDouble("default.yaw", 0));
float pitch = (float) config.getDouble(group + ".pitch", config.getDouble("default.pitch", 0));
Location retval = new Location(world, x, y, z, yaw, pitch);
if (y < 1) {
retval.setY(world.getHighestBlockYAt(retval));
}
return retval;
}
public void reloadConfig() {
config.load();
}
}

View File

@@ -0,0 +1,599 @@
package com.earth2me.essentials;
import java.util.ArrayList;
import org.bukkit.block.Block;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
/**
* @author toi
* Thanks to Raphfrk for optimization of this class.
*/
public class TargetBlock {
private Location loc;
private double viewHeight;
private int maxDistance;
private int[] blockToIgnore;
private double checkDistance, curDistance;
private double xRotation, yRotation;
private Vector targetPos = new Vector();
private Vector targetPosDouble = new Vector();
private Vector prevPos = new Vector();
private final Vector offset = new Vector();
/**
* Constructor requiring a player, uses default values
*
* @param player Player to work with
*/
public TargetBlock(Player player)
{
this.setValues(player.getLocation(), 300, 1.65, 0.2, null);
}
/**
* Constructor requiring a location, uses default values
*
* @param loc Location to work with
*/
public TargetBlock(Location loc)
{
this.setValues(loc, 300, 0, 0.2, null);
}
/**
* Constructor requiring a player, max distance and a checking distance
*
* @param player Player to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
*/
public TargetBlock(Player player, int maxDistance, double checkDistance)
{
this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, null);
}
/**
* Constructor requiring a location, max distance and a checking distance
*
* @param loc What location to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
*/
public TargetBlock(Location loc, int maxDistance, double checkDistance) {
this.setValues(loc, maxDistance, 0, checkDistance, null);
}
/**
* Constructor requiring a player, max distance, checking distance and an array of blocks to ignore
*
* @param player What player to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore Integer array of what block ids to ignore while checking for viable targets
*/
public TargetBlock (Player player, int maxDistance, double checkDistance, int[] blocksToIgnore)
{
this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, blocksToIgnore);
}
/**
* Constructor requiring a location, max distance, checking distance and an array of blocks to ignore
*
* @param loc What location to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore Array of what block ids to ignore while checking for viable targets
*/
public TargetBlock (Location loc, int maxDistance, double checkDistance, int[] blocksToIgnore)
{
this.setValues(loc, maxDistance, 0, checkDistance, blocksToIgnore);
}
/**
* Constructor requiring a player, max distance, checking distance and an array of blocks to ignore
*
* @param player What player to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore String ArrayList of what block ids to ignore while checking for viable targets
*/
public TargetBlock (Player player, int maxDistance, double checkDistance, ArrayList<String> blocksToIgnore)
{
int[] bti = this.convertStringArraytoIntArray(blocksToIgnore);
this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, bti);
}
/**
* Constructor requiring a location, max distance, checking distance and an array of blocks to ignore
*
* @param loc What location to work with
* @param maxDistance How far it checks for blocks
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore String ArrayList of what block ids to ignore while checking for viable targets
*/
public TargetBlock (Location loc, int maxDistance, double checkDistance, ArrayList<String> blocksToIgnore)
{
int[] bti = this.convertStringArraytoIntArray(blocksToIgnore);
this.setValues(loc, maxDistance, 0, checkDistance, bti);
}
/**
* Set the values, all constructors uses this function
*
* @param loc Location of the view
* @param maxDistance How far it checks for blocks
* @param viewPos Where the view is positioned in y-axis
* @param checkDistance How often to check for blocks, the smaller the more precise
* @param blocksToIgnore Ids of blocks to ignore while checking for viable targets
*/
private void setValues(Location loc, int maxDistance, double viewHeight, double checkDistance, int[] blocksToIgnore)
{
this.loc = loc;
this.maxDistance = maxDistance;
this.viewHeight = viewHeight;
this.checkDistance = checkDistance;
this.blockToIgnore = blocksToIgnore;
this.curDistance = 0;
xRotation = (loc.getYaw() + 90) % 360;
yRotation = loc.getPitch() * -1;
double h = (checkDistance * Math.cos(Math.toRadians(yRotation)));
offset.setY((checkDistance * Math.sin(Math.toRadians(yRotation))));
offset.setX((h * Math.cos(Math.toRadians(xRotation))));
offset.setZ((h * Math.sin(Math.toRadians(xRotation))));
targetPosDouble = new Vector(loc.getX(), loc.getY() + viewHeight, loc.getZ());
targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ());
prevPos = targetPos.clone();
}
/**
* Call this to reset checking position to allow you to check for a new target with the same TargetBlock instance.
*/
public void reset()
{
targetPosDouble = new Vector(loc.getX(), loc.getY() + viewHeight, loc.getZ());
targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ());
prevPos = targetPos.clone();
this.curDistance = 0;
}
/**
* Gets the distance to a block. Measures from the block underneath the player to the targetblock
* Should only be used when passing player as an constructor parameter
*
* @return double
*/
public double getDistanceToBlock()
{
Vector blockUnderPlayer = new Vector(
(int) Math.floor(loc.getX() + 0.5),
(int) Math.floor(loc.getY() - 0.5),
(int) Math.floor(loc.getZ() + 0.5));
Block blk = getTargetBlock();
double x = blk.getX() - blockUnderPlayer.getBlockX();
double y = blk.getY() - blockUnderPlayer.getBlockY();
double z = blk.getZ() - blockUnderPlayer.getBlockZ();
return Math.sqrt((Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2)));
}
/**
* Gets the rounded distance to a block. Measures from the block underneath the player to the targetblock
* Should only be used when passing player as an constructor parameter
*
* @return int
*/
public int getDistanceToBlockRounded()
{
Vector blockUnderPlayer = new Vector(
(int) Math.floor(loc.getX() + 0.5),
(int) Math.floor(loc.getY() - 0.5),
(int) Math.floor(loc.getZ() + 0.5));
Block blk = getTargetBlock();
double x = blk.getX() - blockUnderPlayer.getBlockX();
double y = blk.getY() - blockUnderPlayer.getBlockY();
double z = blk.getZ() - blockUnderPlayer.getBlockZ();
return (int) Math.round((Math.sqrt((Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2)))));
}
/**
* Gets the floored x distance to a block.
*
* @return int
*/
public int getXDistanceToBlock()
{
this.reset();
return (int) Math.floor(getTargetBlock().getX() - loc.getBlockX() + 0.5);
}
/**
* Gets the floored y distance to a block
*
* @return int
*/
public int getYDistanceToBlock()
{
this.reset();
return (int) Math.floor(getTargetBlock().getY() - loc.getBlockY() + viewHeight);
}
/**
* Gets the floored z distance to a block
*
* @return int
*/
public int getZDistanceToBlock()
{
this.reset();
return (int) Math.floor(getTargetBlock().getZ() - loc.getBlockZ() + 0.5);
}
/**
* Returns the block at the sight. Returns null if out of range or if no viable target was found
*
* @return Block
*/
@SuppressWarnings("empty-statement")
public Block getTargetBlock()
{
this.reset();
while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId())));
return getCurrentBlock();
}
/**
* Sets the type of the block at the sight. Returns false if the block wasn't set.
*
* @param typeID ID of type to set the block to
* @return boolean
*/
@SuppressWarnings("empty-statement")
public boolean setTargetBlock(int typeID)
{
if (Material.getMaterial(typeID) != null)
{
this.reset();
while (getNextBlock() != null && getCurrentBlock().getTypeId() == 0);
if (getCurrentBlock() != null)
{
Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ());
blk.setTypeId(typeID);
return true;
}
}
return false;
}
/**
* Sets the type of the block at the sight. Returns false if the block wasn't set.
*
* @param type Material to set the block to
* @return boolean
*/
@SuppressWarnings("empty-statement")
public boolean setTargetBlock(Material type)
{
this.reset();
while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId())));
if (getCurrentBlock() != null)
{
Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ());
blk.setType(type);
return true;
}
return false;
}
/**
* Sets the type of the block at the sight. Returns false if the block wasn't set.
* Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented
*
* @param type Name of type to set the block to
* @return boolean
*/
@SuppressWarnings("empty-statement")
public boolean setTargetBlock(String type)
{
Material mat = Material.valueOf(type);
if (mat != null)
{
this.reset();
while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId())));
if (getCurrentBlock() != null)
{
Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ());
blk.setType(mat);
return true;
}
}
return false;
}
/**
* Returns the block attached to the face at the sight. Returns null if out of range or if no viable target was found
*
* @return Block
*/
@SuppressWarnings("empty-statement")
public Block getFaceBlock()
{
while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId())));
if (getCurrentBlock() != null)
{
return getPreviousBlock();
}
else
{
return null;
}
}
/**
* Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set.
*
* @param typeID
* @return boolean
*/
public boolean setFaceBlock(int typeID)
{
if (Material.getMaterial(typeID) != null)
{
if (getCurrentBlock() != null)
{
Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ());
blk.setTypeId(typeID);
return true;
}
}
return false;
}
/**
* Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set.
*
* @param type
* @return boolean
*/
public boolean setFaceBlock(Material type)
{
if (getCurrentBlock() != null)
{
Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ());
blk.setType(type);
return true;
}
return false;
}
/**
* Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set.
* Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented
*
* @param type
* @return boolean
*/
public boolean setFaceBlock(String type)
{
Material mat = Material.valueOf(type);
if (mat != null)
{
if (getCurrentBlock() != null)
{
Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ());
blk.setType(mat);
return true;
}
}
return false;
}
/**
* Get next block
*
* @return Block
*/
public Block getNextBlock()
{
prevPos = targetPos.clone();
do
{
curDistance += checkDistance;
targetPosDouble.setX(offset.getX() + targetPosDouble.getX());
targetPosDouble.setY(offset.getY() + targetPosDouble.getY());
targetPosDouble.setZ(offset.getZ() + targetPosDouble.getZ());
targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ());
}
while (curDistance <= maxDistance && targetPos.getBlockX() == prevPos.getBlockX() && targetPos.getBlockY() == prevPos.getBlockY() && targetPos.getBlockZ() == prevPos.getBlockZ());
if (curDistance > maxDistance)
{
return null;
}
return this.loc.getWorld().getBlockAt(this.targetPos.getBlockX(), this.targetPos.getBlockY(), this.targetPos.getBlockZ());
}
/**
* Returns the current block along the line of vision
*
* @return Block
*/
public Block getCurrentBlock()
{
if (curDistance > maxDistance)
{
return null;
}
else
{
return this.loc.getWorld().getBlockAt(this.targetPos.getBlockX(), this.targetPos.getBlockY(), this.targetPos.getBlockZ());
}
}
/**
* Sets current block type. Returns false if the block wasn't set.
*
* @param typeID
*/
public boolean setCurrentBlock(int typeID)
{
if (Material.getMaterial(typeID) != null)
{
Block blk = getCurrentBlock();
if (blk != null)
{
blk.setTypeId(typeID);
return true;
}
}
return false;
}
/**
* Sets current block type. Returns false if the block wasn't set.
*
* @param type
*/
public boolean setCurrentBlock(Material type)
{
Block blk = getCurrentBlock();
if (blk != null)
{
blk.setType(type);
return true;
}
return false;
}
/**
* Sets current block type. Returns false if the block wasn't set.
* Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented
*
* @param type
*/
public boolean setCurrentBlock(String type)
{
Material mat = Material.valueOf(type);
if (mat != null)
{
Block blk = getCurrentBlock();
if (blk != null)
{
blk.setType(mat);
return true;
}
}
return false;
}
/**
* Returns the previous block in the aimed path
*
* @return Block
*/
public Block getPreviousBlock()
{
return this.loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ());
}
/**
* Sets previous block type id. Returns false if the block wasn't set.
*
* @param typeID
*/
public boolean setPreviousBlock(int typeID)
{
if (Material.getMaterial(typeID) != null)
{
Block blk = getPreviousBlock();
if (blk != null)
{
blk.setTypeId(typeID);
return true;
}
}
return false;
}
/**
* Sets previous block type id. Returns false if the block wasn't set.
*
* @param type
*/
public boolean setPreviousBlock(Material type)
{
Block blk = getPreviousBlock();
if (blk != null)
{
blk.setType(type);
return true;
}
return false;
}
/**
* Sets previous block type id. Returns false if the block wasn't set.
* Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented
*
* @param type
*/
public boolean setPreviousBlock(String type)
{
Material mat = Material.valueOf(type);
if (mat != null)
{
Block blk = getPreviousBlock();
if (blk != null)
{
blk.setType(mat);
return true;
}
}
return false;
}
private int[] convertStringArraytoIntArray(ArrayList<String> array)
{
if (array != null)
{
int intarray[] = new int[array.size()];
for (int i = 0; i < array.size(); i++)
{
try
{
intarray[i] = Integer.parseInt(array.get(i));
}
catch (NumberFormatException nfe)
{
intarray[i] = 0;
}
}
return intarray;
}
return null;
}
private boolean blockToIgnoreHasValue(int value)
{
if (this.blockToIgnore != null)
{
if (this.blockToIgnore.length > 0)
{
for (int i : this.blockToIgnore)
{
if (i == value)
return true;
}
}
}
return false;
}
}

View File

@@ -1,28 +1,15 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.ITeleport;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.perm.Permissions;
import com.earth2me.essentials.user.CooldownException;
import com.earth2me.essentials.user.UserData.TimestampType;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class Teleport implements Runnable, ITeleport
public class Teleport implements Runnable
{
private static final double MOVE_CONSTANT = 0.3;
private static class Target
{
private final Location location;
@@ -61,25 +48,22 @@ public class Teleport implements Runnable, ITeleport
private long initY;
private long initZ;
private Target teleportTarget;
private Trade chargeFor;
private Charge chargeFor;
private final IEssentials ess;
private static final Logger logger = Logger.getLogger("Minecraft");
private TeleportCause cause;
private void initTimer(long delay, Target target, Trade chargeFor, TeleportCause cause)
private void initTimer(long delay, Target target, Charge chargeFor)
{
this.started = System.currentTimeMillis();
this.delay = delay;
this.health = user.getHealth();
this.initX = Math.round(user.getLocation().getX() * MOVE_CONSTANT);
this.initY = Math.round(user.getLocation().getY() * MOVE_CONSTANT);
this.initZ = Math.round(user.getLocation().getZ() * MOVE_CONSTANT);
this.initX = Math.round(user.getLocation().getX() * 10000);
this.initY = Math.round(user.getLocation().getY() * 10000);
this.initZ = Math.round(user.getLocation().getZ() * 10000);
this.teleportTarget = target;
this.chargeFor = chargeFor;
this.cause = cause;
}
@Override
public void run()
{
@@ -88,9 +72,9 @@ public class Teleport implements Runnable, ITeleport
cancel();
return;
}
if (Math.round(user.getLocation().getX() * MOVE_CONSTANT) != initX
|| Math.round(user.getLocation().getY() * MOVE_CONSTANT) != initY
|| Math.round(user.getLocation().getZ() * MOVE_CONSTANT) != initZ
if (Math.round(user.getLocation().getX() * 10000) != initX
|| Math.round(user.getLocation().getY() * 10000) != initY
|| Math.round(user.getLocation().getZ() * 10000) != initZ
|| user.getHealth() < health)
{ // user moved, cancel teleport
cancel(true);
@@ -105,11 +89,11 @@ public class Teleport implements Runnable, ITeleport
try
{
cooldown(false);
user.sendMessage(_("teleportationCommencing"));
user.sendMessage(Util.i18n("teleportationCommencing"));
try
{
now(teleportTarget, cause);
now(teleportTarget);
if (chargeFor != null)
{
chargeFor.charge(user);
@@ -117,12 +101,17 @@ public class Teleport implements Runnable, ITeleport
}
catch (Throwable ex)
{
ess.getCommandHandler().showCommandError(user.getBase(), "teleport", ex);
user.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
if (ess.getSettings().isDebug())
{
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
return;
}
catch (Exception ex)
{
user.sendMessage(_("cooldownWithMessage", ex.getMessage()));
user.sendMessage(Util.format("cooldownWithMessage", ex.getMessage()));
}
}
}
@@ -133,32 +122,37 @@ public class Teleport implements Runnable, ITeleport
this.ess = ess;
}
public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception
public void respawn(Spawn spawn, Charge chargeFor) throws Exception
{
final Player player = user.getBase();
final Location bed = player.getBedSpawnLocation();
final PlayerRespawnEvent pre = new PlayerRespawnEvent(player, bed == null ? player.getWorld().getSpawnLocation() : bed, bed != null);
ess.getServer().getPluginManager().callEvent(pre);
teleport(new Target(pre.getRespawnLocation()), chargeFor, cause);
teleport(new Target(spawn.getSpawn(user.getGroup())), chargeFor);
}
public void warp(String warp, Trade chargeFor, TeleportCause cause) throws Exception
public void warp(String warp, Charge chargeFor) throws Exception
{
final Location loc = ess.getWarps().getWarp(warp);
teleport(new Target(loc), chargeFor, cause);
user.sendMessage(_("warpingTo", warp));
Location loc = ess.getWarps().getWarp(warp);
teleport(new Target(loc), chargeFor);
user.sendMessage(Util.format("warpingTo", warp));
}
public void cooldown(boolean check) throws Exception
{
try
Calendar now = new GregorianCalendar();
if (user.getLastTeleportTimestamp() > 0)
{
user.checkCooldown(TimestampType.LASTTELEPORT, ess.getGroups().getTeleportCooldown(user), !check, Permissions.TELEPORT_COOLDOWN_BYPASS);
double cooldown = ess.getSettings().getTeleportCooldown();
Calendar cooldownTime = new GregorianCalendar();
cooldownTime.setTimeInMillis(user.getLastTeleportTimestamp());
cooldownTime.add(Calendar.SECOND, (int)cooldown);
cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0));
if (cooldownTime.after(now) && !user.isAuthorized("essentials.teleport.cooldown.bypass"))
{
throw new Exception(Util.format("timeBeforeTeleport", Util.formatDateDiff(cooldownTime.getTimeInMillis())));
}
}
catch (CooldownException ex)
// if justCheck is set, don't update lastTeleport; we're just checking
if (!check)
{
throw new Exception(_("timeBeforeTeleport", ex.getMessage()));
user.setLastTeleportTimestamp(now.getTimeInMillis());
}
}
@@ -173,7 +167,7 @@ public class Teleport implements Runnable, ITeleport
ess.getServer().getScheduler().cancelTask(teleTimer);
if (notifyUser)
{
user.sendMessage(_("pendingTeleportCancelled"));
user.sendMessage(Util.i18n("pendingTeleportCancelled"));
}
}
finally
@@ -187,34 +181,29 @@ public class Teleport implements Runnable, ITeleport
cancel(false);
}
public void teleport(Location loc, Trade chargeFor) throws Exception
public void teleport(Location loc, Charge chargeFor) throws Exception
{
teleport(new Target(loc), chargeFor, TeleportCause.PLUGIN);
teleport(new Target(loc), chargeFor);
}
public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception
public void teleport(Entity entity, Charge chargeFor) throws Exception
{
teleport(new Target(loc), chargeFor, cause);
teleport(new Target(entity), chargeFor);
}
public void teleport(Entity entity, Trade chargeFor, TeleportCause cause) throws Exception
private void teleport(Target target, Charge chargeFor) throws Exception
{
teleport(new Target(entity), chargeFor, cause);
}
private void teleport(Target target, Trade chargeFor, TeleportCause cause) throws Exception
{
double delay = ess.getGroups().getTeleportDelay(user);
double delay = ess.getSettings().getTeleportDelay();
if (chargeFor != null)
{
chargeFor.isAffordableFor(user);
}
cooldown(true);
if (delay <= 0 || Permissions.TELEPORT_TIMER_BYPASS.isAuthorized(user))
if (delay <= 0 || user.isAuthorized("essentials.teleport.timer.bypass"))
{
cooldown(false);
now(target, cause);
now(target);
if (chargeFor != null)
{
chargeFor.charge(user);
@@ -226,77 +215,67 @@ public class Teleport implements Runnable, ITeleport
Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int)delay);
c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0));
user.sendMessage(_("dontMoveMessage", Util.formatDateDiff(c.getTimeInMillis())));
initTimer((long)(delay * 1000.0), target, chargeFor, cause);
user.sendMessage(Util.format("dontMoveMessage", Util.formatDateDiff(c.getTimeInMillis())));
initTimer((long)(delay * 1000.0), target, chargeFor);
teleTimer = ess.scheduleSyncRepeatingTask(this, 10, 10);
}
private void now(Target target, TeleportCause cause) throws Exception
private void now(Target target) throws Exception
{
cancel();
user.setLastLocation();
user.getBase().teleport(Util.getSafeDestination(target.getLocation()), cause);
user.getBase().teleport(Util.getSafeDestination(target.getLocation()));
}
public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception
public void now(Location loc) throws Exception
{
if (cooldown)
{
cooldown(false);
}
now(new Target(loc), cause);
cooldown(false);
now(new Target(loc));
}
public void now(Location loc, Trade chargeFor, TeleportCause cause) throws Exception
public void now(Location loc, Charge chargeFor) throws Exception
{
cooldown(false);
chargeFor.charge(user);
now(new Target(loc), cause);
now(new Target(loc));
}
public void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception
public void now(Entity entity) throws Exception
{
if (cooldown)
{
cooldown(false);
}
now(new Target(entity), cause);
cooldown(false);
now(new Target(entity));
}
public void back(Trade chargeFor) throws Exception
public void back(Charge chargeFor) throws Exception
{
user.acquireReadLock();
try
{
teleport(new Target(user.getData().getLastLocation().getBukkitLocation()), chargeFor, TeleportCause.COMMAND);
}
finally
{
user.unlock();
}
teleport(new Target(user.getLastLocation()), chargeFor);
}
public void back() throws Exception
{
user.acquireReadLock();
try
{
now(new Target(user.getData().getLastLocation().getBukkitLocation()), TeleportCause.COMMAND);
}
finally
{
user.unlock();
}
back(null);
}
public void home(IUser user, String home, Trade chargeFor) throws Exception
public void home(Charge chargeFor) throws Exception
{
final Location loc = user.getHome(home);
home(user, chargeFor);
}
public void home(IUser user, Charge chargeFor) throws Exception
{
Location loc = user.getHome(this.user.getLocation());
if (loc == null)
{
throw new NotEnoughArgumentsException();
if (ess.getSettings().spawnIfNoHome())
{
respawn(ess.getSpawn(), chargeFor);
}
else
{
throw new Exception(user == this.user ? Util.i18n("noHomeSet") : Util.i18n("noHomeSetPlayer"));
}
}
teleport(new Target(loc), chargeFor, TeleportCause.COMMAND);
teleport(new Target(loc), chargeFor);
}
}

View File

@@ -1,337 +0,0 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.ChargeException;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.ISettings;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.perm.NoCommandCostPermissions;
import com.earth2me.essentials.perm.Permissions;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import lombok.Cleanup;
import org.bukkit.Location;
import org.bukkit.entity.Item;
import org.bukkit.inventory.ItemStack;
public class Trade
{
private final transient String command;
private final transient Double money;
private final transient ItemStack itemStack;
private final transient Integer exp;
private final transient IEssentials ess;
public Trade(final String command, final IEssentials ess)
{
this(command, null, null, null, ess);
}
public Trade(final double money, final IEssentials ess)
{
this(null, money, null, null, ess);
}
public Trade(final ItemStack items, final IEssentials ess)
{
this(null, null, items, null, ess);
}
public Trade(final int exp, final IEssentials ess)
{
this(null, null, null, exp, ess);
}
private Trade(final String command, final Double money, final ItemStack item, final Integer exp, final IEssentials ess)
{
this.command = command;
this.money = money;
this.itemStack = item;
this.exp = exp;
this.ess = ess;
}
public void isAffordableFor(final IUser user) throws ChargeException
{
final double mon = user.getMoney();
if (getMoney() != null
&& mon < getMoney()
&& getMoney() > 0
&& !Permissions.ECO_LOAN.isAuthorized(user))
{
throw new ChargeException(_("notEnoughMoney"));
}
if (getItemStack() != null
&& !InventoryWorkaround.containsItem(user.getInventory(), true, true, itemStack))
{
throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
}
@Cleanup
final ISettings settings = ess.getSettings();
settings.acquireReadLock();
if (command != null && !command.isEmpty()
&& !NoCommandCostPermissions.getPermission(command).isAuthorized(user)
&& mon < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command)
&& 0 < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command)
&& !Permissions.ECO_LOAN.isAuthorized(user))
{
throw new ChargeException(_("notEnoughMoney"));
}
if (exp != null && exp > 0
&& SetExpFix.getTotalExperience(user) < exp)
{
throw new ChargeException(_("notEnoughExperience"));
}
}
public void pay(final IUser user)
{
pay(user, true);
}
public boolean pay(final IUser user, final boolean dropItems)
{
boolean success = true;
if (getMoney() != null && getMoney() > 0)
{
user.giveMoney(getMoney());
}
if (getItemStack() != null)
{
if (dropItems)
{
final Map<Integer, ItemStack> leftOver = InventoryWorkaround.addItem(user.getInventory(), true, getItemStack());
final Location loc = user.getLocation();
for (ItemStack dropStack : leftOver.values())
{
final int maxStackSize = dropStack.getType().getMaxStackSize();
final int stacks = dropStack.getAmount() / maxStackSize;
final int leftover = dropStack.getAmount() % maxStackSize;
final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)];
for (int i = 0; i < stacks; i++)
{
final ItemStack stack = dropStack.clone();
stack.setAmount(maxStackSize);
itemStacks[i] = loc.getWorld().dropItem(loc, stack);
}
if (leftover > 0)
{
final ItemStack stack = dropStack.clone();
stack.setAmount(leftover);
itemStacks[stacks] = loc.getWorld().dropItem(loc, stack);
}
}
}
else
{
success = InventoryWorkaround.addAllItems(user.getInventory(), true, getItemStack());
}
user.updateInventory();
}
if (getExperience() != null)
{
SetExpFix.setTotalExperience(user, SetExpFix.getTotalExperience(user) + getExperience());
}
return success;
}
public void charge(final IUser user) throws ChargeException
{
if (getMoney() != null)
{
final double mon = user.getMoney();
if (mon < getMoney() && getMoney() > 0 && !Permissions.ECO_LOAN.isAuthorized(user))
{
throw new ChargeException(_("notEnoughMoney"));
}
user.takeMoney(getMoney());
}
if (getItemStack() != null)
{
if (!InventoryWorkaround.containsItem(user.getInventory(), true, true, itemStack))
{
throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
}
InventoryWorkaround.removeItem(user.getInventory(), true, true, getItemStack());
user.updateInventory();
}
if (command != null && !command.isEmpty()
&& !NoCommandCostPermissions.getPermission(command).isAuthorized(user))
{
@Cleanup
final ISettings settings = ess.getSettings();
settings.acquireReadLock();
final double mon = user.getMoney();
final double cost = settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command);
if (mon < cost && cost > 0 && !Permissions.ECO_LOAN.isAuthorized(user))
{
throw new ChargeException(_("notEnoughMoney"));
}
user.takeMoney(cost);
}
if (getExperience() != null)
{
final int experience = SetExpFix.getTotalExperience(user);
if (experience < getExperience() && getExperience() > 0)
{
throw new ChargeException(_("notEnoughExperience"));
}
SetExpFix.setTotalExperience(user, experience - getExperience());
}
}
public Double getMoney()
{
return money;
}
public ItemStack getItemStack()
{
return itemStack;
}
public Integer getExperience()
{
return exp;
}
private static FileWriter fw = null;
public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess)
{
@Cleanup
final ISettings settings = ess.getSettings();
settings.acquireReadLock();
if (!settings.getData().getEconomy().isLogEnabled())
{
return;
}
if (fw == null)
{
try
{
fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true);
}
catch (IOException ex)
{
Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
}
}
StringBuilder sb = new StringBuilder();
sb.append(type).append(",").append(subtype).append(",").append(event).append(",\"");
sb.append(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date()));
sb.append("\",\"");
if (sender != null)
{
sb.append(sender);
}
sb.append("\",");
if (charge == null)
{
sb.append("\"\",\"\",\"\"");
}
else
{
if (charge.getItemStack() != null)
{
sb.append(charge.getItemStack().getAmount()).append(",");
sb.append(charge.getItemStack().getType().toString()).append(",");
sb.append(charge.getItemStack().getDurability());
}
if (charge.getMoney() != null)
{
sb.append(charge.getMoney()).append(",");
sb.append("money").append(",");
sb.append(settings.getData().getEconomy().getCurrencySymbol());
}
if (charge.getExperience() != null)
{
sb.append(charge.getExperience()).append(",");
sb.append("exp").append(",");
sb.append("\"\"");
}
}
sb.append(",\"");
if (receiver != null)
{
sb.append(receiver);
}
sb.append("\",");
if (pay == null)
{
sb.append("\"\",\"\",\"\"");
}
else
{
if (pay.getItemStack() != null)
{
sb.append(pay.getItemStack().getAmount()).append(",");
sb.append(pay.getItemStack().getType().toString()).append(",");
sb.append(pay.getItemStack().getDurability());
}
if (pay.getMoney() != null)
{
sb.append(pay.getMoney()).append(",");
sb.append("money").append(",");
sb.append(settings.getData().getEconomy().getCurrencySymbol());
}
if (pay.getExperience() != null)
{
sb.append(pay.getExperience()).append(",");
sb.append("exp").append(",");
sb.append("\"\"");
}
}
if (loc == null)
{
sb.append(",\"\",\"\",\"\",\"\"");
}
else
{
sb.append(",\"");
sb.append(loc.getWorld().getName()).append("\",");
sb.append(loc.getBlockX()).append(",");
sb.append(loc.getBlockY()).append(",");
sb.append(loc.getBlockZ()).append(",");
}
sb.append("\n");
try
{
fw.write(sb.toString());
fw.flush();
}
catch (IOException ex)
{
Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
}
}
public static void closeLog()
{
if (fw != null)
{
try
{
fw.close();
}
catch (IOException ex)
{
Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex);
}
fw = null;
}
}
}

View File

@@ -0,0 +1,289 @@
package com.earth2me.essentials;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.register.payment.Method;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class User extends UserData implements Comparable<User>, IReplyTo, IUser
{
private static final Logger logger = Logger.getLogger("Minecraft");
private boolean justPortaled = false;
private CommandSender replyTo = null;
private User teleportRequester;
private boolean teleportRequestHere;
private final Teleport teleport;
private long lastActivity;
User(Player base, IEssentials ess)
{
super(base, ess);
teleport = new Teleport(this, ess);
}
User update(Player base)
{
setBase(base);
return this;
}
public boolean isAuthorized(IEssentialsCommand cmd)
{
return isAuthorized("essentials." + (cmd.getName().equals("r") ? "msg" : cmd.getName()));
}
public boolean isAuthorized(String node)
{
if (isOp())
{
return true;
}
if (isJailed())
{
return false;
}
try
{
return com.nijikokun.bukkit.Permissions.Permissions.Security.permission(base, node);
}
catch (Throwable ex)
{
String[] cmds = node.split("\\.", 2);
return !ess.getSettings().isCommandRestricted(cmds[cmds.length - 1]);
}
}
public void healCooldown() throws Exception
{
Calendar now = new GregorianCalendar();
if (getLastHealTimestamp() > 0)
{
double cooldown = ess.getSettings().getHealCooldown();
Calendar cooldownTime = new GregorianCalendar();
cooldownTime.setTimeInMillis(getLastHealTimestamp());
cooldownTime.add(Calendar.SECOND, (int)cooldown);
cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0));
if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass"))
{
throw new Exception(Util.format("timeBeforeHeal", Util.formatDateDiff(cooldownTime.getTimeInMillis())));
}
}
setLastHealTimestamp(now.getTimeInMillis());
}
public void giveMoney(double value)
{
if (value == 0)
{
return;
}
setMoney(getMoney() + value);
sendMessage(Util.format("addedToAccount", Util.formatCurrency(value)));
}
public void payUser(User reciever, double value) throws Exception
{
if (value == 0)
{
return;
}
if (!canAfford(value))
{
throw new Exception(Util.i18n("notEnoughMoney"));
}
else
{
setMoney(getMoney() - value);
reciever.setMoney(reciever.getMoney() + value);
sendMessage(Util.format("moneySentTo", Util.formatCurrency(value), reciever.getDisplayName()));
reciever.sendMessage(Util.format("moneyRecievedFrom", Util.formatCurrency(value), getDisplayName()));
}
}
public void takeMoney(double value)
{
if (value == 0)
{
return;
}
setMoney(getMoney() - value);
sendMessage(Util.format("takenFromAccount", Util.formatCurrency(value)));
}
public boolean canAfford(double cost)
{
double mon = getMoney();
return mon >= cost || isAuthorized("essentials.eco.loan");
}
public void dispose()
{
this.base = new OfflinePlayer(getName());
}
public boolean getJustPortaled()
{
return justPortaled;
}
public void setJustPortaled(boolean value)
{
justPortaled = value;
}
public void setReplyTo(CommandSender user)
{
replyTo = user;
}
public CommandSender getReplyTo()
{
return replyTo;
}
public int compareTo(User t)
{
return ChatColor.stripColor(this.getDisplayName()).compareToIgnoreCase(ChatColor.stripColor(t.getDisplayName()));
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof User))
{
return false;
}
return ChatColor.stripColor(this.getDisplayName()).equalsIgnoreCase(ChatColor.stripColor(((User) o).getDisplayName()));
}
@Override
public int hashCode()
{
return ChatColor.stripColor(this.getDisplayName()).hashCode();
}
public Boolean canSpawnItem(int itemId)
{
return !ess.getSettings().itemSpawnBlacklist().contains(itemId);
}
public void setHome()
{
setHome(getLocation(), true);
}
public void setHome(boolean defaultHome)
{
setHome(getLocation(), defaultHome);
}
public void setLastLocation()
{
setLastLocation(getLocation());
}
public void requestTeleport(User player, boolean here)
{
teleportRequester = player;
teleportRequestHere = here;
}
public User getTeleportRequest()
{
return teleportRequester;
}
public boolean isTeleportRequestHere()
{
return teleportRequestHere;
}
public String getNick()
{
String nickname = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nickname == null || nickname.isEmpty() || nickname.equals(getName()))
{
nickname = getName();
}
else
{
nickname = ess.getSettings().getNicknamePrefix() + nickname;
}
if (isOp())
{
try
{
nickname = ess.getSettings().getOperatorColor().toString() + nickname + "§f";
}
catch(Exception e)
{
}
}
return nickname;
}
public Teleport getTeleport()
{
return teleport;
}
public long getLastActivity()
{
return lastActivity;
}
public void setLastActivity(long timestamp)
{
lastActivity = timestamp;
}
@Override
public double getMoney()
{
if (ess.isRegisterFallbackEnabled() && ess.getPaymentMethod().hasMethod())
{
try
{
Method method = ess.getPaymentMethod().getMethod();
if (!method.hasAccount(this.getName())) {
throw new Exception();
}
Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName());
return account.balance();
}
catch (Throwable ex)
{
}
}
return super.getMoney();
}
@Override
public void setMoney(double value)
{
if (ess.isRegisterFallbackEnabled() && ess.getPaymentMethod().hasMethod())
{
try
{
Method method = ess.getPaymentMethod().getMethod();
if (!method.hasAccount(this.getName())) {
throw new Exception();
}
Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName());
account.set(value);
}
catch (Throwable ex)
{
}
}
super.setMoney(value);
}
}

View File

@@ -0,0 +1,709 @@
package com.earth2me.essentials;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public abstract class UserData extends PlayerExtension implements IConf
{
private final EssentialsConf config;
private static final Logger logger = Logger.getLogger("Minecraft");
protected UserData(Player base, IEssentials ess)
{
super(base, ess);
File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
config = new EssentialsConf(new File(folder, Util.sanitizeFileName(base.getName()) + ".yml"));
reloadConfig();
}
public final void reloadConfig()
{
config.load();
money = _getMoney();
unlimited = _getUnlimited();
powertools = getPowertools();
lastLocation = _getLastLocation();
lastTeleportTimestamp = _getLastTeleportTimestamp();
lastHealTimestamp = _getLastHealTimestamp();
jail = _getJail();
mails = _getMails();
savedInventory = _getSavedInventory();
teleportEnabled = getTeleportEnabled();
ignoredPlayers = getIgnoredPlayers();
godmode = getGodModeEnabled();
muted = getMuted();
muteTimeout = _getMuteTimeout();
jailed = getJailed();
jailTimeout = _getJailTimeout();
lastLogin = _getLastLogin();
lastLogout = _getLastLogout();
afk = getAfk();
newplayer = getNew();
geolocation = _getGeoLocation();
isSocialSpyEnabled = _isSocialSpyEnabled();
isNPC = _isNPC();
}
private double money;
private double _getMoney() {
if (config.hasProperty("money"))
{
return config.getDouble("money", ess.getSettings().getStartingBalance());
}
else
{
return ess.getSettings().getStartingBalance();
}
}
public double getMoney()
{
return money;
}
public void setMoney(double value)
{
money = value;
config.setProperty("money", value);
config.save();
}
public boolean hasHome()
{
if (config.hasProperty("home"))
{
return true;
}
return false;
}
public Location getHome(Location location)
{
if (!hasHome())
{
return null;
}
World world = location.getWorld();
String worldHome = "home.worlds." + world.getName().toLowerCase();
if (!config.hasProperty(worldHome))
{
String defaultWorld = config.getString("home.default");
worldHome = "home.worlds." + defaultWorld;
}
Location loc = config.getLocation(worldHome, getServer());
return loc;
}
public void setHome(Location loc, boolean b)
{
String worldName = loc.getWorld().getName().toLowerCase();
if (worldName == null || worldName.isEmpty())
{
logger.log(Level.WARNING, Util.i18n("emptyWorldName"));
return;
}
if (b || !config.hasProperty("home.default"))
{
config.setProperty("home.default", worldName);
}
config.setProperty("home.worlds." + worldName, loc);
config.save();
}
public String getNickname()
{
return config.getString("nickname");
}
public void setNickname(String nick)
{
config.setProperty("nickname", nick);
config.save();
}
private List<Integer> unlimited;
private List<Integer> _getUnlimited()
{
return config.getIntList("unlimited", new ArrayList<Integer>());
}
public List<Integer> getUnlimited()
{
return unlimited;
}
public boolean hasUnlimited(ItemStack stack)
{
return unlimited.contains(stack.getTypeId());
}
public void setUnlimited(ItemStack stack, boolean state)
{
if (unlimited.contains(stack.getTypeId()))
{
unlimited.remove(Integer.valueOf(stack.getTypeId()));
}
if (state)
{
unlimited.add(stack.getTypeId());
}
config.setProperty("unlimited", unlimited);
config.save();
}
private Map<Integer, String> powertools;
@SuppressWarnings("unchecked")
private Map<Integer, String> getPowertools()
{
Object o = config.getProperty("powertools");
if (o instanceof Map)
{
return (Map<Integer, String>)o;
}
else
{
return new HashMap<Integer, String>();
}
}
public String getPowertool(ItemStack stack)
{
return powertools.get(stack.getTypeId());
}
public void setPowertool(ItemStack stack, String command)
{
if (command == null || command.isEmpty())
{
powertools.remove(stack.getTypeId());
}
else
{
powertools.put(stack.getTypeId(), command);
}
config.setProperty("powertools", powertools);
config.save();
}
private Location lastLocation;
private Location _getLastLocation()
{
return config.getLocation("lastlocation", getServer());
}
public Location getLastLocation()
{
return lastLocation;
}
public void setLastLocation(Location loc)
{
lastLocation = loc;
config.setProperty("lastlocation", loc);
config.save();
}
private long lastTeleportTimestamp;
private long _getLastTeleportTimestamp()
{
return config.getLong("timestamps.lastteleport", 0);
}
public long getLastTeleportTimestamp()
{
return lastTeleportTimestamp;
}
public void setLastTeleportTimestamp(long time)
{
lastTeleportTimestamp = time;
config.setProperty("timestamps.lastteleport", time);
config.save();
}
private long lastHealTimestamp;
private long _getLastHealTimestamp()
{
return config.getLong("timestamps.lastheal", 0);
}
public long getLastHealTimestamp()
{
return lastHealTimestamp;
}
public void setLastHealTimestamp(long time)
{
lastHealTimestamp = time;
config.setProperty("timestamps.lastheal", time);
config.save();
}
private String jail;
private String _getJail()
{
return config.getString("jail");
}
public String getJail()
{
return jail;
}
public void setJail(String jail)
{
if (jail == null || jail.isEmpty())
{
this.jail = null;
config.removeProperty("jail");
}
else
{
this.jail = jail;
config.setProperty("jail", jail);
}
config.save();
}
private List<String> mails;
private List<String> _getMails()
{
return config.getStringList("mail", new ArrayList<String>());
}
public List<String> getMails()
{
return mails;
}
public void setMails(List<String> mails)
{
if (mails == null)
{
config.removeProperty("mail");
mails = _getMails();
}
else
{
config.setProperty("mail", mails);
}
this.mails = mails;
config.save();
}
public void addMail(String mail)
{
mails.add(mail);
setMails(mails);
}
private ItemStack[] savedInventory;
public ItemStack[] getSavedInventory()
{
return savedInventory;
}
private ItemStack[] _getSavedInventory()
{
int size = config.getInt("inventory.size", 0);
if (size < 1 || size > getInventory().getSize())
{
return null;
}
ItemStack[] is = new ItemStack[size];
for (int i = 0; i < size; i++)
{
is[i] = config.getItemStack("inventory." + i);
}
return is;
}
public void setSavedInventory(ItemStack[] is)
{
if (is == null || is.length == 0)
{
savedInventory = null;
config.removeProperty("inventory");
}
else
{
savedInventory = is;
config.setProperty("inventory.size", is.length);
for (int i = 0; i < is.length; i++)
{
if (is[i] == null || is[i].getType() == Material.AIR)
{
continue;
}
config.setProperty("inventory." + i, is[i]);
}
}
config.save();
}
private boolean teleportEnabled;
private boolean getTeleportEnabled()
{
return config.getBoolean("teleportenabled", true);
}
public boolean isTeleportEnabled()
{
return teleportEnabled;
}
public void setTeleportEnabled(boolean set)
{
teleportEnabled = set;
config.setProperty("teleportenabled", set);
config.save();
}
public boolean toggleTeleportEnabled()
{
boolean ret = !isTeleportEnabled();
setTeleportEnabled(ret);
return ret;
}
public boolean toggleSocialSpy()
{
boolean ret = !isSocialSpyEnabled();
setSocialSpyEnabled(ret);
return ret;
}
private List<String> ignoredPlayers;
public List<String> getIgnoredPlayers()
{
return config.getStringList("ignore", new ArrayList<String>());
}
public void setIgnoredPlayers(List<String> players)
{
if (players == null || players.isEmpty())
{
ignoredPlayers = new ArrayList<String>();
config.removeProperty("ignore");
}
else
{
ignoredPlayers = players;
config.setProperty("ignore", players);
}
config.save();
}
public boolean isIgnoredPlayer(String name)
{
return ignoredPlayers.contains(name.toLowerCase());
}
public void setIgnoredPlayer(String name, boolean set)
{
if (set)
{
ignoredPlayers.add(name.toLowerCase());
}
else
{
ignoredPlayers.remove(name.toLowerCase());
}
setIgnoredPlayers(ignoredPlayers);
}
private boolean godmode;
private boolean getGodModeEnabled()
{
return config.getBoolean("godmode", false);
}
public boolean isGodModeEnabled()
{
return godmode;
}
public void setGodModeEnabled(boolean set)
{
godmode = set;
config.setProperty("godmode", set);
config.save();
}
public boolean toggleGodModeEnabled()
{
boolean ret = !isGodModeEnabled();
setGodModeEnabled(ret);
return ret;
}
private boolean muted;
private boolean getMuted()
{
return config.getBoolean("muted", false);
}
public boolean isMuted()
{
return muted;
}
public void setMuted(boolean set)
{
muted = set;
config.setProperty("muted", set);
config.save();
}
public boolean toggleMuted()
{
boolean ret = !isMuted();
setMuted(ret);
return ret;
}
private long muteTimeout;
private long _getMuteTimeout()
{
return config.getLong("timestamps.mute", 0);
}
public long getMuteTimeout()
{
return muteTimeout;
}
public void setMuteTimeout(long time)
{
muteTimeout = time;
config.setProperty("timestamps.mute", time);
config.save();
}
private boolean jailed;
private boolean getJailed()
{
return config.getBoolean("jailed", false);
}
public boolean isJailed()
{
return jailed;
}
public void setJailed(boolean set)
{
jailed = set;
config.setProperty("jailed", set);
config.save();
}
public boolean toggleJailed()
{
boolean ret = !isJailed();
setJailed(ret);
return ret;
}
private long jailTimeout;
private long _getJailTimeout()
{
return config.getLong("timestamps.jail", 0);
}
public long getJailTimeout()
{
return jailTimeout;
}
public void setJailTimeout(long time)
{
jailTimeout = time;
config.setProperty("timestamps.jail", time);
config.save();
}
public String getBanReason()
{
return config.getString("ban.reason");
}
public void setBanReason(String reason)
{
config.setProperty("ban.reason", reason);
config.save();
}
public long getBanTimeout()
{
return config.getLong("ban.timeout", 0);
}
public void setBanTimeout(long time)
{
config.setProperty("ban.timeout", time);
config.save();
}
private long lastLogin;
private long _getLastLogin()
{
return config.getLong("timestamps.login", 0);
}
public long getLastLogin()
{
return lastLogin;
}
public void setLastLogin(long time)
{
lastLogin = time;
config.setProperty("timestamps.login", time);
config.save();
}
private long lastLogout;
private long _getLastLogout()
{
return config.getLong("timestamps.logout", 0);
}
public long getLastLogout()
{
return lastLogout;
}
public void setLastLogout(long time)
{
lastLogout = time;
config.setProperty("timestamps.logout", time);
config.save();
}
private boolean afk;
private boolean getAfk()
{
return config.getBoolean("afk", false);
}
public boolean isAfk()
{
return afk;
}
public void setAfk(boolean set)
{
afk = set;
config.setProperty("afk", set);
config.save();
}
public boolean toggleAfk()
{
boolean ret = !isAfk();
setAfk(ret);
return ret;
}
private boolean newplayer;
private boolean getNew()
{
return config.getBoolean("newplayer", true);
}
public boolean isNew()
{
return newplayer;
}
public void setNew(boolean set)
{
newplayer = set;
config.setProperty("newplayer", set);
config.save();
}
private String geolocation;
private String _getGeoLocation()
{
return config.getString("geolocation");
}
public String getGeoLocation()
{
return geolocation;
}
public void setGeoLocation(String geolocation)
{
if (geolocation == null || geolocation.isEmpty())
{
this.geolocation = null;
config.removeProperty("geolocation");
}
else
{
this.geolocation = geolocation;
config.setProperty("geolocation", geolocation);
}
config.save();
}
private boolean isSocialSpyEnabled;
private boolean _isSocialSpyEnabled()
{
return config.getBoolean("socialspy", false);
}
public boolean isSocialSpyEnabled()
{
return isSocialSpyEnabled;
}
public void setSocialSpyEnabled(boolean status)
{
isSocialSpyEnabled = status;
config.setProperty("socialspy", status);
config.save();
}
private boolean isNPC;
private boolean _isNPC()
{
return config.getBoolean("npc", false);
}
public boolean isNPC()
{
return isNPC;
}
public void setNPC(boolean set)
{
isNPC = set;
config.setProperty("npc", set);
config.save();
}
}

View File

@@ -1,95 +1,42 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.ISettings;
import com.earth2me.essentials.api.InvalidNameException;
import com.earth2me.essentials.external.gnu.inet.encoding.Punycode;
import com.earth2me.essentials.external.gnu.inet.encoding.PunycodeException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.Cleanup;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.PluginManager;
public final class Util
public class Util
{
private Util()
{
}
private final static Pattern INVALIDFILECHARS = Pattern.compile("[^\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]");
private final static Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]");
private final static Logger logger = Logger.getLogger("Minecraft");
public static String sanitizeFileName(String name) throws InvalidNameException
public static String sanitizeFileName(String name)
{
try
{
String r = name.toLowerCase(Locale.ENGLISH);
r = r.replace('.', (char)('\ue200' + '.'));
r = r.replace('\\', (char)('\ue200' + '\\'));
r = r.replace('/', (char)('\ue200' + '/'));
r = r.replace('"', (char)('\ue200' + '"'));
r = r.replace('<', (char)('\ue200' + '<'));
r = r.replace('>', (char)('\ue200' + '>'));
r = r.replace('|', (char)('\ue200' + '|'));
r = r.replace('?', (char)('\ue200' + '?'));
r = r.replace('*', (char)('\ue200' + '*'));
r = r.replace(':', (char)('\ue200' + ':'));
r = r.replace('-', (char)('\ue200' + '-'));
r = INVALIDFILECHARS.matcher(r).replaceAll("");
return Punycode.encode(r);
}
catch (PunycodeException ex)
{
throw new InvalidNameException(ex);
}
}
public static String decodeFileName(String name) throws InvalidNameException
{
try
{
String r = Punycode.decode(name);
r = r.replace((char)('\ue200' + '.'), '.');
r = r.replace((char)('\ue200' + '\\'), '\\');
r = r.replace((char)('\ue200' + '/'), '/');
r = r.replace((char)('\ue200' + '"'), '"');
r = r.replace((char)('\ue200' + '<'), '<');
r = r.replace((char)('\ue200' + '>'), '>');
r = r.replace((char)('\ue200' + '|'), '|');
r = r.replace((char)('\ue200' + '?'), '?');
r = r.replace((char)('\ue200' + '*'), '*');
r = r.replace((char)('\ue200' + ':'), ':');
r = r.replace((char)('\ue200' + '-'), '-');
return r;
}
catch (PunycodeException ex)
{
throw new InvalidNameException(ex);
}
}
public static String sanitizeKey(String name)
{
return INVALIDCHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_");
}
public static String sanitizeString(final String string)
{
return INVALIDCHARS.matcher(string).replaceAll("");
return name.toLowerCase().replaceAll("[^a-z0-9]", "_");
}
public static String formatDateDiff(long date)
@@ -105,7 +52,7 @@ public final class Util
boolean future = false;
if (toDate.equals(fromDate))
{
return _("now");
return Util.i18n("now");
}
if (toDate.after(fromDate))
{
@@ -124,18 +71,18 @@ public final class Util
};
String[] names = new String[]
{
_("year"),
_("years"),
_("month"),
_("months"),
_("day"),
_("days"),
_("hour"),
_("hours"),
_("minute"),
_("minutes"),
_("second"),
_("seconds")
Util.i18n("year"),
Util.i18n("years"),
Util.i18n("month"),
Util.i18n("months"),
Util.i18n("day"),
Util.i18n("days"),
Util.i18n("hour"),
Util.i18n("hours"),
Util.i18n("minute"),
Util.i18n("minutes"),
Util.i18n("second"),
Util.i18n("seconds")
};
for (int i = 0; i < types.length; i++)
{
@@ -235,7 +182,7 @@ public final class Util
}
if (!found)
{
throw new Exception(_("illegalDate"));
throw new Exception(Util.i18n("illegalDate"));
}
Calendar c = new GregorianCalendar();
if (years > 0)
@@ -268,118 +215,56 @@ public final class Util
}
return c.getTimeInMillis();
}
// The player can stand inside these materials
private static final Set<Integer> AIR_MATERIALS = new HashSet<Integer>();
private static final HashSet<Byte> AIR_MATERIALS_TARGET = new HashSet<Byte>();
static
public static Location getSafeDestination(Location loc) throws Exception
{
AIR_MATERIALS.add(Material.AIR.getId());
AIR_MATERIALS.add(Material.SAPLING.getId());
AIR_MATERIALS.add(Material.POWERED_RAIL.getId());
AIR_MATERIALS.add(Material.DETECTOR_RAIL.getId());
AIR_MATERIALS.add(Material.LONG_GRASS.getId());
AIR_MATERIALS.add(Material.DEAD_BUSH.getId());
AIR_MATERIALS.add(Material.YELLOW_FLOWER.getId());
AIR_MATERIALS.add(Material.RED_ROSE.getId());
AIR_MATERIALS.add(Material.BROWN_MUSHROOM.getId());
AIR_MATERIALS.add(Material.RED_MUSHROOM.getId());
AIR_MATERIALS.add(Material.TORCH.getId());
AIR_MATERIALS.add(Material.REDSTONE_WIRE.getId());
AIR_MATERIALS.add(Material.SEEDS.getId());
AIR_MATERIALS.add(Material.SIGN_POST.getId());
AIR_MATERIALS.add(Material.WOODEN_DOOR.getId());
AIR_MATERIALS.add(Material.LADDER.getId());
AIR_MATERIALS.add(Material.RAILS.getId());
AIR_MATERIALS.add(Material.WALL_SIGN.getId());
AIR_MATERIALS.add(Material.LEVER.getId());
AIR_MATERIALS.add(Material.STONE_PLATE.getId());
AIR_MATERIALS.add(Material.IRON_DOOR_BLOCK.getId());
AIR_MATERIALS.add(Material.WOOD_PLATE.getId());
AIR_MATERIALS.add(Material.REDSTONE_TORCH_OFF.getId());
AIR_MATERIALS.add(Material.REDSTONE_TORCH_ON.getId());
AIR_MATERIALS.add(Material.STONE_BUTTON.getId());
AIR_MATERIALS.add(Material.SUGAR_CANE_BLOCK.getId());
AIR_MATERIALS.add(Material.DIODE_BLOCK_OFF.getId());
AIR_MATERIALS.add(Material.DIODE_BLOCK_ON.getId());
AIR_MATERIALS.add(Material.TRAP_DOOR.getId());
AIR_MATERIALS.add(Material.PUMPKIN_STEM.getId());
AIR_MATERIALS.add(Material.MELON_STEM.getId());
AIR_MATERIALS.add(Material.VINE.getId());
AIR_MATERIALS.add(Material.NETHER_WARTS.getId());
AIR_MATERIALS.add(Material.WATER_LILY.getId());
for (Integer integer : AIR_MATERIALS)
if (loc == null)
{
AIR_MATERIALS_TARGET.add(integer.byteValue());
throw new Exception(Util.i18n("destinationNotSet"));
}
AIR_MATERIALS_TARGET.add((byte)Material.WATER.getId());
AIR_MATERIALS_TARGET.add((byte)Material.STATIONARY_WATER.getId());
}
public static Location getTarget(final LivingEntity entity) throws Exception
{
final Block block = entity.getTargetBlock(AIR_MATERIALS_TARGET, 300);
if (block == null)
{
throw new Exception("Not targeting a block");
}
return block.getLocation();
}
public static Location getSafeDestination(final Location loc) throws Exception
{
if (loc == null || loc.getWorld() == null)
{
throw new Exception(_("destinationNotSet"));
}
final World world = loc.getWorld();
int x = loc.getBlockX();
int y = (int)Math.round(loc.getY());
int z = loc.getBlockZ();
World world = loc.getWorld();
double x = Math.floor(loc.getX()) + 0.5;
double y = Math.floor(loc.getY());
double z = Math.floor(loc.getZ()) + 0.5;
while (isBlockAboveAir(world, x, y, z))
{
y -= 1;
if (y < 0)
y -= 1.0D;
if (y < 0.0D)
{
break;
throw new Exception(Util.i18n("holeInFloor"));
}
}
while (isBlockUnsafe(world, x, y, z))
{
y += 1;
if (y >= 127)
y += 1.0D;
if (y >= 110.0D)
{
x += 1;
x += 1.0D;
break;
}
}
while (isBlockUnsafe(world, x, y, z))
{
y -= 1;
if (y <= 1)
y -= 1.0D;
if (y <= 1.0D)
{
y = 127;
x += 1;
if (x - 32 > loc.getBlockX())
{
throw new Exception(_("holeInFloor"));
}
y = 110.0D;
x += 1.0D;
}
}
return new Location(world, x + 0.5D, y, z + 0.5D, loc.getYaw(), loc.getPitch());
return new Location(world, x, y, z, loc.getYaw(), loc.getPitch());
}
private static boolean isBlockAboveAir(final World world, final int x, final int y, final int z)
private static boolean isBlockAboveAir(World world, double x, double y, double z)
{
return AIR_MATERIALS.contains(world.getBlockAt(x, y - 1, z).getType().getId());
return world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)).getType() == Material.AIR;
}
public static boolean isBlockUnsafe(final World world, final int x, final int y, final int z)
public static boolean isBlockUnsafe(World world, double x, double y, double z)
{
final Block below = world.getBlockAt(x, y - 1, z);
Block below = world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z));
if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA)
{
return true;
@@ -390,103 +275,18 @@ public final class Util
return true;
}
if ((!AIR_MATERIALS.contains(world.getBlockAt(x, y, z).getType().getId()))
|| (!AIR_MATERIALS.contains(world.getBlockAt(x, y + 1, z).getType().getId())))
if ((world.getBlockAt((int)Math.floor(x), (int)Math.floor(y), (int)Math.floor(z)).getType() != Material.AIR)
|| (world.getBlockAt((int)Math.floor(x), (int)Math.floor(y + 1.0D), (int)Math.floor(z)).getType() != Material.AIR))
{
return true;
}
return isBlockAboveAir(world, x, y, z);
}
public static ItemStack convertBlockToItem(final Block block)
{
final ItemStack is = new ItemStack(block.getType(), 1, (short)0, block.getData());
switch (is.getType())
{
case WOODEN_DOOR:
is.setType(Material.WOOD_DOOR);
is.setDurability((short)0);
break;
case IRON_DOOR_BLOCK:
is.setType(Material.IRON_DOOR);
is.setDurability((short)0);
break;
case SIGN_POST:
case WALL_SIGN:
is.setType(Material.SIGN);
is.setDurability((short)0);
break;
case CROPS:
is.setType(Material.SEEDS);
is.setDurability((short)0);
break;
case CAKE_BLOCK:
is.setType(Material.CAKE);
is.setDurability((short)0);
break;
case BED_BLOCK:
is.setType(Material.BED);
is.setDurability((short)0);
break;
case REDSTONE_WIRE:
is.setType(Material.REDSTONE);
is.setDurability((short)0);
break;
case REDSTONE_TORCH_OFF:
case REDSTONE_TORCH_ON:
is.setType(Material.REDSTONE_TORCH_ON);
is.setDurability((short)0);
break;
case DIODE_BLOCK_OFF:
case DIODE_BLOCK_ON:
is.setType(Material.DIODE);
is.setDurability((short)0);
break;
case DOUBLE_STEP:
is.setType(Material.STEP);
break;
case TORCH:
case RAILS:
case LADDER:
case WOOD_STAIRS:
case COBBLESTONE_STAIRS:
case LEVER:
case STONE_BUTTON:
case FURNACE:
case DISPENSER:
case PUMPKIN:
case JACK_O_LANTERN:
case WOOD_PLATE:
case STONE_PLATE:
case PISTON_STICKY_BASE:
case PISTON_BASE:
case IRON_FENCE:
case THIN_GLASS:
case TRAP_DOOR:
case FENCE:
case FENCE_GATE:
case NETHER_FENCE:
is.setDurability((short)0);
break;
case FIRE:
return null;
case PUMPKIN_STEM:
is.setType(Material.PUMPKIN_SEEDS);
break;
case MELON_STEM:
is.setType(Material.MELON_SEEDS);
break;
}
return is;
}
private static DecimalFormat df = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US));
public static String formatCurrency(final double value, final IEssentials ess)
public static String formatCurrency(double value)
{
@Cleanup
final ISettings settings = ess.getSettings();
settings.acquireReadLock();
String str = settings.getData().getEconomy().getCurrencySymbol() + df.format(value);
String str = Essentials.getStatic().getSettings().getCurrencySymbol() + df.format(value);
if (str.endsWith(".00"))
{
str = str.substring(0, str.length() - 3);
@@ -494,156 +294,156 @@ public final class Util
return str;
}
public static double roundDouble(final double d)
public static double roundDouble(double d)
{
return Math.round(d * 100.0) / 100.0;
}
public static boolean isInt(final String sInt)
public static Locale getCurrentLocale()
{
try
{
Integer.parseInt(sInt);
}
catch (NumberFormatException e)
{
return false;
}
return true;
return currentLocale;
}
public static String joinList(Object... list)
{
return joinList(", ", list);
}
public static String joinList(String seperator, Object... list)
private static class ConfigClassLoader extends ClassLoader
{
StringBuilder buf = new StringBuilder();
for (Object each : list)
private final File dataFolder;
private final ClassLoader cl;
public ConfigClassLoader(File dataFolder, ClassLoader cl)
{
if (buf.length() > 0)
{
buf.append(seperator);
}
this.dataFolder = dataFolder;
this.cl = cl;
}
if (each instanceof Collection)
{
buf.append(joinList(seperator, ((Collection)each).toArray()));
}
else
@Override
public URL getResource(String string)
{
File file = new File(dataFolder, string);
if (file.exists())
{
try
{
buf.append(each.toString());
return file.toURI().toURL();
}
catch (Exception e)
catch (MalformedURLException ex)
{
buf.append(each.toString());
return cl.getResource(string);
}
}
return cl.getResource(string);
}
@Override
public synchronized void clearAssertionStatus()
{
cl.clearAssertionStatus();
}
@Override
public InputStream getResourceAsStream(String string)
{
File file = new File(dataFolder, string);
if (file.exists())
{
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String version = br.readLine();
br.close();
if (version == null || !version.equals("#version: " + Essentials.getStatic().getDescription().getVersion()))
{
logger.log(Level.WARNING, String.format("Translation file %s is not updated for Essentials version. Will use default.", file));
return cl.getResourceAsStream(string);
}
return new FileInputStream(file);
}
catch (IOException ex)
{
return cl.getResourceAsStream(string);
}
}
return cl.getResourceAsStream(string);
}
@Override
public Enumeration<URL> getResources(String string) throws IOException
{
return cl.getResources(string);
}
@Override
public Class<?> loadClass(String string) throws ClassNotFoundException
{
return cl.loadClass(string);
}
@Override
public synchronized void setClassAssertionStatus(String string, boolean bln)
{
cl.setClassAssertionStatus(string, bln);
}
@Override
public synchronized void setDefaultAssertionStatus(boolean bln)
{
cl.setDefaultAssertionStatus(bln);
}
@Override
public synchronized void setPackageAssertionStatus(String string, boolean bln)
{
cl.setPackageAssertionStatus(string, bln);
}
}
private static final Locale defaultLocale = Locale.getDefault();
private static Locale currentLocale = defaultLocale;
private static ResourceBundle bundle = ResourceBundle.getBundle("messages", defaultLocale);
private static ResourceBundle defaultBundle = ResourceBundle.getBundle("messages", Locale.US);
public static String i18n(String string)
{
try
{
return bundle.getString(string);
}
catch (MissingResourceException ex)
{
logger.log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), bundle.getLocale().toString()), ex);
return defaultBundle.getString(string);
}
return buf.toString();
}
public static void registerPermissions(String path, Collection<String> nodes, boolean hasDefault, IEssentials ess)
public static String format(String string, Object... objects)
{
if (nodes == null || nodes.isEmpty())
MessageFormat mf = new MessageFormat(i18n(string));
return mf.format(objects);
}
public static void updateLocale(String loc, File dataFolder)
{
if (loc == null || loc.isEmpty())
{
return;
}
final PluginManager pluginManager = ess.getServer().getPluginManager();
Permission basePerm = pluginManager.getPermission(path + ".*");
if (basePerm != null && !basePerm.getChildren().isEmpty())
String[] parts = loc.split("[_\\.]");
if (parts.length == 1)
{
basePerm.getChildren().clear();
currentLocale = new Locale(parts[0]);
}
if (basePerm == null)
if (parts.length == 2)
{
basePerm = new Permission(path + ".*", PermissionDefault.OP);
pluginManager.addPermission(basePerm);
Permission mainPerm = pluginManager.getPermission("essentials.*");
if (mainPerm == null)
{
mainPerm = new Permission("essentials.*", PermissionDefault.OP);
pluginManager.addPermission(mainPerm);
}
mainPerm.getChildren().put(basePerm.getName(), Boolean.TRUE);
currentLocale = new Locale(parts[0], parts[1]);
}
for (String nodeName : nodes)
if (parts.length == 3)
{
final String permissionName = path + "." + nodeName;
Permission perm = pluginManager.getPermission(permissionName);
if (perm == null)
{
final PermissionDefault defaultPerm = hasDefault && nodeName.equalsIgnoreCase("default") ? PermissionDefault.TRUE : PermissionDefault.OP;
perm = new Permission(permissionName, defaultPerm);
pluginManager.addPermission(perm);
}
basePerm.getChildren().put(permissionName, Boolean.TRUE);
currentLocale = new Locale(parts[0], parts[1], parts[2]);
}
basePerm.recalculatePermissibles();
}
private static transient final Pattern DOT_PATTERN = Pattern.compile("\\.");
public static Permission registerPermission(String permission, PermissionDefault defaultPerm)
{
final PluginManager pluginManager = Bukkit.getServer().getPluginManager();
final String[] parts = DOT_PATTERN.split(permission);
final StringBuilder builder = new StringBuilder(permission.length());
Permission parent = null;
for (int i = 0; i < parts.length - 1; i++)
logger.log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
bundle = ResourceBundle.getBundle("messages", currentLocale, new ConfigClassLoader(dataFolder, Util.class.getClassLoader()));
if (!bundle.keySet().containsAll(defaultBundle.keySet()))
{
builder.append(parts[i]).append(".*");
String permString = builder.toString();
Permission perm = pluginManager.getPermission(permString);
if (perm == null)
{
perm = new Permission(permString, PermissionDefault.FALSE);
pluginManager.addPermission(perm);
if (parent != null)
{
parent.getChildren().put(perm.getName(), Boolean.TRUE);
}
parent = perm;
}
builder.deleteCharAt(builder.length() - 1);
logger.log(Level.WARNING, String.format("Translation file %s does not contain all translation keys.", currentLocale.toString()));
}
Permission perm = pluginManager.getPermission(permission);
if (perm == null)
{
perm = new Permission(permission, defaultPerm);
pluginManager.addPermission(perm);
if (parent != null)
{
parent.getChildren().put(perm.getName(), Boolean.TRUE);
}
parent = perm;
}
perm.recalculatePermissibles();
return perm;
}
private static transient final Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00A7+[0-9A-FKa-fk]");
private static transient final Pattern EASY_COLOR_PATTERN = Pattern.compile("&([0-9a-fk])");
public static String stripColor(final String input)
{
if (input == null)
{
return null;
}
return VANILLA_COLOR_PATTERN.matcher(input).replaceAll("");
}
public static String replaceColor(final String input)
{
if (input == null)
{
return null;
}
return EASY_COLOR_PATTERN.matcher(input).replaceAll("\u00a7$1");
}
}

View File

@@ -1,121 +1,122 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.IWarp;
import com.earth2me.essentials.api.IWarps;
import com.earth2me.essentials.api.InvalidNameException;
import com.earth2me.essentials.commands.WarpNotFoundException;
import com.earth2me.essentials.settings.WarpHolder;
import com.earth2me.essentials.storage.StorageObjectMap;
import java.io.File;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
public class Warps extends StorageObjectMap<IWarp> implements IWarps
public class Warps implements IConf
{
private static final Logger logger = Bukkit.getLogger();
private static final Logger logger = Logger.getLogger("Minecraft");
private final Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>();
private final File warpsFolder;
private final Server server;
public Warps(IEssentials ess)
public Warps(Server server, File dataFolder)
{
super(ess, "warps");
this.server = server;
warpsFolder = new File(dataFolder, "warps");
if (!warpsFolder.exists())
{
warpsFolder.mkdirs();
}
reloadConfig();
}
@Override
public boolean isEmpty()
{
return getKeySize() == 0;
return warpPoints.isEmpty();
}
@Override
public Collection<String> getList()
public Iterable<String> getWarpNames()
{
final List<String> names = new ArrayList<String>();
for (String key : getAllKeys())
List<String> keys = new ArrayList<String>();
for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet())
{
IWarp warp = getObject(key);
if (warp == null)
keys.add(stringIgnoreCase.getString());
}
Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
return keys;
}
public Location getWarp(String warp) throws Exception
{
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
if (conf == null)
{
throw new Exception(Util.i18n("warpNotExist"));
}
return conf.getLocation(null, server);
}
public void setWarp(String name, Location loc) throws Exception
{
String filename = Util.sanitizeFileName(name);
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null)
{
File confFile = new File(warpsFolder, filename + ".yml");
if (confFile.exists())
{
continue;
throw new Exception(Util.i18n("similarWarpExist"));
}
warp.acquireReadLock();
try
conf = new EssentialsConf(confFile);
warpPoints.put(new StringIgnoreCase(name), conf);
}
conf.setProperty(null, loc);
conf.setProperty("name", name);
conf.save();
}
public void delWarp(String name) throws Exception
{
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null)
{
throw new Exception(Util.i18n("warpNotExist"));
}
if (!conf.getFile().delete())
{
throw new Exception(Util.i18n("warpDeleteError"));
}
warpPoints.remove(new StringIgnoreCase(name));
}
public final void reloadConfig()
{
warpPoints.clear();
File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1)
{
for (int i = 0; i < listOfFiles.length; i++)
{
names.add(warp.getData().getName());
}
finally
{
warp.unlock();
String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".yml"))
{
try
{
EssentialsConf conf = new EssentialsConf(listOfFiles[i]);
conf.load();
String name = conf.getString("name");
if (name != null)
{
warpPoints.put(new StringIgnoreCase(name), conf);
}
}
catch (Exception ex)
{
logger.log(Level.WARNING, Util.format("loadWarpError", filename), ex);
}
}
}
}
Collections.sort(names, String.CASE_INSENSITIVE_ORDER);
return names;
}
@Override
public Location getWarp(final String name) throws Exception
{
IWarp warp = getObject(name);
if (warp == null)
{
throw new WarpNotFoundException(_("warpNotExist"));
}
warp.acquireReadLock();
try
{
return warp.getData().getLocation().getBukkitLocation();
}
finally
{
warp.unlock();
}
}
@Override
public void setWarp(final String name, final Location loc) throws Exception
{
setWarp(name, new com.earth2me.essentials.storage.Location(loc));
}
public void setWarp(final String name, final com.earth2me.essentials.storage.Location loc) throws Exception
{
IWarp warp = getObject(name);
if (warp == null)
{
warp = new WarpHolder(name, ess);
}
warp.acquireWriteLock();
try
{
warp.getData().setLocation(loc);
}
finally
{
warp.unlock();
}
}
@Override
public void removeWarp(final String name) throws Exception
{
removeObject(name);
}
@Override
public File getWarpFile(String name) throws InvalidNameException
{
return getStorageFile(name);
}
@Override
public IWarp load(String name) throws Exception
{
final IWarp warp = new WarpHolder(name, ess);
warp.onReload();
return warp;
}
@@ -131,7 +132,7 @@ public class Warps extends StorageObjectMap<IWarp> implements IWarps
@Override
public int hashCode()
{
return getString().toLowerCase(Locale.ENGLISH).hashCode();
return getString().toLowerCase().hashCode();
}
@Override

View File

@@ -1,86 +1,54 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IEssentials;
import com.earth2me.essentials.api.IWorth;
import com.earth2me.essentials.storage.AsyncStorageObjectHolder;
import com.earth2me.essentials.storage.EnchantmentLevel;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.enchantments.Enchantment;
import java.util.logging.Logger;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
public class Worth extends AsyncStorageObjectHolder<com.earth2me.essentials.settings.Worth> implements IWorth
public class Worth implements IConf
{
public Worth(final IEssentials ess)
private static final Logger logger = Logger.getLogger("Minecraft");
private final EssentialsConf config;
public Worth(File dataFolder)
{
super(ess, com.earth2me.essentials.settings.Worth.class);
onReload(false);
config = new EssentialsConf(new File(dataFolder, "worth.yml"));
config.setTemplateName("/worth.yml");
config.load();
}
@Override
public double getPrice(final ItemStack itemStack)
public double getPrice(ItemStack itemStack)
{
this.acquireReadLock();
try
{
final Map<MaterialData, Double> prices = this.getData().getSell();
if (prices == null || itemStack == null)
{
return Double.NaN;
}
final Double basePrice = prices.get(itemStack.getData());
if (basePrice == null || Double.isNaN(basePrice))
{
return Double.NaN;
}
double multiplier = 1.0;
if (itemStack.getType().getMaxDurability() > 0) {
multiplier *= (double)itemStack.getDurability() / (double)itemStack.getType().getMaxDurability();
}
if (itemStack.getEnchantments() != null && !itemStack.getEnchantments().isEmpty())
{
final Map<EnchantmentLevel, Double> enchantmentMultipliers = this.getData().getEnchantmentMultiplier();
if (enchantmentMultipliers != null)
{
for (Map.Entry<Enchantment, Integer> entry : itemStack.getEnchantments().entrySet())
{
final Double enchMult = enchantmentMultipliers.get(new EnchantmentLevel(entry.getKey(), entry.getValue()));
if (enchMult != null)
{
multiplier *= enchMult;
}
}
}
}
return basePrice * multiplier;
String itemname = itemStack.getType().toString().toLowerCase().replace("_", "");
double result;
result = config.getDouble("worth."+itemname+"."+itemStack.getDurability(), Double.NaN);
if (Double.isNaN(result)) {
result = config.getDouble("worth."+itemname+".0", Double.NaN);
}
finally
{
this.unlock();
if (Double.isNaN(result)) {
result = config.getDouble("worth."+itemname, Double.NaN);
}
if (Double.isNaN(result)) {
result = config.getDouble("worth-"+itemStack.getTypeId(), Double.NaN);
}
return result;
}
@Override
public void setPrice(final ItemStack itemStack, final double price)
public void setPrice(ItemStack itemStack, double price)
{
acquireWriteLock();
try {
if (getData().getSell() == null) {
getData().setSell(new HashMap<MaterialData, Double>());
}
getData().getSell().put(itemStack.getData(), price);
} finally {
unlock();
if (itemStack.getType().getData() == null) {
config.setProperty("worth." + itemStack.getType().toString().toLowerCase().replace("_", ""), price);
} else {
// Bukkit-bug: getDurability still contains the correct value, while getData().getData() is 0.
config.setProperty("worth." + itemStack.getType().toString().toLowerCase().replace("_", "")+"."+itemStack.getDurability(), price);
}
config.removeProperty("worth-"+itemStack.getTypeId());
config.save();
}
@Override
public File getStorageFile() throws IOException
public void reloadConfig()
{
return new File(ess.getDataFolder(), "worth.yml");
config.load();
}
}

View File

@@ -1,15 +0,0 @@
package com.earth2me.essentials.api;
public class ChargeException extends Exception
{
public ChargeException(final String message)
{
super(message);
}
public ChargeException(final String message, final Throwable throwable)
{
super(message, throwable);
}
}

View File

@@ -1,7 +1,13 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.EssentialsConf;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.entity.Player;
/**
* Instead of using this api directly, we recommend to use the register plugin:
@@ -12,8 +18,53 @@ public final class Economy
private Economy()
{
}
private static IEssentials ess;
private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded.";
private static final Logger logger = Logger.getLogger("Minecraft");
private static void createNPCFile(String name)
{
File folder = new File(Essentials.getStatic().getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
EssentialsConf npcConfig = new EssentialsConf(new File(folder, Util.sanitizeFileName(name) + ".yml"));
npcConfig.load();
npcConfig.setProperty("npc", true);
npcConfig.setProperty("money", Essentials.getStatic().getSettings().getStartingBalance());
npcConfig.save();
}
private static void deleteNPC(String name)
{
File folder = new File(Essentials.getStatic().getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
File config = new File(folder, Util.sanitizeFileName(name) + ".yml");
EssentialsConf npcConfig = new EssentialsConf(config);
npcConfig.load();
if (npcConfig.hasProperty("npc") && npcConfig.getBoolean("npc", false)) {
if (!config.delete()) {
logger.log(Level.WARNING, Util.format("deleteFileError", config));
}
}
}
private static User getUserByName(String name)
{
User user;
Player player = Essentials.getStatic().getServer().getPlayer(name);
if (player != null)
{
user = Essentials.getStatic().getUser(player);
}
else
{
user = Essentials.getStatic().getOfflineUser(name);
}
return user;
}
/**
* Returns the balance of a user
@@ -23,11 +74,11 @@ public final class Economy
*/
public static double getMoney(String name) throws UserDoesNotExistException
{
if (ess == null)
{
throw new RuntimeException(noCallBeforeLoad);
User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return ess.getEconomy().getMoney(name);
return user.getMoney();
}
/**
@@ -39,11 +90,15 @@ public final class Economy
*/
public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException
{
if (ess == null)
{
throw new RuntimeException(noCallBeforeLoad);
User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
ess.getEconomy().setMoney(name, balance);
if (balance < 0.0 && !user.isAuthorized("essentials.eco.loan"))
{
throw new NoLoanPermittedException();
}
user.setMoney(balance);
}
/**
@@ -58,7 +113,7 @@ public final class Economy
double result = getMoney(name) + amount;
setMoney(name, result);
}
/**
* Substracts money from the balance of a user
* @param name Name of the user
@@ -106,11 +161,7 @@ public final class Economy
*/
public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException
{
if (ess == null)
{
throw new RuntimeException(noCallBeforeLoad);
}
ess.getEconomy().resetBalance(name);
setMoney(name, Essentials.getStatic().getSettings().getStartingBalance());
}
/**
@@ -165,27 +216,18 @@ public final class Economy
*/
public static String format(double amount)
{
if (ess == null)
{
throw new RuntimeException(noCallBeforeLoad);
}
return Util.formatCurrency(amount, ess);
return Util.formatCurrency(amount);
}
/**
* Test if a player exists to avoid the UserDoesNotExistException
* @param name Name of the user
* @return true, if the user exists
*/
public static boolean playerExists(String name)
{
if (ess == null)
{
throw new RuntimeException(noCallBeforeLoad);
}
return ess.getEconomy().playerExists(name);
public static boolean playerExists(String name) {
return getUserByName(name) != null;
}
/**
* Test if a player is a npc
* @param name Name of the player
@@ -194,13 +236,13 @@ public final class Economy
*/
public static boolean isNPC(String name) throws UserDoesNotExistException
{
if (ess == null)
{
throw new RuntimeException(noCallBeforeLoad);
User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return ess.getEconomy().isNPC(name);
return user.isNPC();
}
/**
* Creates dummy files for a npc, if there is no player yet with that name.
* @param name Name of the player
@@ -208,11 +250,12 @@ public final class Economy
*/
public static boolean createNPC(String name)
{
if (ess == null)
{
throw new RuntimeException(noCallBeforeLoad);
User user = getUserByName(name);
if (user == null) {
createNPCFile(name);
return true;
}
return ess.getEconomy().createNPC(name);
return false;
}
/**
@@ -222,10 +265,10 @@ public final class Economy
*/
public static void removeNPC(String name) throws UserDoesNotExistException
{
if (ess == null)
{
throw new RuntimeException(noCallBeforeLoad);
User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
ess.getEconomy().removeNPC(name);
deleteNPC(name);
}
}

View File

@@ -1,7 +0,0 @@
package com.earth2me.essentials.api;
public interface IBackup extends Runnable
{
public void startTask();
}

View File

@@ -1,20 +0,0 @@
package com.earth2me.essentials.api;
import java.util.Map;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
public interface ICommandHandler extends IReload
{
Map<String, String> disabledCommands();
public void removePlugin(Plugin plugin);
public void addPlugin(Plugin plugin);
boolean handleCommand(CommandSender sender, Command command, String commandLabel, String[] args);
void showCommandError(CommandSender sender, String commandLabel, Throwable exception);
}

View File

@@ -1,21 +0,0 @@
package com.earth2me.essentials.api;
public interface IEconomy extends IReload
{
public double getMoney(String name) throws UserDoesNotExistException;
public void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException;
public void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException;
public String format(double amount);
public boolean playerExists(String name);
public boolean isNPC(String name) throws UserDoesNotExistException;
public boolean createNPC(String name);
public void removeNPC(String name) throws UserDoesNotExistException;
}

View File

@@ -1,64 +0,0 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.listener.TntExplodeListener;
import com.earth2me.essentials.register.payment.Methods;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public interface IEssentials extends Plugin
{
void addReloadListener(IReload listener);
IUser getUser(Player player);
IUser getUser(String playerName);
int broadcastMessage(IUser sender, String message);
II18n getI18n();
ISettings getSettings();
IGroups getGroups();
IJails getJails();
IKits getKits();
IWarps getWarps();
IWorth getWorth();
IItemDb getItemDb();
IUserMap getUserMap();
IBackup getBackup();
ICommandHandler getCommandHandler();
World getWorld(String name);
Methods getPaymentMethod();
int scheduleAsyncDelayedTask(Runnable run);
int scheduleSyncDelayedTask(Runnable run);
int scheduleSyncDelayedTask(Runnable run, long delay);
int scheduleSyncRepeatingTask(Runnable run, long delay, long period);
//IPermissionsHandler getPermissionsHandler();
void reload();
TntExplodeListener getTNTListener();
void setGroups(IGroups groups);
void removeReloadListener(IReload groups);
IEconomy getEconomy();
}

View File

@@ -1,6 +0,0 @@
package com.earth2me.essentials.api;
public interface IEssentialsModule
{
}

View File

@@ -1,25 +0,0 @@
package com.earth2me.essentials.api;
import java.text.MessageFormat;
public interface IGroups
{
String getMainGroup(IUser player);
boolean inGroup(IUser player, String groupname);
double getHealCooldown(IUser player);
double getTeleportCooldown(IUser player);
double getTeleportDelay(IUser player);
String getPrefix(IUser player);
String getSuffix(IUser player);
int getHomeLimit(IUser player);
MessageFormat getChatFormat(IUser player);
}

View File

@@ -1,9 +0,0 @@
package com.earth2me.essentials.api;
import java.util.Locale;
public interface II18n
{
Locale getCurrentLocale();
}

View File

@@ -1,13 +0,0 @@
package com.earth2me.essentials.api;
import org.bukkit.inventory.ItemStack;
public interface IItemDb extends IReload
{
ItemStack get(final String name, final IUser user) throws Exception;
ItemStack get(final String name, final int quantity) throws Exception;
ItemStack get(final String name) throws Exception;
}

View File

@@ -1,18 +0,0 @@
package com.earth2me.essentials.api;
import java.util.Collection;
import org.bukkit.Location;
public interface IJails extends IReload
{
Location getJail(String jailName) throws Exception;
Collection<String> getList() throws Exception;
void removeJail(String jail) throws Exception;
void sendToJail(IUser user, String jail) throws Exception;
void setJail(String jailName, Location loc) throws Exception;
}

View File

@@ -1,18 +0,0 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.settings.Kit;
import java.util.Collection;
public interface IKits extends IReload
{
Kit getKit(String kit) throws Exception;
void sendKit(IUser user, String kit) throws Exception;
void sendKit(IUser user, Kit kit) throws Exception;
Collection<String> getList() throws Exception;
boolean isEmpty();
}

View File

@@ -1,17 +0,0 @@
package com.earth2me.essentials.api;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
public interface IPermission
{
String getPermission();
boolean isAuthorized(CommandSender sender);
Permission getBukkitPermission();
PermissionDefault getPermissionDefault();
}

View File

@@ -1,7 +0,0 @@
package com.earth2me.essentials.api;
public interface IReload
{
void onReload();
}

View File

@@ -1,11 +0,0 @@
package com.earth2me.essentials.api;
import org.bukkit.command.CommandSender;
public interface IReplyTo
{
void setReplyTo(CommandSender user);
CommandSender getReplyTo();
}

View File

@@ -1,14 +0,0 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.settings.Settings;
import com.earth2me.essentials.storage.IStorageObjectHolder;
public interface ISettings extends IStorageObjectHolder<Settings>
{
public String getLocale();
public boolean isDebug();
public void setDebug(boolean b);
}

View File

@@ -1,28 +0,0 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.Trade;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public interface ITeleport
{
void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception;
void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception;
void back(Trade chargeFor) throws Exception;
void teleport(Location bed, Trade charge, TeleportCause teleportCause) throws Exception;
void teleport(Entity entity, Trade chargeFor, TeleportCause cause) throws Exception;
void home(IUser player, String toLowerCase, Trade charge) throws Exception;
void respawn(Trade charge, TeleportCause teleportCause) throws Exception;
void back() throws Exception;
public void warp(String name, Trade charge, TeleportCause teleportCause) throws Exception;
}

View File

@@ -1,104 +0,0 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.storage.IStorageObjectHolder;
import com.earth2me.essentials.user.CooldownException;
import com.earth2me.essentials.user.UserData;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public interface IUser extends Player, IStorageObjectHolder<UserData>, IReload, IReplyTo, Comparable<IUser>
{
Player getBase();
double getMoney();
void takeMoney(double value);
void takeMoney(double value, CommandSender initiator);
void giveMoney(double value);
void giveMoney(double value, CommandSender initiator);
void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException;
void giveItems(List<ItemStack> itemStacks, Boolean canSpew) throws ChargeException;
void setMoney(double value);
void payUser(final IUser reciever, final double value) throws Exception;
void setLastLocation();
Location getHome(String name) throws Exception;
Location getHome(Location loc);
boolean isHidden();
ITeleport getTeleport();
void checkCooldown(UserData.TimestampType cooldownType, double cooldown, boolean set, IPermission bypassPermission) throws CooldownException;
boolean toggleAfk();
void updateActivity(boolean broadcast);
void updateDisplayName();
boolean checkJailTimeout(long currentTime);
boolean checkMuteTimeout(long currentTime);
boolean checkBanTimeout(long currentTime);
long getTimestamp(UserData.TimestampType name);
void setTimestamp(UserData.TimestampType name, long value);
void setLastOnlineActivity(long currentTime);
void checkActivity();
long getLastOnlineActivity();
boolean isGodModeEnabled();
boolean isIgnoringPlayer(String name);
void setIgnoredPlayer(String name, boolean set);
Location getAfkPosition();
boolean toggleGodModeEnabled();
void dispose();
void updateCompass();
List<String> getHomes();
void addMail(String string);
boolean toggleMuted();
boolean toggleSocialSpy();
void requestTeleport(IUser user, boolean b);
boolean isTeleportRequestHere();
IUser getTeleportRequester();
boolean toggleTeleportEnabled();
long getTeleportRequestTime();
boolean gotMailInfo();
List<String> getMails();
}

View File

@@ -1,23 +0,0 @@
package com.earth2me.essentials.api;
import java.io.File;
import java.util.Set;
import org.bukkit.entity.Player;
public interface IUserMap extends IReload
{
boolean userExists(final String name);
IUser getUser(final Player player);
IUser getUser(final String playerName);
void removeUser(final String name) throws InvalidNameException;
Set<String> getAllUniqueUsers();
int getUniqueUsers();
File getUserFile(final String name) throws InvalidNameException;
}

View File

@@ -1,9 +0,0 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.settings.Warp;
import com.earth2me.essentials.storage.IStorageObjectHolder;
public interface IWarp extends IStorageObjectHolder<Warp>
{
}

View File

@@ -1,21 +0,0 @@
package com.earth2me.essentials.api;
import java.io.File;
import java.util.Collection;
import org.bukkit.Location;
public interface IWarps extends IReload
{
Location getWarp(String warp) throws Exception;
Collection<String> getList();
void removeWarp(String name) throws Exception;
void setWarp(String name, Location loc) throws Exception;
public boolean isEmpty();
public File getWarpFile(String name) throws InvalidNameException;
}

View File

@@ -1,11 +0,0 @@
package com.earth2me.essentials.api;
import org.bukkit.inventory.ItemStack;
public interface IWorth extends IReload
{
double getPrice(ItemStack itemStack);
void setPrice(ItemStack itemStack, double price);
}

View File

@@ -1,10 +0,0 @@
package com.earth2me.essentials.api;
public class InvalidNameException extends Exception
{
public InvalidNameException(Throwable thrwbl)
{
super(thrwbl);
}
}

View File

@@ -1,12 +1,13 @@
package com.earth2me.essentials.api;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Util;
public class NoLoanPermittedException extends Exception
{
public NoLoanPermittedException()
{
super(_("negativeBalanceError"));
super(Util.i18n("negativeBalanceError"));
}
}

View File

@@ -1,12 +1,13 @@
package com.earth2me.essentials.api;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Util;
public class UserDoesNotExistException extends Exception
{
public UserDoesNotExistException(String name)
{
super(_("userDoesNotExist", name));
super(Util.format("userDoesNotExist", name));
}
}

View File

@@ -1,55 +1,29 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.perm.Permissions;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.Server;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandafk extends EssentialsCommand
{
@Override
public void run(final IUser user, final String commandLabel, final String[] args) throws Exception
public Commandafk()
{
if (args.length > 0 && Permissions.AFK_OTHERS.isAuthorized(user))
{
IUser afkUser = ess.getUser((Player)ess.getServer().matchPlayer(args[0]));
if (afkUser != null)
{
toggleAfk(afkUser);
}
}
else
{
toggleAfk(user);
}
super("afk");
}
private void toggleAfk(IUser user)
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
charge(user);
if (!user.toggleAfk())
{
//user.sendMessage(_("markedAsNotAway"));
if (!user.isHidden())
{
ess.broadcastMessage(user, _("userIsNotAway", user.getDisplayName()));
}
user.updateActivity(false);
user.sendMessage(Util.i18n("markedAsNotAway"));
ess.broadcastMessage(user.getName(), Util.format("userIsNotAway", user.getDisplayName()));
} else {
user.sendMessage(Util.i18n("markedAsAway"));
ess.broadcastMessage(user.getName(), Util.format("userIsAway", user.getDisplayName()));
}
else
{
//user.sendMessage(_("markedAsAway"));
if (!user.isHidden())
{
ess.broadcastMessage(user, _("userIsAway", user.getDisplayName()));
}
}
}
@Override
public PermissionDefault getPermissionDefault()
{
return PermissionDefault.TRUE;
}
}

View File

@@ -1,20 +1,33 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Util;
import com.earth2me.essentials.api.IUser;
import net.minecraft.server.EntityTNTPrimed;
import net.minecraft.server.World;
import org.bukkit.Location;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.Server;
import org.bukkit.craftbukkit.CraftWorld;
import com.earth2me.essentials.User;
import com.earth2me.essentials.TargetBlock;
public class Commandantioch extends EssentialsCommand
{
@Override
public void run(final IUser user, final String commandLabel, final String[] args) throws Exception
public Commandantioch()
{
ess.broadcastMessage(user, "...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,");
ess.broadcastMessage(user, "who being naughty in My sight, shall snuff it.");
super("antioch");
}
final Location loc = Util.getTarget(user);
loc.getWorld().spawn(loc, TNTPrimed.class);
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
charge(user);
ess.broadcastMessage(user.getName(), "...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,");
ess.broadcastMessage(user.getName(), "who being naughty in My sight, shall snuff it.");
Location loc = user.getLocation();
World world = ((CraftWorld)user.getWorld()).getHandle();
loc = new TargetBlock(user).getTargetBlock().getLocation();
EntityTNTPrimed tnt = new EntityTNTPrimed(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
world.addEntity(tnt);
world.makeSound(tnt, "random.fuse", 1.0F, 1.0F);
}
}

View File

@@ -1,19 +1,24 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.Charge;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.Server;
public class Commandback extends EssentialsCommand
{
@Override
protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception
public Commandback()
{
final Trade charge = new Trade(commandName, ess);
super("back");
}
@Override
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
Charge charge = new Charge(this.getName(), ess);
charge.isAffordableFor(user);
user.sendMessage(_("backUsageMsg"));
user.sendMessage(Util.i18n("backUsageMsg"));
user.getTeleport().back(charge);
throw new NoChargeException();
}
}

View File

@@ -1,17 +1,28 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IBackup;
import com.earth2me.essentials.Backup;
import com.earth2me.essentials.Util;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
public class Commandbackup extends EssentialsCommand
{
@Override
protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception
public Commandbackup()
{
final IBackup backup = ess.getBackup();
super("backup");
}
@Override
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
Backup backup = ess.getBackup();
if (backup == null)
{
return;
}
charge(sender);
backup.run();
sender.sendMessage(_("backupStarted"));
sender.sendMessage(Util.i18n("backupStarted"));
}
}

View File

@@ -1,31 +1,37 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import org.bukkit.Server;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.perm.Permissions;
import org.bukkit.command.CommandSender;
public class Commandbalance extends EssentialsCommand
{
public Commandbalance()
{
super("balance");
}
@Override
protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
sender.sendMessage(_("balance", Util.formatCurrency(getPlayer(args, 0, true).getMoney(), ess)));
sender.sendMessage(Util.format("balance", Util.formatCurrency(getPlayer(server, args, 0).getMoney())));
}
@Override
public void run(final IUser user, final String commandLabel, final String[] args) throws Exception
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
final double bal = (args.length < 1
|| !Permissions.BALANCE_OTHERS.isAuthorized(user)
? user
: getPlayer(args, 0, true)).getMoney();
user.sendMessage(_("balance", Util.formatCurrency(bal, ess)));
charge(user);
double bal = (args.length < 1
|| !(user.isAuthorized("essentials.balance.others")
|| user.isAuthorized("essentials.balance.other"))
? user
: getPlayer(server, args, 0)).getMoney();
user.sendMessage(Util.format("balance", Util.formatCurrency(bal)));
}
}

View File

@@ -1,173 +0,0 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Util;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.textreader.ArrayListInput;
import com.earth2me.essentials.textreader.TextPager;
import java.text.DateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.bukkit.command.CommandSender;
public class Commandbalancetop extends EssentialsCommand
{
private static final int CACHETIME = 2 * 60 * 1000;
public static final int MINUSERS = 50;
private static ArrayListInput cache = new ArrayListInput();
private static long cacheage = 0;
private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
@Override
protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
int page = 0;
boolean force = false;
if (args.length > 0)
{
try
{
page = Integer.parseInt(args[0]);
}
catch (NumberFormatException ex)
{
if (args[0].equalsIgnoreCase("force") && sender.isOp())
{
force = true;
}
}
}
if (!force && lock.readLock().tryLock())
{
try
{
if (cacheage > System.currentTimeMillis() - CACHETIME)
{
outputCache(sender, page);
return;
}
if (ess.getUserMap().getUniqueUsers() > MINUSERS)
{
sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers()));
}
}
finally
{
lock.readLock().unlock();
}
ess.scheduleAsyncDelayedTask(new Viewer(sender, page, force));
}
else
{
if (ess.getUserMap().getUniqueUsers() > MINUSERS)
{
sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers()));
}
ess.scheduleAsyncDelayedTask(new Viewer(sender, page, force));
}
}
private static void outputCache(final CommandSender sender, int page)
{
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cacheage);
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
sender.sendMessage(_("balanceTop", format.format(cal.getTime())));
new TextPager(cache).showPage(Integer.toString(page), "", "balancetop", sender);
}
private class Calculator implements Runnable
{
private final transient Viewer viewer;
private final boolean force;
public Calculator(final Viewer viewer, final boolean force)
{
this.viewer = viewer;
this.force = force;
}
@Override
public void run()
{
lock.writeLock().lock();
try
{
if (force || cacheage <= System.currentTimeMillis() - CACHETIME)
{
cache.getLines().clear();
final Map<String, Double> balances = new HashMap<String, Double>();
for (String u : ess.getUserMap().getAllUniqueUsers())
{
final IUser user = ess.getUserMap().getUser(u);
if (user != null)
{
balances.put(user.getDisplayName(), user.getMoney());
}
}
final List<Map.Entry<String, Double>> sortedEntries = new ArrayList<Map.Entry<String, Double>>(balances.entrySet());
Collections.sort(sortedEntries, new Comparator<Map.Entry<String, Double>>()
{
@Override
public int compare(final Entry<String, Double> entry1, final Entry<String, Double> entry2)
{
return -entry1.getValue().compareTo(entry2.getValue());
}
});
int pos = 1;
for (Map.Entry<String, Double> entry : sortedEntries)
{
cache.getLines().add(pos + ". " + entry.getKey() + ", " + Util.formatCurrency(entry.getValue(), ess));
pos++;
}
cacheage = System.currentTimeMillis();
}
}
finally
{
lock.writeLock().unlock();
}
ess.scheduleAsyncDelayedTask(viewer);
}
}
private class Viewer implements Runnable
{
private final transient CommandSender sender;
private final transient int page;
private final transient boolean force;
public Viewer(final CommandSender sender, final int page, final boolean force)
{
this.sender = sender;
this.page = page;
this.force = force;
}
@Override
public void run()
{
lock.readLock().lock();
try
{
if (!force && cacheage > System.currentTimeMillis() - CACHETIME)
{
outputCache(sender, page);
return;
}
}
finally
{
lock.readLock().unlock();
}
ess.scheduleAsyncDelayedTask(new Calculator(new Viewer(sender, page, force), force));
}
}
}

View File

@@ -1,66 +1,45 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Console;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.perm.Permissions;
import com.earth2me.essentials.user.Ban;
import lombok.Cleanup;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.craftbukkit.CraftServer;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandban extends EssentialsCommand
{
public Commandban()
{
super("ban");
}
@Override
public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
@Cleanup
final IUser user = getPlayer(args, 0, true);
if (user.isOnline())
User p = null;
if (server.matchPlayer(args[0]).isEmpty())
{
if (Permissions.BAN_EXEMPT.isAuthorized(user))
{
sender.sendMessage(_("banExempt"));
return;
}
((CraftServer)server).getHandle().a(args[0]);
sender.sendMessage(Util.format("playerBanned",args[0]));
}
else
{
if (Permissions.BAN_OFFLINE.isAuthorized(sender))
{
sender.sendMessage(_("banExempt"));
return;
}
}
user.acquireWriteLock();
String banReason;
user.getData().setBan(new Ban());
if (args.length > 1)
{
banReason = getFinalArg(args, 1);
user.getData().getBan().setReason(banReason);
}
else
{
banReason = _("defaultBanReason");
}
user.setBanned(true);
user.kickPlayer(banReason);
final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
for (Player onlinePlayer : server.getOnlinePlayers())
{
final IUser player = ess.getUser(onlinePlayer);
if (Permissions.BAN_NOTIFY.isAuthorized(player))
{
onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason));
p = ess.getUser(server.matchPlayer(args[0]).get(0));
String banReason = Util.i18n("defaultBanReason");
if(args.length > 1) {
banReason = getFinalArg(args, 1);
p.setBanReason(commandLabel);
}
p.kickPlayer(banReason);
((CraftServer)server).getHandle().a(p.getName());
sender.sendMessage(Util.format("playerBanned", p.getName()));
}
ess.loadBanList();
}
}

View File

@@ -1,39 +1,29 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IUser;
import lombok.Cleanup;
import com.earth2me.essentials.Util;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.CraftServer;
public class Commandbanip extends EssentialsCommand
{
public Commandbanip()
{
super("banip");
}
@Override
public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
@Cleanup
final IUser player = ess.getUser(args[0]);
player.acquireReadLock();
((CraftServer)server).getHandle().c(args[0]);
sender.sendMessage(Util.i18n("banIpAddress"));
ess.loadBanList();
if (player == null)
{
ess.getServer().banIP(args[0]);
sender.sendMessage(_("banIpAddress"));
}
else
{
final String ipAddress = player.getData().getIpAddress();
if (ipAddress.length() == 0)
{
throw new Exception(_("playerNotFound"));
}
ess.getServer().banIP(player.getData().getIpAddress());
sender.sendMessage(_("banIpAddress"));
}
}
}

View File

@@ -1,18 +1,23 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Util;
import com.earth2me.essentials.api.IUser;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.TreeType;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.Location;
public class Commandbigtree extends EssentialsCommand
{
@Override
public void run(final IUser user, final String commandLabel, final String[] args) throws Exception
public Commandbigtree()
{
TreeType tree;
super("bigtree");
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
TreeType tree = TreeType.TREE;
if (args.length > 0 && args[0].equalsIgnoreCase("redwood"))
{
tree = TreeType.TALL_REDWOOD;
@@ -26,16 +31,39 @@ public class Commandbigtree extends EssentialsCommand
throw new NotEnoughArgumentsException();
}
final Location loc = Util.getTarget(user);
final Location safeLocation = Util.getSafeDestination(loc);
final boolean success = user.getWorld().generateTree(safeLocation, tree);
double x = user.getLocation().getX();
double y = user.getLocation().getY();
double z = user.getLocation().getZ();
// offset tree in direction player is facing
int r = (int)user.getCorrectedYaw();
if (r < 68 || r > 292) // north
{
x -= 3.0D;
}
else if (r > 112 && r < 248) // south
{
x += 3.0D;
}
if (r > 22 && r < 158) // east
{
z -= 3.0D;
}
else if (r > 202 && r < 338) // west
{
z += 3.0D;
}
Location safeLocation = Util.getSafeDestination(new Location(user.getWorld(), x, y, z));
boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree);
if (success)
{
user.sendMessage(_("bigTreeSuccess"));
charge(user);
user.sendMessage(Util.i18n("bigTreeSuccess"));
}
else
{
throw new Exception(_("bigTreeFailure"));
user.sendMessage(Util.i18n("bigTreeFailure"));
}
}
}

View File

@@ -1,40 +0,0 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.perm.Permissions;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.block.BlockBreakEvent;
public class Commandbreak extends EssentialsCommand
{
//TODO: Switch to use util class
@Override
public void run(final IUser user, final String commandLabel, final String[] args) throws Exception
{
final Block block = user.getTargetBlock(null, 20);
if (block == null)
{
throw new NoChargeException();
}
if (block.getType() == Material.AIR)
{
throw new NoChargeException();
}
if (block.getType() == Material.BEDROCK && !Permissions.BREAK_BEDROCK.isAuthorized(user))
{
throw new Exception("You are not allowed to destroy bedrock."); //TODO: Translation
}
final BlockBreakEvent event = new BlockBreakEvent(block, user.getBase());
server.getPluginManager().callEvent(event);
if (event.isCancelled())
{
throw new NoChargeException();
}
else
{
block.setType(Material.AIR);
}
}
}

View File

@@ -1,19 +1,29 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Console;
import com.earth2me.essentials.Util;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandbroadcast extends EssentialsCommand
{
public Commandbroadcast()
{
super("broadcast");
}
@Override
public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
ess.broadcastMessage(null, _("broadcast", getFinalArg(args, 0)));
charge(sender);
ess.broadcastMessage(sender instanceof Player ? ((Player)sender).getName() : Console.NAME,
Util.format("broadcast", getFinalArg(args, 0)));
}
}

View File

@@ -1,24 +1,31 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.Util;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandburn extends EssentialsCommand
{
public Commandburn()
{
super("burn");
}
@Override
protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
charge(sender);
for (Player p : server.matchPlayer(args[0]))
{
p.setFireTicks(Integer.parseInt(args[1]) * 20);
sender.sendMessage(_("burnMsg", p.getDisplayName(), Integer.parseInt(args[1])));
sender.sendMessage(Util.format("burnMsg", p.getDisplayName(), Integer.parseInt(args[1])));
}
}
}

View File

@@ -1,60 +1,67 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IUser;
import com.earth2me.essentials.perm.Permissions;
import java.util.List;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.util.List;
import org.bukkit.ChatColor;
public class Commandclearinventory extends EssentialsCommand
{
//TODO: Cleanup
@Override
public void run(final IUser user, final String commandLabel, final String[] args) throws Exception
public Commandclearinventory()
{
if (args.length > 0 && Permissions.CLEARINVENTORY_OTHERS.isAuthorized(user))
super("clearinventory");
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
if (args.length > 0 && user.isAuthorized("essentials.clearinventory.others"))
{
//TODO: Fix fringe user match case.
if (args[0].length() >= 3)
{
List<Player> online = server.matchPlayer(args[0]);
if (!online.isEmpty())
{
charge(user);
for (Player p : online)
{
p.getInventory().clear();
user.sendMessage(_("inventoryClearedOthers", p.getDisplayName()));
user.sendMessage(Util.format("inventoryClearedOthers", p.getDisplayName()));
}
return;
}
throw new Exception(_("playerNotFound"));
throw new Exception(Util.i18n("playerNotFound"));
}
else
{
Player p = server.getPlayer(args[0]);
if (p != null)
{
charge(user);
p.getInventory().clear();
user.sendMessage(_("inventoryClearedOthers", p.getDisplayName()));
user.sendMessage(Util.format("inventoryClearedOthers", p.getDisplayName()));
}
else
{
throw new Exception(_("playerNotFound"));
throw new Exception(Util.i18n("playerNotFound"));
}
}
}
else
{
charge(user);
user.getInventory().clear();
user.sendMessage(_("inventoryCleared"));
user.sendMessage(Util.i18n("inventoryCleared"));
}
}
@Override
protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 1)
{
@@ -70,11 +77,11 @@ public class Commandclearinventory extends EssentialsCommand
for (Player p : online)
{
p.getInventory().clear();
sender.sendMessage(_("inventoryClearedOthers", p.getDisplayName()));
sender.sendMessage(Util.format("inventoryClearedOthers", p.getDisplayName()));
}
return;
}
throw new Exception(_("playerNotFound"));
throw new Exception(Util.i18n("playerNotFound"));
}
else
{
@@ -82,11 +89,11 @@ public class Commandclearinventory extends EssentialsCommand
if (u != null)
{
u.getInventory().clear();
sender.sendMessage(_("inventoryClearedOthers", u.getDisplayName()));
sender.sendMessage(Util.format("inventoryClearedOthers", u.getDisplayName()));
}
else
{
throw new Exception(_("playerNotFound"));
throw new Exception(Util.i18n("playerNotFound"));
}
}
}

View File

@@ -1,52 +1,32 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.IUser;
import org.bukkit.Server;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
public class Commandcompass extends EssentialsCommand
{
@Override
public void run(final IUser user, final String commandLabel, final String[] args) throws Exception
public Commandcompass()
{
final int bearing = (int)(user.getLocation().getYaw() + 180 + 360) % 360;
super("compass");
}
@Override
public void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
charge(user);
int r = (int)user.getCorrectedYaw();
String dir;
if (bearing < 23)
{
dir = "N";
}
else if (bearing < 68)
{
dir = "NE";
}
else if (bearing < 113)
{
dir = "E";
}
else if (bearing < 158)
{
dir = "SE";
}
else if (bearing < 203)
{
dir = "S";
}
else if (bearing < 248)
{
dir = "SW";
}
else if (bearing < 293)
{
dir = "W";
}
else if (bearing < 338)
{
dir = "NW";
}
else
{
dir = "N";
}
user.sendMessage(_("compassBearing", dir, bearing));
if (r < 23) dir = "N";
else if (r < 68) dir = "NE";
else if (r < 113) dir = "E";
else if (r < 158) dir = "SE";
else if (r < 203) dir = "S";
else if (r < 248) dir = "SW";
else if (r < 293) dir = "W";
else if (r < 338) dir = "NW";
else dir = "N";
user.sendMessage(Util.format("compassBearing", dir, r));
}
}

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