diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..edf9e5c --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Eclipse stuff +/.classpath +/.project +/.settings + +# netbeans +/nbproject + +# we use maven! +/build.xml + +# maven +/target + +# vim +.*.sw[a-p] + +# various other potential build files +/build +/bin +/dist +/manifest.mf + +# Mac filesystem dust +.DS_Store + +# intellij +*.iml +*.ipr +*.iws +.idea/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..3031b97 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,497 @@ +# How to Contribute + +The Bukkit project prides itself on being community built and driven. We love it when members of our community want to jump right in and get involved, so here's what you need to know. + +## Quick Guide +1. Create or find an issue to address on our [JIRA issue tracker](http://leaky.bukkit.org). +- Does your proposed change [fit Bukkit's goals](#does-the-change-fit-bukkits-goals)? +- Fork the repository if you haven't done so already. +- Make your changes in a new branch (if your change affects both Bukkit and CraftBukkit, we highly suggest you use the same name for your branches in both repos). +- Test your changes. +- Push to your fork and submit a pull request. +- **Note:** The project is put under a code freeze leading up to the release of a Minecraft update in order to give the Bukkit team a static code base to work on. + +![Life Cycle of a Bukkit Improvement](http://i.imgur.com/Ed6T7AE.png) + +## Getting Started +- You'll need a free [JIRA account](http://leaky.bukkit.org) (on our issue tracker affectionately called Leaky). +- You'll need a free [GitHub account](https://github.com/signup/free). +- Make sure you have a JIRA ticket for your issue at hand. + * Either search the list of current issues and find an appropriate issue. + * Or create one yourself if one does not already exist. + * When creating an issue, make sure to clearly describe the issue (including steps to reproduce it if it is a bug). +- Fork the repository on GitHub. +- **Note:** The project is put under a code freeze leading up to the release of a Minecraft update in order to give the Bukkit team a static code base to work on. + +## Does the Change Fit Bukkit's Goals? +As a rough guideline, ask yourself the following questions to determine if your proposed change fits the Bukkit project's goals. Please remember that this is only a rough guideline and may or may not reflect the definitive answer to this question. + +* Does it expose an implementation detail of the server software, the protocol or file formats? + + If your change revolves around an implementation detail then it is not proper API design. Examples of bad API design would be along the lines of a packet API, an NBT storage API, or basing an enum on implementation values. + +* Does it result in unexpected behaviour as defined by the Vanilla specification? + + One of the goals of the Bukkit project is to be an extended Minecraft vanilla server - meaning: if you choose to run the Bukkit server without any plugins, it should function exactly as the Minecraft server would with some rare exceptions. If your change alters the behaviour of the server in such a way that you would not have the same experience as you would in Vanilla, your change does not fit the Bukkit project's goals. + +* Does it expose an issue or vulnerability when operating within the Vanilla environment? + + One of the goals of the Bukkit project is to be able to operate within the limitations of the Vanilla environment. If your change results in or exposes the ability to, for example, crash the client when invalid data is set, it does not fit the Bukkit project's needs. + +If you answered yes to any of these questions, chances are high your change does not fit the Bukkit project's goals and will most likely not be accepted. Regardless, there are a few other important questions you need to ask yourself before you start working on a change: + +* Is this change reasonably supportable and maintainable? + +* Is this change future proof? + +## Making the Changes +* Create a branch on your fork where you'll be making your changes. + * Name your branch something relevant to the change you are looking to make. + * Note: if your changes affect both Bukkit and CraftBukkit, it is highly suggested you use the same branch name on both repos. + * To create a branch in Git; + * `git branch relevantBranchName` + * Then checkout the new branch with `git checkout relevantBranchName` +* Check for unnecessary whitespace with `git diff --check` before committing. +* Make sure your code meets [our requirements](#code-requirements). +* If the work you want to do involves editing Minecraft classes, be sure to read over the [Using Minecraft Internals](#using-minecraft-internals) section. +* Make sure your commit messages are in the [proper format](#commit-message-example). +* Test your changes to make sure it actually addresses the issue it should. +* Make sure your code compiles under Java 6, as that is what the project has to be built with. + +### Code Requirements +* We generally follow the [Sun/Oracle coding standards](http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html). + +* No tabs; use 4 spaces instead. + +* No trailing whitespaces. + +* No CRLF line endings, LF only, set your Gits 'core.autocrlf' to 'true'. + + These whitespace requirements are easily and often overlooked. They are critical formatting requirements designed to help simplify a shared heterogeneous development environment. Learn how your IDE functions in order to show you these characters and verify them. Analyse the git diff closely to verify every character and if the PR should include the character change. It is tedious and it is critical. + + Eclipse: http://stackoverflow.com/a/11596227/532590 + NetBeans: http://stackoverflow.com/a/1866385/532590 + +* No 80 column limit or 'weird' midstatement newlines. + +* Any major additions should have documentation ready and provided if applicable (this is usually the case). + +* Try to follow test driven development where applicable. + + Bukkit employs JUnit (http://www.vogella.com/articles/JUnit/article.html) for testing and PRs should attempt to integrate with that framework as appropriate. Bukkit is a large project and what seems simple to a PR author at the time of writing a PR may easily be overlooked later by other authors and updates. Including unit tests with your PR will help to ensure the PR can be easily maintained over time and encourage the Bukkit Team to pull the PR. + +* There needs to be a new line at the end of every file. + +* Imports should be organised by alphabetical order, separated and grouped by package. + + **For example:** + + ```java + import java.io.ByteArrayInputStream; + import java.io.DataInputStream; + import java.io.IOException; + import java.util.ArrayList; + import java.util.Iterator; + import java.util.Random; + import java.util.concurrent.Callable; + + // CraftBukkit start + import java.io.UnsupportedEncodingException; + import java.util.concurrent.ExecutionException; + import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + import java.util.logging.Level; + import java.util.HashSet; + + import org.bukkit.Bukkit; + import org.bukkit.Location; + import org.bukkit.craftbukkit.CraftWorld; + import org.bukkit.craftbukkit.inventory.CraftInventoryView; + import org.bukkit.craftbukkit.inventory.CraftItemStack; + import org.bukkit.craftbukkit.util.LazyPlayerSet; + import org.bukkit.craftbukkit.util.Waitable; + import org.bukkit.craftbukkit.entity.CraftPlayer; + import org.bukkit.craftbukkit.event.CraftEventFactory; + import org.bukkit.entity.Player; + import org.bukkit.event.Event; + import org.bukkit.event.block.Action; + import org.bukkit.event.block.SignChangeEvent; + import org.bukkit.event.player.AsyncPlayerChatEvent; + import org.bukkit.event.player.PlayerAnimationEvent; + import org.bukkit.event.player.PlayerChatEvent; + import org.bukkit.event.player.PlayerCommandPreprocessEvent; + import org.bukkit.event.player.PlayerInteractEntityEvent; + import org.bukkit.event.player.PlayerItemHeldEvent; + import org.bukkit.event.player.PlayerKickEvent; + import org.bukkit.event.player.PlayerMoveEvent; + import org.bukkit.event.player.PlayerTeleportEvent; + import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + import org.bukkit.event.player.PlayerToggleSneakEvent; + import org.bukkit.event.player.PlayerToggleSprintEvent; + import org.bukkit.event.inventory.*; + import org.bukkit.event.inventory.InventoryType.SlotType; + import org.bukkit.event.player.PlayerPortalEvent; + import org.bukkit.event.player.PlayerToggleFlightEvent; + import org.bukkit.inventory.CraftingInventory; + import org.bukkit.inventory.InventoryView; + // CraftBukkit end + ``` + +### Using Minecraft Internals +#### Importing a New Minecraft Class +When contributing to the Bukkit project, you will likely find that you need to edit a Minecraft class that isn't already found within the project. In this case, you need to look at [our mc-dev repository](https://github.com/Bukkit/mc-dev), find the class you need, add it to the CraftBukkit repo and include it in its own special commit separate from your other changes. The commit message of this special commit should simply be "Add x for diff visibility", where x is the name of the file you are adding from mc-dev. + +If, however, you need to import multiple files from mc-dev into the Bukkit project, they should all be contained in the same special commit with the commit message "Add files for diff visibility". Note how the commit message no longer specifically mentions any class names. + +#### Making Changes to Minecraft Classes +The Bukkit project employs a Minimal Diff policy to help guide when changes should be made to Minecraft classes and what those changes should be. This is to ensure that any changes made have the smallest impact possible on the update process we go through whenever a Minecraft update is released. As well as keeping the Minimal Diff policy in mind, every change made to a Minecraft class needs to be marked as such with the appropriate CraftBukkit comment. + +##### Minimal Diff Policy +The Minimal Diff policy is a really important part of the project as it reminds us that every change to the Minecraft Internals has an impact on our update process. When people think of the phrase "minimal diffs", they often take it to the extreme - they go completely out of their way to abstract the changes they are trying to make away from editing Minecraft's classes as much as possible. However, this isn't what we mean by "minimal diffs". Instead, when trying to understand the minimal diffs policy, it helps to keep in mind its end goal: to reduce the impact changes we make to Minecraft's internals have on our update process. + +Put simply, the Minimal Diffs Policy simply means to make the smallest change in a Minecraft class possible without duplicating logic. + +Here are a few tips you should keep in mind or common areas you should focus on: + +* Try to avoid duplicating logic or code when making changes. + +* Try to keep your changes easily discernible - don't nest or group several unrelated changes together. + +* If you only use an import once within a class, don't import it and use fully qualified names instead. + +* Try to employ "short circuiting" of logic if at all possible. This means that you should force a conditional to be the value needed to side-step the code block if you would like to ignore that block of code. + + **For example, to short circuit this:** + + ```java + if (!this.world.isStatic && !this.dead && d0 * d0 + d1 * d1 + d2 * d2 > 0.0D) { + this.die(); + this.h(); + } + ``` + **You would do this:** + + ```java + if (false && !this.world.isStatic && !this.dead && d0 * d0 + d1 * d1 + d2 * d2 > 0.0D) { // CraftBukkit - not needed + this.die(); + this.h(); + } + ``` + +* When adding a validation check, see if the Validate package we already use has a better, more concise method you can use instead. + + **For example, you should use:** + + ```java + Validate.notNull(sender, "Sender cannot be null"); + ``` + + **Instead of:** + + ```java + if (sender == null) { + throw new IllegalArgumentException("Sender cannot be null"); + } + ``` + +* When the change you are attempting to make involves removing code, instead of removing it outright, you should comment it out. + + **For example:** + + ```java + // CraftBukkit start - special case dropping so we can get info from the tile entity + public void dropNaturally(World world, int i, int j, int k, int l, float f, int i1) { + if (world.random.nextFloat() < f) { + ItemStack itemstack = new ItemStack(Item.SKULL.id, 1, this.getDropData(world, i, j, k)); + TileEntitySkull tileentityskull = (TileEntitySkull) world.getTileEntity(i, j, k); + + if (tileentityskull.getSkullType() == 3 && tileentityskull.getExtraType() != null && tileentityskull.getExtraType().length() > 0) { + itemstack.setTag(new NBTTagCompound()); + itemstack.getTag().setString("SkullOwner", tileentityskull.getExtraType()); + } + + this.b(world, i, j, k, itemstack); + } + } + // CraftBukkit end + + public void a(World world, int i, int j, int k, int l, EntityHuman entityhuman) { + if (entityhuman.abilities.canInstantlyBuild) { + l |= 8; + world.setData(i, j, k, l, 4); + } + + super.a(world, i, j, k, l, entityhuman); + } + + public void remove(World world, int i, int j, int k, int l, int i1) { + if (!world.isStatic) { + /* CraftBukkit start - drop item in code above, not here + if ((i1 & 8) == 0) { + ItemStack itemstack = new ItemStack(Item.SKULL.id, 1, this.getDropData(world, i, j, k)); + TileEntitySkull tileentityskull = (TileEntitySkull) world.getTileEntity(i, j, k); + + if (tileentityskull.getSkullType() == 3 && tileentityskull.getExtraType() != null && tileentityskull.getExtraType().length() > 0) { + itemstack.setTag(new NBTTagCompound()); + itemstack.getTag().setString("SkullOwner", tileentityskull.getExtraType()); + } + + this.b(world, i, j, k, itemstack); + } + // CraftBukkit end */ + + super.remove(world, i, j, k, l, i1); + } + } + ``` + +##### General Guidelines +When editing Minecraft's classes, we have a set of rules and guidelines that need to be followed to keep us sane when it comes time for us to update Bukkit. + +**CraftBukkit comments** +Changes to a Minecraft class should be clearly marked using CraftBukkit comments. Here are a few tips to help explain what kind of CraftBukkit comment to use and where to use them: + +* Regardless of what kind of CraftBukkit comment you use, please take care to be explicit and exact with your usage. If the "C" in "CraftBukkit" is capitalised in the example, you should capitalise it when you use it. If the "start" begins with a lowercase "s", you should make sure yours does too. + +* If the change only affects one line of code, you should use an end of line CraftBukkit comment. + + **Examples:** + + If the change is obvious when looking at the diff, then you just need a simple end of line CraftBukkit comment. + + ```java + if (true || minecraftserver.getAllowNether()) { // CraftBukkit + ``` + + If, however, the change is something important to note or difficult to discern, you should include a reason at the end of the end of line CraftBukkit comment. + + ```java + public int fireTicks; // CraftBukkit - private -> public + ``` + + If adding the CraftBukkit comment to the end of the line negatively affects the readability of the code, then you should place the CraftBukkit comment on a new line above the change you made. + + ```java + // CraftBukkit + if (!isEffect && !world.isStatic && world.difficulty >= 2 && world.areChunksLoaded(MathHelper.floor(d0), MathHelper.floor(d1), MathHelper.floor(d2), 10)) { + ``` + +* If the change affects more than one line, you should use a multi-line CraftBukkit comment. + + **Examples:** + + The majority of the time multi-line changes should be accompanied by a reason since they're usually much more complicated than a single line change. We'd like to suggest you follow the same rule as above: if the change is something important to note or difficult to discern, you should include a reason at the end of the end of line CraftBukkit comment, however it is not always clear if this is the case. Looking through the code in the project, you'll see that we sometimes include a reason when we should have left it off and vice versa. + + ```java + // CraftBukkit start - special case dropping so we can get info from the tile entity + public void dropNaturally(World world, int i, int j, int k, int l, float f, int i1) { + if (world.random.nextFloat() < f) { + ItemStack itemstack = new ItemStack(Item.SKULL.id, 1, this.getDropData(world, i, j, k)); + TileEntitySkull tileentityskull = (TileEntitySkull) world.getTileEntity(i, j, k); + + if (tileentityskull.getSkullType() == 3 && tileentityskull.getExtraType() != null && tileentityskull.getExtraType().length() > 0) { + itemstack.setTag(new NBTTagCompound()); + itemstack.getTag().setString("SkullOwner", tileentityskull.getExtraType()); + } + + this.b(world, i, j, k, itemstack); + } + } + // CraftBukkit end + ```` + + Otherwise, just use a multi-line CraftBukkit comment without a reason. + + ```java + // CraftBukkit start + BlockIgniteEvent event = new BlockIgniteEvent(this.cworld.getBlockAt(i, j, k), BlockIgniteEvent.IgniteCause.LIGHTNING, null); + world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + world.setTypeIdUpdate(i, j, k, Block.FIRE.id); + } + // CraftBukkit end + ``` + +* CraftBukkit comments should be on the same indentation level of the code block it is in. + + **For example:** + + ```java + if (j == 1) { + // CraftBukkit start - store a reference + ItemStack itemstack4 = playerinventory.getCarried(); + if (itemstack4.count > 0) { + entityhuman.drop(itemstack4.a(1)); + } + + if (itemstack4.count == 0) { + // CraftBukkit end + playerinventory.setCarried((ItemStack) null); + } + } + ``` + +**Other guidelines** + +* When adding imports to a Minecraft class, they should be organised by alphabetical order, separated and grouped by package. + + **For example:** + + ```java + import java.io.ByteArrayInputStream; + import java.io.DataInputStream; + import java.io.IOException; + import java.util.ArrayList; + import java.util.Iterator; + import java.util.Random; + import java.util.concurrent.Callable; + + // CraftBukkit start + import java.io.UnsupportedEncodingException; + import java.util.concurrent.ExecutionException; + import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + import java.util.logging.Level; + import java.util.HashSet; + + import org.bukkit.Bukkit; + import org.bukkit.Location; + import org.bukkit.craftbukkit.CraftWorld; + import org.bukkit.craftbukkit.inventory.CraftInventoryView; + import org.bukkit.craftbukkit.inventory.CraftItemStack; + import org.bukkit.craftbukkit.util.LazyPlayerSet; + import org.bukkit.craftbukkit.util.Waitable; + import org.bukkit.craftbukkit.entity.CraftPlayer; + import org.bukkit.craftbukkit.event.CraftEventFactory; + import org.bukkit.entity.Player; + import org.bukkit.event.Event; + import org.bukkit.event.block.Action; + import org.bukkit.event.block.SignChangeEvent; + import org.bukkit.event.player.AsyncPlayerChatEvent; + import org.bukkit.event.player.PlayerAnimationEvent; + import org.bukkit.event.player.PlayerChatEvent; + import org.bukkit.event.player.PlayerCommandPreprocessEvent; + import org.bukkit.event.player.PlayerInteractEntityEvent; + import org.bukkit.event.player.PlayerItemHeldEvent; + import org.bukkit.event.player.PlayerKickEvent; + import org.bukkit.event.player.PlayerMoveEvent; + import org.bukkit.event.player.PlayerTeleportEvent; + import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + import org.bukkit.event.player.PlayerToggleSneakEvent; + import org.bukkit.event.player.PlayerToggleSprintEvent; + import org.bukkit.event.inventory.*; + import org.bukkit.event.inventory.InventoryType.SlotType; + import org.bukkit.event.player.PlayerPortalEvent; + import org.bukkit.event.player.PlayerToggleFlightEvent; + import org.bukkit.inventory.CraftingInventory; + import org.bukkit.inventory.InventoryView; + // CraftBukkit end + ``` + +* Do not remove unused imports if they are not marked by CraftBukkit comments. + +### Commit Message Example +> Provide an example commit for CONTRIBUTING.md. Fixes BUKKIT-1 +> +> The CONTRIBUTING.md is missing an example commit message. Without this +> commit, we are unable to provide potential contributors with a helpful example, +> forcing developers to guess at what an acceptable commit message would look +> like. This commit fixes this issue by providing a clear and informative example +> for contributors to base their work off of. + +### Commit Message Expectations +The first line in a commit message is an imperative statement briefly explaining what the commit is achieving with an associated ticket number from our JIRA, in the form of BUKKIT-#. See the list of acceptable keywords to reference tickets with for more information on this. + +The body of the commit message needs to describe how the code behaves without this change, why this is a problem and how this commit addresses it. The body of the commit message should be restricted by a 78 character, plus newline, limit per line (meaning: once you hit about 78 characters, you should explicitly start a new line in the commit message). + +Acceptable keywords to reference tickets with: + +* **Fixes** BUKKIT-1 - this commit fixes the bug detailed in BUKKIT-1 +* **Adds** BUKKIT-2 - this commit adds the new feature requested by BUKKIT-2 + +You can reference multiple tickets in a single commit message, for example: "Fixes BUKKIT-1, BUKKIT-2" or "Adds BUKKIT-1, BUKKIT-2" without closing punctuation. + +## Submitting the Changes + +* Push your changes to a topic branch in your fork of the repository. +* Submit a pull request to the relevant repository in the Bukkit organization. + * Make sure your pull request meets [our expectations](#pull-request-formatting-expectations) before submitting. + * No merges should be included in any pull requests. +* Update your JIRA ticket to reflect that you have submitted a pull request and are ready for it to be reviewed. + * Include a link to the pull request in the ticket. +* Follow our [Tips to Get Your Pull Request Accepted](#tips-to-get-your-pull-request-accepted). +* **Note:** The project is put under a code freeze leading up to the release of a Minecraft update in order to give the Bukkit team a static code base to work on. + +### Pull Request Formatting Expectations +#### Title +> [PR Type] Brief summary. Fixes BUKKIT-#### +> PR Type can be B for Bukkit, C for CraftBukkit, B+C for a PR in both sides +> +> Title Example: +> [B+C] Provide an example commit for CONTRIBUTING.md. Fixes BUKKIT-1 + +#### Description: +> ##### The Issue: +> Paragraphs explaining what the issue the PR is meant to be addressing. +> +> ##### Justification for this PR: +> Paragraphs providing justification for the PR +> +> ##### PR Breakdown: +> Paragraphs breaking down what the PR is doing, in detail. +> +> ##### Testing Results and Materials: +> Paragraphs describing what you did to test the code in this PR and links to pre-compiled test binaries and source. +> +> ##### Relevant PR(s): +> This should be links to accompanying PRs, or alternate PRs that attempted to perform the task. Each reference should have a reason attached as to why it is being referenced (for example: "Similar to PR ### but won't empty your Bukkits"). Accompanying PRs need no explanation, but still need to be linked. +> +> B-#### - https://github.com/Bukkit/Bukkit/pull/#### - Reason +> CB-#### - https://github.com/Bukkit/CraftBukkit/pull/#### - Reason +> +> ##### JIRA Ticket: +> BUKKIT-#### - https://bukkit.atlassian.net/browse/BUKKIT-#### +> +> ##### Pull Request Check List (For Your Use): +> +>**General:** +> +>- [ ] Fits Bukkit's Goals +>- [ ] Leaky Ticket Ready +>- [ ] Code Meets Requirements +>- [ ] Code is Documented +>- [ ] Code Addresses Leaky Ticket +>- [ ] Followed Pull Request Format +>- [ ] Tested Code +>- [ ] Included Test Material and Source +> +>**If Applicable:** +> +>- [ ] Importing New Minecraft Classes In Special Commit +>- [ ] Follows Minimal Diff Policy +>- [ ] Uses Proper CraftBukkit Comments +>- [ ] Imports Are Ordered, Separated and Organised Properly + +### Tips to Get Your Pull Request Accepted +Making sure you follow the above conventions is important, but just the beginning. Follow these tips to better the chances of your pull request being accepted and pulled. + +* Your change should [fit with Bukkit's goals](#does-the-change-fit-bukkits-goals). +* Make sure you follow all of our conventions to the letter. +* Make sure your code compiles under Java 6. +* Check for misplaced whitespaces. It may be invisible, but [we notice](https://github.com/Bukkit/CraftBukkit/pull/1070). +* Provide proper JavaDocs where appropriate. + * JavaDocs should detail every limitation, caveat and gotcha the code has. +* Provide proper accompanying documentation where appropriate. +* Test your code and provide testing material. + * For example: adding an event? Test it with a test plugin and provide us with that plugin and its source. +* Make sure to follow coding best practises. +* Your pull request should adhere to our [Pull Request Formatting Expectations](#pull-request-formatting-expectations). +* **Note:** The project is put under a code freeze leading up to the release of a Minecraft update in order to give the Bukkit team a static code base to work on. + +## Useful Resources +* [An example pull request demonstrating the things we look out for](https://github.com/Bukkit/CraftBukkit/pull/1070) +* [Handy gist version of our Pull Request Format Template](https://gist.github.com/EvilSeph/35bb477eaa1dffc5f1d7) +* [More information on contributing](http://wiki.bukkit.org/Getting_Involved) +* [Leaky, Our Issue Tracker (JIRA)](http://leaky.bukkit.org) +* [General GitHub documentation](http://help.github.com/) +* [GitHub pull request documentation](http://help.github.com/send-pull-requests/) +* [Join us on IRC - #bukkitdev @ irc.esper.net](http://wiki.bukkit.org/IRC) diff --git a/LICENCE.txt b/LICENCE.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENCE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a51766e --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +Bukkit +====== + +A Minecraft Server API. + +Website: [http://bukkit.org](http://bukkit.org) +Bugs/Suggestions: [http://leaky.bukkit.org](http://leaky.bukkit.org) +Contributing Guidelines: [CONTRIBUTING.md](https://github.com/Bukkit/Bukkit/blob/master/CONTRIBUTING.md) + +Compilation +----------- + +We use maven to handle our dependencies. + +* Install [Maven 3](http://maven.apache.org/download.html) +* Check out this repo and: `mvn clean install` diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..dcf7ed3 --- /dev/null +++ b/pom.xml @@ -0,0 +1,145 @@ + + 4.0.0 + org.bukkit + bukkit + 1.7.9-R0.3-SNAPSHOT + Bukkit + http://www.bukkit.org + + + UTF-8 + + + + scm:git:git@github.com:Bukkit/Bukkit.git + scm:git:git://github.com/Bukkit/Bukkit.git + https://github.com/Bukkit/Bukkit/tree/master/ + + + + jenkins + http://ci.bukkit.org + + + + + jd.bukkit.org + file:///home/javadocs/public_html/ + + + repobo-rel + repo.bukkit.org Releases + http://repo.bukkit.org/content/repositories/releases/ + + + repobo-snap + repo.bukkit.org Snapshots + http://repo.bukkit.org/content/repositories/snapshots/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-shade-plugin + 1.4 + + + package + + shade + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.0-beta-3 + + + + org.codehaus.mojo + jxr-maven-plugin + 2.0-beta-1 + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + true + + + + + javadoc + + + + + + + + + + + + org.yaml + snakeyaml + 1.9 + jar + compile + + + com.googlecode.json-simple + json-simple + 1.1 + jar + compile + + + org.avaje + ebean + 2.7.3 + jar + compile + + + com.google.guava + guava + 10.0.1 + jar + compile + + + commons-lang + commons-lang + 2.3 + + + + + junit + junit + 4.11 + test + + + org.hamcrest + hamcrest-library + 1.3 + test + + + diff --git a/src/main/java/org/bukkit/Achievement.java b/src/main/java/org/bukkit/Achievement.java new file mode 100644 index 0000000..928b6d5 --- /dev/null +++ b/src/main/java/org/bukkit/Achievement.java @@ -0,0 +1,69 @@ +package org.bukkit; + +/** + * Represents an achievement, which may be given to players. + */ +public enum Achievement { + OPEN_INVENTORY, + MINE_WOOD (OPEN_INVENTORY), + BUILD_WORKBENCH (MINE_WOOD), + BUILD_PICKAXE (BUILD_WORKBENCH), + BUILD_FURNACE (BUILD_PICKAXE), + ACQUIRE_IRON (BUILD_FURNACE), + BUILD_HOE (BUILD_WORKBENCH), + MAKE_BREAD (BUILD_HOE), + BAKE_CAKE (BUILD_HOE), + BUILD_BETTER_PICKAXE (BUILD_PICKAXE), + COOK_FISH (BUILD_FURNACE), + ON_A_RAIL (ACQUIRE_IRON), + BUILD_SWORD (BUILD_WORKBENCH), + KILL_ENEMY (BUILD_SWORD), + KILL_COW (BUILD_SWORD), + FLY_PIG (KILL_COW), + SNIPE_SKELETON (KILL_ENEMY), + GET_DIAMONDS (ACQUIRE_IRON), + NETHER_PORTAL (GET_DIAMONDS), + GHAST_RETURN (NETHER_PORTAL), + GET_BLAZE_ROD (NETHER_PORTAL), + BREW_POTION (GET_BLAZE_ROD), + END_PORTAL (GET_BLAZE_ROD), + THE_END (END_PORTAL), + ENCHANTMENTS (GET_DIAMONDS), + OVERKILL (ENCHANTMENTS), + BOOKCASE (ENCHANTMENTS), + EXPLORE_ALL_BIOMES (END_PORTAL), + SPAWN_WITHER (THE_END), + KILL_WITHER (SPAWN_WITHER), + FULL_BEACON (KILL_WITHER), + BREED_COW (KILL_COW), + DIAMONDS_TO_YOU (GET_DIAMONDS), + ; + + private final Achievement parent; + + private Achievement() { + parent = null; + } + + private Achievement(Achievement parent) { + this.parent = parent; + } + + /** + * Returns whether or not this achievement has a parent achievement. + * + * @return whether the achievement has a parent achievement + */ + public boolean hasParent() { + return parent != null; + } + + /** + * Returns the parent achievement of this achievement, or null if none. + * + * @return the parent achievement or null + */ + public Achievement getParent() { + return parent; + } +} diff --git a/src/main/java/org/bukkit/Art.java b/src/main/java/org/bukkit/Art.java new file mode 100644 index 0000000..ba66f16 --- /dev/null +++ b/src/main/java/org/bukkit/Art.java @@ -0,0 +1,111 @@ +package org.bukkit; + +import java.util.HashMap; + +import org.apache.commons.lang.Validate; + +import com.google.common.collect.Maps; + +/** + * Represents the art on a painting + */ +public enum Art { + KEBAB(0, 1, 1), + AZTEC(1, 1, 1), + ALBAN(2, 1, 1), + AZTEC2(3, 1, 1), + BOMB(4, 1, 1), + PLANT(5, 1, 1), + WASTELAND(6, 1, 1), + POOL(7, 2, 1), + COURBET(8, 2, 1), + SEA(9, 2, 1), + SUNSET(10, 2, 1), + CREEBET(11, 2, 1), + WANDERER(12, 1, 2), + GRAHAM(13, 1, 2), + MATCH(14, 2, 2), + BUST(15, 2, 2), + STAGE(16, 2, 2), + VOID(17, 2, 2), + SKULL_AND_ROSES(18, 2, 2), + WITHER(19, 2, 2), + FIGHTERS(20, 4, 2), + POINTER(21, 4, 4), + PIGSCENE(22, 4, 4), + BURNINGSKULL(23, 4, 4), + SKELETON(24, 4, 3), + DONKEYKONG(25, 4, 3); + + private int id, width, height; + private static final HashMap BY_NAME = Maps.newHashMap(); + private static final HashMap BY_ID = Maps.newHashMap(); + + private Art(int id, int width, int height) { + this.id = id; + this.width = width; + this.height = height; + } + + /** + * Gets the width of the painting, in blocks + * + * @return The width of the painting, in blocks + */ + public int getBlockWidth() { + return width; + } + + /** + * Gets the height of the painting, in blocks + * + * @return The height of the painting, in blocks + */ + public int getBlockHeight() { + return height; + } + + /** + * Get the ID of this painting. + * + * @return The ID of this painting + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Get a painting by its numeric ID + * + * @param id The ID + * @return The painting + * @deprecated Magic value + */ + @Deprecated + public static Art getById(int id) { + return BY_ID.get(id); + } + + /** + * Get a painting by its unique name + *

+ * This ignores underscores and capitalization + * + * @param name The name + * @return The painting + */ + public static Art getByName(String name) { + Validate.notNull(name, "Name cannot be null"); + + return BY_NAME.get(name.toLowerCase().replaceAll("_", "")); + } + + static { + for (Art art : values()) { + BY_ID.put(art.id, art); + BY_NAME.put(art.toString().toLowerCase().replaceAll("_", ""), art); + } + } +} diff --git a/src/main/java/org/bukkit/BanEntry.java b/src/main/java/org/bukkit/BanEntry.java new file mode 100644 index 0000000..986120e --- /dev/null +++ b/src/main/java/org/bukkit/BanEntry.java @@ -0,0 +1,127 @@ +package org.bukkit; + +import java.util.Date; + +/** + * A single entry from a ban list. This may represent either a player ban or + * an IP ban. + *

+ * Ban entries include the following properties: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
PropertyDescription
Target Name / IP AddressThe target name or IP address
Creation DateThe creation date of the ban
SourceThe source of the ban, such as a player, console, plugin, etc
Expiration DateThe expiration date of the ban
ReasonThe reason for the ban
+ *

+ * Unsaved information is not automatically written to the implementation's + * ban list, instead, the {@link #save()} method must be called to write the + * changes to the ban list. If this ban entry has expired (such as from an + * unban) and is no longer found in the list, the {@link #save()} call will + * re-add it to the list, therefore banning the victim specified. + *

+ * Likewise, changes to the associated {@link BanList} or other entries may or + * may not be reflected in this entry. + */ +public interface BanEntry { + + /** + * Gets the target involved. This may be in the form of an IP or a player + * name. + * + * @return the target name or IP address + */ + public String getTarget(); + + /** + * Gets the date this ban entry was created. + * + * @return the creation date + */ + public Date getCreated(); + + /** + * Sets the date this ban entry was created. + * + * @param created the new created date, cannot be null + * @see #save() saving changes + */ + public void setCreated(Date created); + + /** + * Gets the source of this ban. + *

+ * Note: A source is considered any String, although this is generally a + * player name. + * + * @return the source of the ban + */ + public String getSource(); + + /** + * Sets the source of this ban. + *

+ * Note: A source is considered any String, although this is generally a + * player name. + * + * @param source the new source where null values become empty strings + * @see #save() saving changes + */ + public void setSource(String source); + + /** + * Gets the date this ban expires on, or null for no defined end date. + * + * @return the expiration date + */ + public Date getExpiration(); + + /** + * Sets the date this ban expires on. Null values are considered + * "infinite" bans. + * + * @param expiration the new expiration date, or null to indicate an + * eternity + * @see #save() saving changes + */ + public void setExpiration(Date expiration); + + /** + * Gets the reason for this ban. + * + * @return the ban reason, or null if not set + */ + public String getReason(); + + /** + * Sets the reason for this ban. Reasons must not be null. + * + * @param reason the new reason, null values assume the implementation + * default + * @see #save() saving changes + */ + public void setReason(String reason); + + /** + * Saves the ban entry, overwriting any previous data in the ban list. + *

+ * Saving the ban entry of an unbanned player will cause the player to be + * banned once again. + */ + public void save(); +} diff --git a/src/main/java/org/bukkit/BanList.java b/src/main/java/org/bukkit/BanList.java new file mode 100644 index 0000000..c21b858 --- /dev/null +++ b/src/main/java/org/bukkit/BanList.java @@ -0,0 +1,72 @@ +package org.bukkit; + +import java.util.Date; +import java.util.Set; + +/** + * A ban list, containing bans of some {@link Type}. + */ +public interface BanList { + + /** + * Represents a ban-type that a {@link BanList} may track. + */ + public enum Type { + /** + * Banned player names + */ + NAME, + /** + * Banned player IP addresses + */ + IP, + ; + } + + /** + * Gets a {@link BanEntry} by target. + * + * @param target entry parameter to search for + * @return the corresponding entry, or null if none found + */ + public BanEntry getBanEntry(String target); + + /** + * Adds a ban to the this list. If a previous ban exists, this will + * update the previous entry. + * + * @param target the target of the ban + * @param reason reason for the ban, null indicates implementation default + * @param expires date for the ban's expiration (unban), or null to imply + * forever + * @param source source of the ban, null indicates implementation default + * @return the entry for the newly created ban, or the entry for the + * (updated) previous ban + */ + public BanEntry addBan(String target, String reason, Date expires, String source); + + /** + * Gets a set containing every {@link BanEntry} in this list. + * + * @return an immutable set containing every entry tracked by this list + */ + public Set getBanEntries(); + + /** + * Gets if a {@link BanEntry} exists for the target, indicating an active + * ban status. + * + * @param target the target to find + * @return true if a {@link BanEntry} exists for the name, indicating an + * active ban status, false otherwise + */ + public boolean isBanned(String target); + + /** + * Removes the specified target from this list, therefore indicating a + * "not banned" status. + * + * @param target the target to remove from this list + */ + public void pardon(String target); +} diff --git a/src/main/java/org/bukkit/BlockChangeDelegate.java b/src/main/java/org/bukkit/BlockChangeDelegate.java new file mode 100644 index 0000000..e6b9f0e --- /dev/null +++ b/src/main/java/org/bukkit/BlockChangeDelegate.java @@ -0,0 +1,104 @@ +package org.bukkit; + +/** + * A delegate for handling block changes. This serves as a direct interface + * between generation algorithms in the server implementation and utilizing + * code. + */ +public interface BlockChangeDelegate { + + /** + * Set a block type at the specified coordinates without doing all world + * updates and notifications. + *

+ * It is safe to have this call World.setTypeId, but it may be slower than + * World.setRawTypeId. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param typeId New block ID + * @return true if the block was set successfully + * @deprecated Magic value + */ + @Deprecated + public boolean setRawTypeId(int x, int y, int z, int typeId); + + /** + * Set a block type and data at the specified coordinates without doing + * all world updates and notifications. + *

+ * It is safe to have this call World.setTypeId, but it may be slower than + * World.setRawTypeId. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param typeId New block ID + * @param data Block data + * @return true if the block was set successfully + * @deprecated Magic value + */ + @Deprecated + public boolean setRawTypeIdAndData(int x, int y, int z, int typeId, int data); + + /** + * Set a block type at the specified coordinates. + *

+ * This method cannot call World.setRawTypeId, a full update is needed. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param typeId New block ID + * @return true if the block was set successfully + * @deprecated Magic value + */ + @Deprecated + public boolean setTypeId(int x, int y, int z, int typeId); + + /** + * Set a block type and data at the specified coordinates. + *

+ * This method cannot call World.setRawTypeId, a full update is needed. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param typeId New block ID + * @param data Block data + * @return true if the block was set successfully + * @deprecated Magic value + */ + @Deprecated + public boolean setTypeIdAndData(int x, int y, int z, int typeId, int data); + + /** + * Get the block type at the location. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return The block ID + * @deprecated Magic value + */ + @Deprecated + public int getTypeId(int x, int y, int z); + + /** + * Gets the height of the world. + * + * @return Height of the world + */ + public int getHeight(); + + /** + * Checks if the specified block is empty (air) or not. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return True if the block is considered empty. + */ + public boolean isEmpty(int x, int y, int z); +} diff --git a/src/main/java/org/bukkit/Bukkit.java b/src/main/java/org/bukkit/Bukkit.java new file mode 100644 index 0000000..1eaf92d --- /dev/null +++ b/src/main/java/org/bukkit/Bukkit.java @@ -0,0 +1,750 @@ +package org.bukkit; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Logger; + +import org.bukkit.Warning.WarningState; +import org.bukkit.command.CommandException; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.help.HelpMap; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemFactory; +import org.bukkit.inventory.Recipe; +import org.bukkit.map.MapView; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.ServicesManager; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scoreboard.ScoreboardManager; +import org.bukkit.util.CachedServerIcon; + +import com.avaje.ebean.config.ServerConfig; + +/** + * Represents the Bukkit core, for version and Server singleton handling + */ +public final class Bukkit { + private static Server server; + + /** + * Static class cannot be initialized. + */ + private Bukkit() {} + + /** + * Gets the current {@link Server} singleton + * + * @return Server instance being ran + */ + public static Server getServer() { + return server; + } + + /** + * Attempts to set the {@link Server} singleton. + *

+ * This cannot be done if the Server is already set. + * + * @param server Server instance + */ + public static void setServer(Server server) { + if (Bukkit.server != null) { + throw new UnsupportedOperationException("Cannot redefine singleton Server"); + } + + Bukkit.server = server; + server.getLogger().info("This server is running " + getName() + " version " + getVersion() + " (Implementing API version " + getBukkitVersion() + ")"); + } + + /** + * @see Server#getName() + */ + public static String getName() { + return server.getName(); + } + + /** + * @see Server#getVersion() + */ + public static String getVersion() { + return server.getVersion(); + } + + /** + * @see Server#getBukkitVersion() + */ + public static String getBukkitVersion() { + return server.getBukkitVersion(); + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @Deprecated + * @see Server#_INVALID_getOnlinePlayers() + */ + @Deprecated + public static Player[] _INVALID_getOnlinePlayers() { + return server._INVALID_getOnlinePlayers(); + } + + /** + * @see Server#getOnlinePlayers() + */ + public static Collection getOnlinePlayers() { + return server.getOnlinePlayers(); + } + + /** + * @see Server#getMaxPlayers() + */ + public static int getMaxPlayers() { + return server.getMaxPlayers(); + } + + /** + * @see Server#getPort() + */ + public static int getPort() { + return server.getPort(); + } + + /** + * @see Server#getViewDistance() + */ + public static int getViewDistance() { + return server.getViewDistance(); + } + + /** + * @see Server#getIp() + */ + public static String getIp() { + return server.getIp(); + } + + /** + * @see Server#getServerName() + */ + public static String getServerName() { + return server.getServerName(); + } + + /** + * @see Server#getServerId() + */ + public static String getServerId() { + return server.getServerId(); + } + + /** + * @see Server#getWorldType() + */ + public static String getWorldType() { + return server.getWorldType(); + } + + /** + * @see Server#getGenerateStructures() + */ + public static boolean getGenerateStructures() { + return server.getGenerateStructures(); + } + + /** + * @see Server#getAllowNether() + */ + public static boolean getAllowNether() { + return server.getAllowNether(); + } + + /** + * @see Server#hasWhitelist() + */ + public static boolean hasWhitelist() { + return server.hasWhitelist(); + } + + /** + * @see Server#broadcastMessage(String message) + */ + public static int broadcastMessage(String message) { + return server.broadcastMessage(message); + } + + /** + * @see Server#getUpdateFolder() + */ + public static String getUpdateFolder() { + return server.getUpdateFolder(); + } + + /** + * @see Server#getPlayer(String name) + */ + @Deprecated + public static Player getPlayer(String name) { + return server.getPlayer(name); + } + + /** + * @see Server#matchPlayer(String name) + */ + @Deprecated + public static List matchPlayer(String name) { + return server.matchPlayer(name); + } + + /** + * @see Server#getPlayer(java.util.UUID) + */ + public static Player getPlayer(UUID id) { + return server.getPlayer(id); + } + + /** + * @see Server#getPluginManager() + */ + public static PluginManager getPluginManager() { + return server.getPluginManager(); + } + + /** + * @see Server#getScheduler() + */ + public static BukkitScheduler getScheduler() { + return server.getScheduler(); + } + + /** + * @see Server#getServicesManager() + */ + public static ServicesManager getServicesManager() { + return server.getServicesManager(); + } + + /** + * @see Server#getWorlds() + */ + public static List getWorlds() { + return server.getWorlds(); + } + + /** + * @see Server#createWorld(WorldCreator options) + */ + public static World createWorld(WorldCreator options) { + return server.createWorld(options); + } + + /** + * @see Server#unloadWorld(String name, boolean save) + */ + public static boolean unloadWorld(String name, boolean save) { + return server.unloadWorld(name, save); + } + + /** + * @see Server#unloadWorld(World world, boolean save) + */ + public static boolean unloadWorld(World world, boolean save) { + return server.unloadWorld(world, save); + } + + /** + * @see Server#getWorld(String name) + */ + public static World getWorld(String name) { + return server.getWorld(name); + } + + /** + * @see Server#getWorld(UUID uid) + */ + public static World getWorld(UUID uid) { + return server.getWorld(uid); + } + + /** + * @see Server#getMap(short id) + * @deprecated Magic value + */ + @Deprecated + public static MapView getMap(short id) { + return server.getMap(id); + } + + /** + * @see Server#createMap(World world) + */ + public static MapView createMap(World world) { + return server.createMap(world); + } + + /** + * @see Server#reload() + */ + public static void reload() { + server.reload(); + } + + /** + * @see Server#getLogger() + */ + public static Logger getLogger() { + return server.getLogger(); + } + + /** + * @see Server#getPluginCommand(String name) + */ + public static PluginCommand getPluginCommand(String name) { + return server.getPluginCommand(name); + } + + /** + * @see Server#savePlayers() + */ + public static void savePlayers() { + server.savePlayers(); + } + + /** + * @see Server#dispatchCommand(CommandSender sender, String commandLine) + */ + public static boolean dispatchCommand(CommandSender sender, String commandLine) throws CommandException { + return server.dispatchCommand(sender, commandLine); + } + + /** + * @see Server#configureDbConfig(ServerConfig config) + */ + public static void configureDbConfig(ServerConfig config) { + server.configureDbConfig(config); + } + + /** + * @see Server#addRecipe(Recipe recipe) + */ + public static boolean addRecipe(Recipe recipe) { + return server.addRecipe(recipe); + } + + /** + * @see Server#getRecipesFor(ItemStack result) + */ + public static List getRecipesFor(ItemStack result) { + return server.getRecipesFor(result); + } + + /** + * @see Server#recipeIterator() + */ + public static Iterator recipeIterator() { + return server.recipeIterator(); + } + + /** + * @see Server#clearRecipes() + */ + public static void clearRecipes() { + server.clearRecipes(); + } + + /** + * @see Server#resetRecipes() + */ + public static void resetRecipes() { + server.resetRecipes(); + } + + /** + * @see Server#getCommandAliases() + */ + public static Map getCommandAliases() { + return server.getCommandAliases(); + } + + /** + * @see Server#getSpawnRadius() + */ + public static int getSpawnRadius() { + return server.getSpawnRadius(); + } + + /** + * @see Server#setSpawnRadius(int value) + */ + public static void setSpawnRadius(int value) { + server.setSpawnRadius(value); + } + + /** + * @see Server#getOnlineMode() + */ + public static boolean getOnlineMode() { + return server.getOnlineMode(); + } + + /** + * @see Server#getAllowFlight() + */ + public static boolean getAllowFlight() { + return server.getAllowFlight(); + } + + /** + * @see Server#isHardcore() + */ + public static boolean isHardcore() { + return server.isHardcore(); + } + + /** + * @see Server#shutdown() + */ + public static void shutdown() { + server.shutdown(); + } + + /** + * @see Server#broadcast(String message, String permission) + */ + public static int broadcast(String message, String permission) { + return server.broadcast(message, permission); + } + + /** + * @see Server#getOfflinePlayer(String name) + */ + @Deprecated + public static OfflinePlayer getOfflinePlayer(String name) { + return server.getOfflinePlayer(name); + } + + /** + * @see Server#getOfflinePlayer(java.util.UUID) + */ + public static OfflinePlayer getOfflinePlayer(UUID id) { + return server.getOfflinePlayer(id); + } + + /** + * @see Server#getPlayerExact(String name) + */ + @Deprecated + public static Player getPlayerExact(String name) { + return server.getPlayerExact(name); + } + + /** + * @see Server#getIPBans() + */ + public static Set getIPBans() { + return server.getIPBans(); + } + + /** + * @see Server#banIP(String address) + */ + public static void banIP(String address) { + server.banIP(address); + } + + /** + * @see Server#unbanIP(String address) + */ + public static void unbanIP(String address) { + server.unbanIP(address); + } + + /** + * @see Server#getBannedPlayers() + */ + public static Set getBannedPlayers() { + return server.getBannedPlayers(); + } + + /** + * @see Server#getBanList(BanList.Type) + */ + public static BanList getBanList(BanList.Type type){ + return server.getBanList(type); + } + + /** + * @see Server#setWhitelist(boolean value) + */ + public static void setWhitelist(boolean value) { + server.setWhitelist(value); + } + + /** + * @see Server#getWhitelistedPlayers() + */ + public static Set getWhitelistedPlayers() { + return server.getWhitelistedPlayers(); + } + + /** + * @see Server#reloadWhitelist() + */ + public static void reloadWhitelist() { + server.reloadWhitelist(); + } + + /** + * @see Server#getConsoleSender() + */ + public static ConsoleCommandSender getConsoleSender() { + return server.getConsoleSender(); + } + + /** + * @see Server#getOperators() + */ + public static Set getOperators() { + return server.getOperators(); + } + + /** + * @see Server#getWorldContainer() + */ + public static File getWorldContainer() { + return server.getWorldContainer(); + } + + /** + * @see Server#getMessenger() + */ + public static Messenger getMessenger() { + return server.getMessenger(); + } + + /** + * @see Server#getAllowEnd() + */ + public static boolean getAllowEnd() { + return server.getAllowEnd(); + } + + /** + * @see Server#getUpdateFolderFile() + */ + public static File getUpdateFolderFile() { + return server.getUpdateFolderFile(); + } + + /** + * @see Server#getConnectionThrottle() + */ + public static long getConnectionThrottle() { + return server.getConnectionThrottle(); + } + + /** + * @see Server#getTicksPerAnimalSpawns() + */ + public static int getTicksPerAnimalSpawns() { + return server.getTicksPerAnimalSpawns(); + } + + /** + * @see Server#getTicksPerMonsterSpawns() + */ + public static int getTicksPerMonsterSpawns() { + return server.getTicksPerMonsterSpawns(); + } + + /** + * @see Server#useExactLoginLocation() + */ + public static boolean useExactLoginLocation() { + return server.useExactLoginLocation(); + } + + /** + * @see Server#getDefaultGameMode() + */ + public static GameMode getDefaultGameMode() { + return server.getDefaultGameMode(); + } + + /** + * @see Server#setDefaultGameMode(GameMode mode) + */ + public static void setDefaultGameMode(GameMode mode) { + server.setDefaultGameMode(mode); + } + + /** + * @see Server#getOfflinePlayers() + */ + public static OfflinePlayer[] getOfflinePlayers() { + return server.getOfflinePlayers(); + } + + /** + * @see Server#createInventory(InventoryHolder owner, InventoryType type) + */ + public static Inventory createInventory(InventoryHolder owner, InventoryType type) { + return server.createInventory(owner, type); + } + + /** + * @see Server#createInventory(InventoryHolder owner, InventoryType type, String title) + */ + public static Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { + return server.createInventory(owner, type, title); + } + + /** + * @see Server#createInventory(InventoryHolder owner, int size) + */ + public static Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException { + return server.createInventory(owner, size); + } + + /** + * @see Server#createInventory(InventoryHolder owner, int size, String + * title) + */ + public static Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException { + return server.createInventory(owner, size, title); + } + + /** + * @see Server#getHelpMap() + */ + public static HelpMap getHelpMap() { + return server.getHelpMap(); + } + + /** + * @see Server#getMonsterSpawnLimit() + */ + public static int getMonsterSpawnLimit() { + return server.getMonsterSpawnLimit(); + } + + /** + * @see Server#getAnimalSpawnLimit() + */ + public static int getAnimalSpawnLimit() { + return server.getAnimalSpawnLimit(); + } + + /** + * @see Server#getWaterAnimalSpawnLimit() + */ + public static int getWaterAnimalSpawnLimit() { + return server.getWaterAnimalSpawnLimit(); + } + + /** + * @see Server#getAmbientSpawnLimit() + */ + public static int getAmbientSpawnLimit() { + return server.getAmbientSpawnLimit(); + } + + /** + * @see Server#isPrimaryThread() + */ + public static boolean isPrimaryThread() { + return server.isPrimaryThread(); + } + + /** + * @see Server#getMotd() + */ + public static String getMotd() { + return server.getMotd(); + } + + /** + * @see Server#getShutdownMessage() + */ + public static String getShutdownMessage() { + return server.getShutdownMessage(); + } + + /** + * @see Server#getWarningState() + */ + public static WarningState getWarningState() { + return server.getWarningState(); + } + + /** + * @see Server#getItemFactory() + */ + public static ItemFactory getItemFactory() { + return server.getItemFactory(); + } + + /** + * @see Server#getScoreboardManager() + */ + public static ScoreboardManager getScoreboardManager() { + return server.getScoreboardManager(); + } + + /** + * @see Server#getServerIcon() + */ + public static CachedServerIcon getServerIcon() { + return server.getServerIcon(); + } + + /** + * @see Server#loadServerIcon(File) + */ + public static CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception { + return server.loadServerIcon(file); + } + + /** + * @see Server#loadServerIcon(BufferedImage) + */ + public static CachedServerIcon loadServerIcon(BufferedImage image) throws IllegalArgumentException, Exception { + return server.loadServerIcon(image); + } + + /** + * @see Server#setIdleTimeout(int) + */ + public static void setIdleTimeout(int threshold) { + server.setIdleTimeout(threshold); + } + + /** + * @see Server#getIdleTimeout() + */ + public static int getIdleTimeout() { + return server.getIdleTimeout(); + } + + /** + * @see Server#getUnsafe() + */ + @Deprecated + public static UnsafeValues getUnsafe() { + return server.getUnsafe(); + } +} diff --git a/src/main/java/org/bukkit/ChatColor.java b/src/main/java/org/bukkit/ChatColor.java new file mode 100644 index 0000000..0bbc9fa --- /dev/null +++ b/src/main/java/org/bukkit/ChatColor.java @@ -0,0 +1,253 @@ +package org.bukkit; + +import java.util.Map; +import java.util.regex.Pattern; + +import org.apache.commons.lang.Validate; + +import com.google.common.collect.Maps; + +/** + * All supported color values for chat + */ +public enum ChatColor { + /** + * Represents black + */ + BLACK('0', 0x00), + /** + * Represents dark blue + */ + DARK_BLUE('1', 0x1), + /** + * Represents dark green + */ + DARK_GREEN('2', 0x2), + /** + * Represents dark blue (aqua) + */ + DARK_AQUA('3', 0x3), + /** + * Represents dark red + */ + DARK_RED('4', 0x4), + /** + * Represents dark purple + */ + DARK_PURPLE('5', 0x5), + /** + * Represents gold + */ + GOLD('6', 0x6), + /** + * Represents gray + */ + GRAY('7', 0x7), + /** + * Represents dark gray + */ + DARK_GRAY('8', 0x8), + /** + * Represents blue + */ + BLUE('9', 0x9), + /** + * Represents green + */ + GREEN('a', 0xA), + /** + * Represents aqua + */ + AQUA('b', 0xB), + /** + * Represents red + */ + RED('c', 0xC), + /** + * Represents light purple + */ + LIGHT_PURPLE('d', 0xD), + /** + * Represents yellow + */ + YELLOW('e', 0xE), + /** + * Represents white + */ + WHITE('f', 0xF), + /** + * Represents magical characters that change around randomly + */ + MAGIC('k', 0x10, true), + /** + * Makes the text bold. + */ + BOLD('l', 0x11, true), + /** + * Makes a line appear through the text. + */ + STRIKETHROUGH('m', 0x12, true), + /** + * Makes the text appear underlined. + */ + UNDERLINE('n', 0x13, true), + /** + * Makes the text italic. + */ + ITALIC('o', 0x14, true), + /** + * Resets all previous chat colors or formats. + */ + RESET('r', 0x15); + + /** + * The special character which prefixes all chat colour codes. Use this if + * you need to dynamically convert colour codes from your custom format. + */ + public static final char COLOR_CHAR = '\u00A7'; + private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-FK-OR]"); + + private final int intCode; + private final char code; + private final boolean isFormat; + private final String toString; + private final static Map BY_ID = Maps.newHashMap(); + private final static Map BY_CHAR = Maps.newHashMap(); + + private ChatColor(char code, int intCode) { + this(code, intCode, false); + } + + private ChatColor(char code, int intCode, boolean isFormat) { + this.code = code; + this.intCode = intCode; + this.isFormat = isFormat; + this.toString = new String(new char[] {COLOR_CHAR, code}); + } + + /** + * Gets the char value associated with this color + * + * @return A char value of this color code + */ + public char getChar() { + return code; + } + + @Override + public String toString() { + return toString; + } + + /** + * Checks if this code is a format code as opposed to a color code. + */ + public boolean isFormat() { + return isFormat; + } + + /** + * Checks if this code is a color code as opposed to a format code. + */ + public boolean isColor() { + return !isFormat && this != RESET; + } + + /** + * Gets the color represented by the specified color code + * + * @param code Code to check + * @return Associative {@link org.bukkit.ChatColor} with the given code, + * or null if it doesn't exist + */ + public static ChatColor getByChar(char code) { + return BY_CHAR.get(code); + } + + /** + * Gets the color represented by the specified color code + * + * @param code Code to check + * @return Associative {@link org.bukkit.ChatColor} with the given code, + * or null if it doesn't exist + */ + public static ChatColor getByChar(String code) { + Validate.notNull(code, "Code cannot be null"); + Validate.isTrue(code.length() > 0, "Code must have at least one char"); + + return BY_CHAR.get(code.charAt(0)); + } + + /** + * Strips the given message of all color codes + * + * @param input String to strip of color + * @return A copy of the input string, without any coloring + */ + public static String stripColor(final String input) { + if (input == null) { + return null; + } + + return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); + } + + /** + * Translates a string using an alternate color code character into a + * string that uses the internal ChatColor.COLOR_CODE color code + * character. The alternate color code character will only be replaced if + * it is immediately followed by 0-9, A-F, a-f, K-O, k-o, R or r. + * + * @param altColorChar The alternate color code character to replace. Ex: & + * @param textToTranslate Text containing the alternate color code character. + * @return Text containing the ChatColor.COLOR_CODE color code character. + */ + public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { + char[] b = textToTranslate.toCharArray(); + for (int i = 0; i < b.length - 1; i++) { + if (b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i+1]) > -1) { + b[i] = ChatColor.COLOR_CHAR; + b[i+1] = Character.toLowerCase(b[i+1]); + } + } + return new String(b); + } + + /** + * Gets the ChatColors used at the end of the given input string. + * + * @param input Input string to retrieve the colors from. + * @return Any remaining ChatColors to pass onto the next line. + */ + public static String getLastColors(String input) { + String result = ""; + int length = input.length(); + + // Search backwards from the end as it is faster + for (int index = length - 1; index > -1; index--) { + char section = input.charAt(index); + if (section == COLOR_CHAR && index < length - 1) { + char c = input.charAt(index + 1); + ChatColor color = getByChar(c); + + if (color != null) { + result = color.toString() + result; + + // Once we find a color or reset we can stop searching + if (color.isColor() || color.equals(RESET)) { + break; + } + } + } + } + + return result; + } + + static { + for (ChatColor color : values()) { + BY_ID.put(color.intCode, color); + BY_CHAR.put(color.code, color); + } + } +} diff --git a/src/main/java/org/bukkit/Chunk.java b/src/main/java/org/bukkit/Chunk.java new file mode 100644 index 0000000..0510151 --- /dev/null +++ b/src/main/java/org/bukkit/Chunk.java @@ -0,0 +1,124 @@ +package org.bukkit; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Entity; + +/** + * Represents a chunk of blocks + */ +public interface Chunk { + + /** + * Gets the X-coordinate of this chunk + * + * @return X-coordinate + */ + int getX(); + + /** + * Gets the Z-coordinate of this chunk + * + * @return Z-coordinate + */ + int getZ(); + + /** + * Gets the world containing this chunk + * + * @return Parent World + */ + World getWorld(); + + /** + * Gets a block from this chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return the Block + */ + Block getBlock(int x, int y, int z); + + /** + * Capture thread-safe read-only snapshot of chunk data + * + * @return ChunkSnapshot + */ + ChunkSnapshot getChunkSnapshot(); + + /** + * Capture thread-safe read-only snapshot of chunk data + * + * @param includeMaxblocky - if true, snapshot includes per-coordinate + * maximum Y values + * @param includeBiome - if true, snapshot includes per-coordinate biome + * type + * @param includeBiomeTempRain - if true, snapshot includes per-coordinate + * raw biome temperature and rainfall + * @return ChunkSnapshot + */ + ChunkSnapshot getChunkSnapshot(boolean includeMaxblocky, boolean includeBiome, boolean includeBiomeTempRain); + + /** + * Get a list of all entities in the chunk. + * + * @return The entities. + */ + Entity[] getEntities(); + + /** + * Get a list of all tile entities in the chunk. + * + * @return The tile entities. + */ + BlockState[] getTileEntities(); + + /** + * Checks if the chunk is loaded. + * + * @return True if it is loaded. + */ + boolean isLoaded(); + + /** + * Loads the chunk. + * + * @param generate Whether or not to generate a chunk if it doesn't + * already exist + * @return true if the chunk has loaded successfully, otherwise false + */ + boolean load(boolean generate); + + /** + * Loads the chunk. + * + * @return true if the chunk has loaded successfully, otherwise false + */ + boolean load(); + + /** + * Unloads and optionally saves the Chunk + * + * @param save Controls whether the chunk is saved + * @param safe Controls whether to unload the chunk when players are + * nearby + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unload(boolean save, boolean safe); + + /** + * Unloads and optionally saves the Chunk + * + * @param save Controls whether the chunk is saved + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unload(boolean save); + + /** + * Unloads and optionally saves the Chunk + * + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unload(); +} diff --git a/src/main/java/org/bukkit/ChunkSnapshot.java b/src/main/java/org/bukkit/ChunkSnapshot.java new file mode 100644 index 0000000..83fccc8 --- /dev/null +++ b/src/main/java/org/bukkit/ChunkSnapshot.java @@ -0,0 +1,129 @@ +package org.bukkit; + +import org.bukkit.block.Biome; + +/** + * Represents a static, thread-safe snapshot of chunk of blocks. + *

+ * Purpose is to allow clean, efficient copy of a chunk data to be made, and + * then handed off for processing in another thread (e.g. map rendering) + */ +public interface ChunkSnapshot { + + /** + * Gets the X-coordinate of this chunk + * + * @return X-coordinate + */ + int getX(); + + /** + * Gets the Z-coordinate of this chunk + * + * @return Z-coordinate + */ + int getZ(); + + /** + * Gets name of the world containing this chunk + * + * @return Parent World Name + */ + String getWorldName(); + + /** + * Get block type for block at corresponding coordinate in the chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return 0-255 + * @deprecated Magic value + */ + @Deprecated + int getBlockTypeId(int x, int y, int z); + + /** + * Get block data for block at corresponding coordinate in the chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return 0-15 + * @deprecated Magic value + */ + @Deprecated + int getBlockData(int x, int y, int z); + + /** + * Get sky light level for block at corresponding coordinate in the chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return 0-15 + */ + int getBlockSkyLight(int x, int y, int z); + + /** + * Get light level emitted by block at corresponding coordinate in the + * chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return 0-15 + */ + int getBlockEmittedLight(int x, int y, int z); + + /** + * Gets the highest non-air coordinate at the given coordinates + * + * @param x X-coordinate of the blocks + * @param z Z-coordinate of the blocks + * @return Y-coordinate of the highest non-air block + */ + int getHighestBlockYAt(int x, int z); + + /** + * Get biome at given coordinates + * + * @param x X-coordinate + * @param z Z-coordinate + * @return Biome at given coordinate + */ + Biome getBiome(int x, int z); + + /** + * Get raw biome temperature (0.0-1.0) at given coordinate + * + * @param x X-coordinate + * @param z Z-coordinate + * @return temperature at given coordinate + */ + double getRawBiomeTemperature(int x, int z); + + /** + * Get raw biome rainfall (0.0-1.0) at given coordinate + * + * @param x X-coordinate + * @param z Z-coordinate + * @return rainfall at given coordinate + */ + double getRawBiomeRainfall(int x, int z); + + /** + * Get world full time when chunk snapshot was captured + * + * @return time in ticks + */ + long getCaptureFullTime(); + + /** + * Test if section is empty + * + * @param sy - section Y coordinate (block Y / 16) + * @return true if empty, false if not + */ + boolean isSectionEmpty(int sy); +} diff --git a/src/main/java/org/bukkit/CoalType.java b/src/main/java/org/bukkit/CoalType.java new file mode 100644 index 0000000..4fcccd2 --- /dev/null +++ b/src/main/java/org/bukkit/CoalType.java @@ -0,0 +1,50 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +/** + * Represents the two types of coal + */ +public enum CoalType { + COAL(0x0), + CHARCOAL(0x1); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + private CoalType(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this type of coal + * + * @return A byte containing the data value of this coal type + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the type of coal with the given data value + * + * @param data Data value to fetch + * @return The {@link CoalType} representing the given value, or null if + * it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static CoalType getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (CoalType type : values()) { + BY_DATA.put(type.data, type); + } + } +} diff --git a/src/main/java/org/bukkit/Color.java b/src/main/java/org/bukkit/Color.java new file mode 100644 index 0000000..76ff651 --- /dev/null +++ b/src/main/java/org/bukkit/Color.java @@ -0,0 +1,344 @@ +package org.bukkit; + +import java.util.Map; + +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; + +import com.google.common.collect.ImmutableMap; + +/** + * A container for a color palette. This class is immutable; the set methods + * return a new color. The color names listed as fields are HTML4 standards, + * but subject to change. + */ +@SerializableAs("Color") +public final class Color implements ConfigurationSerializable { + private static final int BIT_MASK = 0xff; + + /** + * White, or (0xFF,0xFF,0xFF) in (R,G,B) + */ + public static final Color WHITE = fromRGB(0xFFFFFF); + + /** + * Silver, or (0xC0,0xC0,0xC0) in (R,G,B) + */ + public static final Color SILVER = fromRGB(0xC0C0C0); + + /** + * Gray, or (0x80,0x80,0x80) in (R,G,B) + */ + public static final Color GRAY = fromRGB(0x808080); + + /** + * Black, or (0x00,0x00,0x00) in (R,G,B) + */ + public static final Color BLACK = fromRGB(0x000000); + + /** + * Red, or (0xFF,0x00,0x00) in (R,G,B) + */ + public static final Color RED = fromRGB(0xFF0000); + + /** + * Maroon, or (0x80,0x00,0x00) in (R,G,B) + */ + public static final Color MAROON = fromRGB(0x800000); + + /** + * Yellow, or (0xFF,0xFF,0x00) in (R,G,B) + */ + public static final Color YELLOW = fromRGB(0xFFFF00); + + /** + * Olive, or (0x80,0x80,0x00) in (R,G,B) + */ + public static final Color OLIVE = fromRGB(0x808000); + + /** + * Lime, or (0x00,0xFF,0x00) in (R,G,B) + */ + public static final Color LIME = fromRGB(0x00FF00); + + /** + * Green, or (0x00,0x80,0x00) in (R,G,B) + */ + public static final Color GREEN = fromRGB(0x008000); + + /** + * Aqua, or (0x00,0xFF,0xFF) in (R,G,B) + */ + public static final Color AQUA = fromRGB(0x00FFFF); + + /** + * Teal, or (0x00,0x80,0x80) in (R,G,B) + */ + public static final Color TEAL = fromRGB(0x008080); + + /** + * Blue, or (0x00,0x00,0xFF) in (R,G,B) + */ + public static final Color BLUE = fromRGB(0x0000FF); + + /** + * Navy, or (0x00,0x00,0x80) in (R,G,B) + */ + public static final Color NAVY = fromRGB(0x000080); + + /** + * Fuchsia, or (0xFF,0x00,0xFF) in (R,G,B) + */ + public static final Color FUCHSIA = fromRGB(0xFF00FF); + + /** + * Purple, or (0x80,0x00,0x80) in (R,G,B) + */ + public static final Color PURPLE = fromRGB(0x800080); + + /** + * Orange, or (0xFF,0xA5,0x00) in (R,G,B) + */ + public static final Color ORANGE = fromRGB(0xFFA500); + + private final byte red; + private final byte green; + private final byte blue; + + /** + * Creates a new Color object from a red, green, and blue + * + * @param red integer from 0-255 + * @param green integer from 0-255 + * @param blue integer from 0-255 + * @return a new Color object for the red, green, blue + * @throws IllegalArgumentException if any value is strictly >255 or <0 + */ + public static Color fromRGB(int red, int green, int blue) throws IllegalArgumentException { + return new Color(red, green, blue); + } + + /** + * Creates a new Color object from a blue, green, and red + * + * @param blue integer from 0-255 + * @param green integer from 0-255 + * @param red integer from 0-255 + * @return a new Color object for the red, green, blue + * @throws IllegalArgumentException if any value is strictly >255 or <0 + */ + public static Color fromBGR(int blue, int green, int red) throws IllegalArgumentException { + return new Color(red, green, blue); + } + + /** + * Creates a new color object from an integer that contains the red, + * green, and blue bytes in the lowest order 24 bits. + * + * @param rgb the integer storing the red, green, and blue values + * @return a new color object for specified values + * @throws IllegalArgumentException if any data is in the highest order 8 + * bits + */ + public static Color fromRGB(int rgb) throws IllegalArgumentException { + Validate.isTrue((rgb >> 24) == 0, "Extrenuous data in: ", rgb); + return fromRGB(rgb >> 16 & BIT_MASK, rgb >> 8 & BIT_MASK, rgb >> 0 & BIT_MASK); + } + + /** + * Creates a new color object from an integer that contains the blue, + * green, and red bytes in the lowest order 24 bits. + * + * @param bgr the integer storing the blue, green, and red values + * @return a new color object for specified values + * @throws IllegalArgumentException if any data is in the highest order 8 + * bits + */ + public static Color fromBGR(int bgr) throws IllegalArgumentException { + Validate.isTrue((bgr >> 24) == 0, "Extrenuous data in: ", bgr); + return fromBGR(bgr >> 16 & BIT_MASK, bgr >> 8 & BIT_MASK, bgr >> 0 & BIT_MASK); + } + + private Color(int red, int green, int blue) { + Validate.isTrue(red >= 0 && red <= BIT_MASK, "Red is not between 0-255: ", red); + Validate.isTrue(green >= 0 && green <= BIT_MASK, "Green is not between 0-255: ", green); + Validate.isTrue(blue >= 0 && blue <= BIT_MASK, "Blue is not between 0-255: ", blue); + + this.red = (byte) red; + this.green = (byte) green; + this.blue = (byte) blue; + } + + /** + * Gets the red component + * + * @return red component, from 0 to 255 + */ + public int getRed() { + return BIT_MASK & red; + } + + /** + * Creates a new Color object with specified component + * + * @param red the red component, from 0 to 255 + * @return a new color object with the red component + */ + public Color setRed(int red) { + return fromRGB(red, getGreen(), getBlue()); + } + + /** + * Gets the green component + * + * @return green component, from 0 to 255 + */ + public int getGreen() { + return BIT_MASK & green; + } + + /** + * Creates a new Color object with specified component + * + * @param green the red component, from 0 to 255 + * @return a new color object with the red component + */ + public Color setGreen(int green) { + return fromRGB(getRed(), green, getBlue()); + } + + /** + * Gets the blue component + * + * @return blue component, from 0 to 255 + */ + public int getBlue() { + return BIT_MASK & blue; + } + + /** + * Creates a new Color object with specified component + * + * @param blue the red component, from 0 to 255 + * @return a new color object with the red component + */ + public Color setBlue(int blue) { + return fromRGB(getRed(), getGreen(), blue); + } + + /** + * + * @return An integer representation of this color, as 0xRRGGBB + */ + public int asRGB() { + return getRed() << 16 | getGreen() << 8 | getBlue() << 0; + } + + /** + * + * @return An integer representation of this color, as 0xBBGGRR + */ + public int asBGR() { + return getBlue() << 16 | getGreen() << 8 | getRed() << 0; + } + + /** + * Creates a new color with its RGB components changed as if it was dyed + * with the colors passed in, replicating vanilla workbench dyeing + * + * @param colors The DyeColors to dye with + * @return A new color with the changed rgb components + */ + // TODO: Javadoc what this method does, not what it mimics. API != Implementation + public Color mixDyes(DyeColor... colors) { + Validate.noNullElements(colors, "Colors cannot be null"); + + Color[] toPass = new Color[colors.length]; + for (int i = 0; i < colors.length; i++) { + toPass[i] = colors[i].getColor(); + } + + return mixColors(toPass); + } + + /** + * Creates a new color with its RGB components changed as if it was dyed + * with the colors passed in, replicating vanilla workbench dyeing + * + * @param colors The colors to dye with + * @return A new color with the changed rgb components + */ + // TODO: Javadoc what this method does, not what it mimics. API != Implementation + public Color mixColors(Color... colors) { + Validate.noNullElements(colors, "Colors cannot be null"); + + int totalRed = this.getRed(); + int totalGreen = this.getGreen(); + int totalBlue = this.getBlue(); + int totalMax = Math.max(Math.max(totalRed, totalGreen), totalBlue); + for (Color color : colors) { + totalRed += color.getRed(); + totalGreen += color.getGreen(); + totalBlue += color.getBlue(); + totalMax += Math.max(Math.max(color.getRed(), color.getGreen()), color.getBlue()); + } + + float averageRed = totalRed / (colors.length + 1); + float averageGreen = totalGreen / (colors.length + 1); + float averageBlue = totalBlue / (colors.length + 1); + float averageMax = totalMax / (colors.length + 1); + + float maximumOfAverages = Math.max(Math.max(averageRed, averageGreen), averageBlue); + float gainFactor = averageMax / maximumOfAverages; + + return Color.fromRGB((int) (averageRed * gainFactor), (int) (averageGreen * gainFactor), (int) (averageBlue * gainFactor)); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Color)) { + return false; + } + final Color that = (Color) o; + return this.blue == that.blue && this.green == that.green && this.red == that.red; + } + + @Override + public int hashCode() { + return asRGB() ^ Color.class.hashCode(); + } + + public Map serialize() { + return ImmutableMap.of( + "RED", getRed(), + "BLUE", getBlue(), + "GREEN", getGreen() + ); + } + + @SuppressWarnings("javadoc") + public static Color deserialize(Map map) { + return fromRGB( + asInt("RED", map), + asInt("GREEN", map), + asInt("BLUE", map) + ); + } + + private static int asInt(String string, Map map) { + Object value = map.get(string); + if (value == null) { + throw new IllegalArgumentException(string + " not in map " + map); + } + if (!(value instanceof Number)) { + throw new IllegalArgumentException(string + '(' + value + ") is not a number"); + } + return ((Number) value).intValue(); + } + + @Override + public String toString() { + return "Color:[rgb0x" + Integer.toHexString(getRed()).toUpperCase() + Integer.toHexString(getGreen()).toUpperCase() + Integer.toHexString(getBlue()).toUpperCase() + "]"; + } +} diff --git a/src/main/java/org/bukkit/CropState.java b/src/main/java/org/bukkit/CropState.java new file mode 100644 index 0000000..ef0faf9 --- /dev/null +++ b/src/main/java/org/bukkit/CropState.java @@ -0,0 +1,81 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +/** + * Represents the different growth states of crops + */ +public enum CropState { + + /** + * State when first seeded + */ + SEEDED(0x0), + /** + * First growth stage + */ + GERMINATED(0x1), + /** + * Second growth stage + */ + VERY_SMALL(0x2), + /** + * Third growth stage + */ + SMALL(0x3), + /** + * Fourth growth stage + */ + MEDIUM(0x4), + /** + * Fifth growth stage + */ + TALL(0x5), + /** + * Almost ripe stage + */ + VERY_TALL(0x6), + /** + * Ripe stage + */ + RIPE(0x7); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + private CropState(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this growth state + * + * @return A byte containing the data value of this growth state + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the CropState with the given data value + * + * @param data Data value to fetch + * @return The {@link CropState} representing the given value, or null if + * it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static CropState getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (CropState cropState : values()) { + BY_DATA.put(cropState.getData(), cropState); + } + } +} diff --git a/src/main/java/org/bukkit/Difficulty.java b/src/main/java/org/bukkit/Difficulty.java new file mode 100644 index 0000000..a8a5a78 --- /dev/null +++ b/src/main/java/org/bukkit/Difficulty.java @@ -0,0 +1,72 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +/** + * Represents the various difficulty levels that are available. + */ +public enum Difficulty { + /** + * Players regain health over time, hostile mobs don't spawn, the hunger + * bar does not deplete. + */ + PEACEFUL(0), + + /** + * Hostile mobs spawn, enemies deal less damage than on normal difficulty, + * the hunger bar does deplete and starving deals up to 5 hearts of + * damage. (Default value) + */ + EASY(1), + + /** + * Hostile mobs spawn, enemies deal normal amounts of damage, the hunger + * bar does deplete and starving deals up to 9.5 hearts of damage. + */ + NORMAL(2), + + /** + * Hostile mobs spawn, enemies deal greater damage than on normal + * difficulty, the hunger bar does deplete and starving can kill players. + */ + HARD(3); + + private final int value; + private final static Map BY_ID = Maps.newHashMap(); + + private Difficulty(final int value) { + this.value = value; + } + + /** + * Gets the difficulty value associated with this Difficulty. + * + * @return An integer value of this difficulty + * @deprecated Magic value + */ + @Deprecated + public int getValue() { + return value; + } + + /** + * Gets the Difficulty represented by the specified value + * + * @param value Value to check + * @return Associative {@link Difficulty} with the given value, or null if + * it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static Difficulty getByValue(final int value) { + return BY_ID.get(value); + } + + static { + for (Difficulty diff : values()) { + BY_ID.put(diff.value, diff); + } + } +} diff --git a/src/main/java/org/bukkit/DyeColor.java b/src/main/java/org/bukkit/DyeColor.java new file mode 100644 index 0000000..214806e --- /dev/null +++ b/src/main/java/org/bukkit/DyeColor.java @@ -0,0 +1,239 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.ImmutableMap; + +/** + * All supported color values for dyes and cloth + */ +public enum DyeColor { + + /** + * Represents white dye. + */ + WHITE(0x0, 0xF, Color.WHITE, Color.fromRGB(0xF0F0F0)), + /** + * Represents orange dye. + */ + ORANGE(0x1, 0xE, Color.fromRGB(0xD87F33), Color.fromRGB(0xEB8844)), + /** + * Represents magenta dye. + */ + MAGENTA(0x2, 0xD, Color.fromRGB(0xB24CD8), Color.fromRGB(0xC354CD)), + /** + * Represents light blue dye. + */ + LIGHT_BLUE(0x3, 0xC, Color.fromRGB(0x6699D8), Color.fromRGB(0x6689D3)), + /** + * Represents yellow dye. + */ + YELLOW(0x4, 0xB, Color.fromRGB(0xE5E533), Color.fromRGB(0xDECF2A)), + /** + * Represents lime dye. + */ + LIME(0x5, 0xA, Color.fromRGB(0x7FCC19), Color.fromRGB(0x41CD34)), + /** + * Represents pink dye. + */ + PINK(0x6, 0x9, Color.fromRGB(0xF27FA5), Color.fromRGB(0xD88198)), + /** + * Represents gray dye. + */ + GRAY(0x7, 0x8, Color.fromRGB(0x4C4C4C), Color.fromRGB(0x434343)), + /** + * Represents silver dye. + */ + SILVER(0x8, 0x7, Color.fromRGB(0x999999), Color.fromRGB(0xABABAB)), + /** + * Represents cyan dye. + */ + CYAN(0x9, 0x6, Color.fromRGB(0x4C7F99), Color.fromRGB(0x287697)), + /** + * Represents purple dye. + */ + PURPLE(0xA, 0x5, Color.fromRGB(0x7F3FB2), Color.fromRGB(0x7B2FBE)), + /** + * Represents blue dye. + */ + BLUE(0xB, 0x4, Color.fromRGB(0x334CB2), Color.fromRGB(0x253192)), + /** + * Represents brown dye. + */ + BROWN(0xC, 0x3, Color.fromRGB(0x664C33), Color.fromRGB(0x51301A)), + /** + * Represents green dye. + */ + GREEN(0xD, 0x2, Color.fromRGB(0x667F33), Color.fromRGB(0x3B511A)), + /** + * Represents red dye. + */ + RED(0xE, 0x1, Color.fromRGB(0x993333), Color.fromRGB(0xB3312C)), + /** + * Represents black dye. + */ + BLACK(0xF, 0x0, Color.fromRGB(0x191919), Color.fromRGB(0x1E1B1B)); + + private final byte woolData; + private final byte dyeData; + private final Color color; + private final Color firework; + private final static DyeColor[] BY_WOOL_DATA; + private final static DyeColor[] BY_DYE_DATA; + private final static Map BY_COLOR; + private final static Map BY_FIREWORK; + + private DyeColor(final int woolData, final int dyeData, Color color, Color firework) { + this.woolData = (byte) woolData; + this.dyeData = (byte) dyeData; + this.color = color; + this.firework = firework; + } + + /** + * Gets the associated (wool) data value representing this color. + * + * @return A byte containing the (wool) data value of this color + * @deprecated The name is misleading. It would imply {@link + * Material#INK_SACK} but uses {@link Material#WOOL} + * @see #getWoolData() + * @see #getDyeData() + */ + @Deprecated + public byte getData() { + return getWoolData(); + } + + /** + * Gets the associated wool data value representing this color. + * + * @return A byte containing the wool data value of this color + * @see #getDyeData() + * @deprecated Magic value + */ + @Deprecated + public byte getWoolData() { + return woolData; + } + + /** + * Gets the associated dye data value representing this color. + * + * @return A byte containing the dye data value of this color + * @see #getWoolData() + * @deprecated Magic value + */ + @Deprecated + public byte getDyeData() { + return dyeData; + } + + /** + * Gets the color that this dye represents. + * + * @return The {@link Color} that this dye represents + */ + public Color getColor() { + return color; + } + + /** + * Gets the firework color that this dye represents. + * + * @return The {@link Color} that this dye represents + */ + public Color getFireworkColor() { + return firework; + } + + /** + * Gets the DyeColor with the given (wool) data value. + * + * @param data (wool) data value to fetch + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + * @deprecated The name is misleading. It would imply {@link + * Material#INK_SACK} but uses {@link Material#WOOL} + * @see #getByDyeData(byte) + * @see #getByWoolData(byte) + */ + @Deprecated + public static DyeColor getByData(final byte data) { + return getByWoolData(data); + } + + /** + * Gets the DyeColor with the given wool data value. + * + * @param data Wool data value to fetch + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + * @see #getByDyeData(byte) + * @deprecated Magic value + */ + @Deprecated + public static DyeColor getByWoolData(final byte data) { + int i = 0xff & data; + if (i >= BY_WOOL_DATA.length) { + return null; + } + return BY_WOOL_DATA[i]; + } + + /** + * Gets the DyeColor with the given dye data value. + * + * @param data Dye data value to fetch + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + * @see #getByWoolData(byte) + * @deprecated Magic value + */ + @Deprecated + public static DyeColor getByDyeData(final byte data) { + int i = 0xff & data; + if (i >= BY_DYE_DATA.length) { + return null; + } + return BY_DYE_DATA[i]; + } + + /** + * Gets the DyeColor with the given color value. + * + * @param color Color value to get the dye by + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + */ + public static DyeColor getByColor(final Color color) { + return BY_COLOR.get(color); + } + + /** + * Gets the DyeColor with the given firework color value. + * + * @param color Color value to get dye by + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + */ + public static DyeColor getByFireworkColor(final Color color) { + return BY_FIREWORK.get(color); + } + + static { + BY_WOOL_DATA = values(); + BY_DYE_DATA = values(); + ImmutableMap.Builder byColor = ImmutableMap.builder(); + ImmutableMap.Builder byFirework = ImmutableMap.builder(); + + for (DyeColor color : values()) { + BY_WOOL_DATA[color.woolData & 0xff] = color; + BY_DYE_DATA[color.dyeData & 0xff] = color; + byColor.put(color.getColor(), color); + byFirework.put(color.getFireworkColor(), color); + } + + BY_COLOR = byColor.build(); + BY_FIREWORK = byFirework.build(); + } +} diff --git a/src/main/java/org/bukkit/Effect.java b/src/main/java/org/bukkit/Effect.java new file mode 100644 index 0000000..2474a2d --- /dev/null +++ b/src/main/java/org/bukkit/Effect.java @@ -0,0 +1,147 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +import org.bukkit.block.BlockFace; +import org.bukkit.potion.Potion; + +/** + * A list of effects that the server is able to send to players. + */ +public enum Effect { + /** + * An alternate click sound. + */ + CLICK2(1000, Type.SOUND), + /** + * A click sound. + */ + CLICK1(1001, Type.SOUND), + /** + * Sound of a bow firing. + */ + BOW_FIRE(1002, Type.SOUND), + /** + * Sound of a door opening/closing. + */ + DOOR_TOGGLE(1003, Type.SOUND), + /** + * Sound of fire being extinguished. + */ + EXTINGUISH(1004, Type.SOUND), + /** + * A song from a record. Needs the record item ID as additional info + */ + RECORD_PLAY(1005, Type.SOUND, Material.class), + /** + * Sound of ghast shrieking. + */ + GHAST_SHRIEK(1007, Type.SOUND), + /** + * Sound of ghast firing. + */ + GHAST_SHOOT(1008, Type.SOUND), + /** + * Sound of blaze firing. + */ + BLAZE_SHOOT(1009, Type.SOUND), + /** + * Sound of zombies chewing on wooden doors. + */ + ZOMBIE_CHEW_WOODEN_DOOR(1010, Type.SOUND), + /** + * Sound of zombies chewing on iron doors. + */ + ZOMBIE_CHEW_IRON_DOOR(1011, Type.SOUND), + /** + * Sound of zombies destroying a door. + */ + ZOMBIE_DESTROY_DOOR(1012, Type.SOUND), + /** + * A visual smoke effect. Needs direction as additional info. + */ + SMOKE(2000, Type.VISUAL, BlockFace.class), + /** + * Sound of a block breaking. Needs block ID as additional info. + */ + STEP_SOUND(2001, Type.SOUND, Material.class), + /** + * Visual effect of a splash potion breaking. Needs potion data value as + * additional info. + */ + POTION_BREAK(2002, Type.VISUAL, Potion.class), + /** + * An ender eye signal; a visual effect. + */ + ENDER_SIGNAL(2003, Type.VISUAL), + /** + * The flames seen on a mobspawner; a visual effect. + */ + MOBSPAWNER_FLAMES(2004, Type.VISUAL); + + private final int id; + private final Type type; + private final Class data; + private static final Map BY_ID = Maps.newHashMap(); + + Effect(int id, Type type) { + this(id,type,null); + } + + Effect(int id, Type type, Class data) { + this.id = id; + this.type = type; + this.data = data; + } + + /** + * Gets the ID for this effect. + * + * @return ID of this effect + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return this.id; + } + + /** + * @return The type of the effect. + */ + public Type getType() { + return this.type; + } + + /** + * @return The class which represents data for this effect, or null if + * none + */ + public Class getData() { + return this.data; + } + + /** + * Gets the Effect associated with the given ID. + * + * @param id ID of the Effect to return + * @return Effect with the given ID + * @deprecated Magic value + */ + @Deprecated + public static Effect getById(int id) { + return BY_ID.get(id); + } + + static { + for (Effect effect : values()) { + BY_ID.put(effect.id, effect); + } + } + + /** + * Represents the type of an effect. + */ + public enum Type {SOUND, VISUAL} +} diff --git a/src/main/java/org/bukkit/EntityEffect.java b/src/main/java/org/bukkit/EntityEffect.java new file mode 100644 index 0000000..ec7d1e3 --- /dev/null +++ b/src/main/java/org/bukkit/EntityEffect.java @@ -0,0 +1,136 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +/** + * A list of all Effects that can happen to entities. + */ +public enum EntityEffect { + + /** + * When mobs get hurt. + */ + HURT(2), + + /** + * When a mob dies. + *

+ * This will cause client-glitches! + */ + DEATH(3), + + /** + * The smoke when taming a wolf fails. + *

+ * Without client-mods this will be ignored if the entity is not a wolf. + */ + WOLF_SMOKE(6), + + /** + * The hearts when taming a wolf succeeds. + *

+ * Without client-mods this will be ignored if the entity is not a wolf. + */ + WOLF_HEARTS(7), + + /** + * When a wolf shakes (after being wet). + *

+ * Without client-mods this will be ignored if the entity is not a wolf. + */ + WOLF_SHAKE(8), + + /** + * When a sheep eats a LONG_GRASS block. + */ + SHEEP_EAT(10), + + /** + * When an Iron Golem gives a rose. + *

+ * This will not play an effect if the entity is not an iron golem. + */ + IRON_GOLEM_ROSE(11), + + /** + * Hearts from a villager. + *

+ * This will not play an effect if the entity is not a villager. + */ + VILLAGER_HEART(12), + + /** + * When a villager is angry. + *

+ * This will not play an effect if the entity is not a villager. + */ + VILLAGER_ANGRY(13), + + /** + * Happy particles from a villager. + *

+ * This will not play an effect if the entity is not a villager. + */ + VILLAGER_HAPPY(14), + + /** + * Magic particles from a witch. + *

+ * This will not play an effect if the entity is not a witch. + */ + WITCH_MAGIC(15), + + /** + * When a zombie transforms into a villager by shaking violently. + *

+ * This will not play an effect if the entity is not a zombie. + */ + ZOMBIE_TRANSFORM(16), + + /** + * When a firework explodes. + *

+ * This will not play an effect if the entity is not a firework. + */ + FIREWORK_EXPLODE(17); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + EntityEffect(final int data) { + this.data = (byte) data; + } + + /** + * Gets the data value of this EntityEffect + * + * @return The data value + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the EntityEffect with the given data value + * + * @param data Data value to fetch + * @return The {@link EntityEffect} representing the given value, or null + * if it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static EntityEffect getByData(final byte data) { + return BY_DATA.get(data); + } + + + static { + for (EntityEffect entityEffect : values()) { + BY_DATA.put(entityEffect.data, entityEffect); + } + } +} diff --git a/src/main/java/org/bukkit/FireworkEffect.java b/src/main/java/org/bukkit/FireworkEffect.java new file mode 100644 index 0000000..6f2d096 --- /dev/null +++ b/src/main/java/org/bukkit/FireworkEffect.java @@ -0,0 +1,421 @@ +package org.bukkit; + +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +/** + * Represents a single firework effect. + */ +@SerializableAs("Firework") +public final class FireworkEffect implements ConfigurationSerializable { + + /** + * The type or shape of the effect. + */ + public enum Type { + /** + * A small ball effect. + */ + BALL, + /** + * A large ball effect. + */ + BALL_LARGE, + /** + * A star-shaped effect. + */ + STAR, + /** + * A burst effect. + */ + BURST, + /** + * A creeper-face effect. + */ + CREEPER, + ; + } + + /** + * Construct a firework effect. + * + * @return A utility object for building a firework effect + */ + public static Builder builder() { + return new Builder(); + } + + /** + * This is a builder for FireworkEffects. + * + * @see FireworkEffect#builder() + */ + public static final class Builder { + boolean flicker = false; + boolean trail = false; + final ImmutableList.Builder colors = ImmutableList.builder(); + ImmutableList.Builder fadeColors = null; + Type type = Type.BALL; + + Builder() {} + + /** + * Specify the type of the firework effect. + * + * @param type The effect type + * @return This object, for chaining + * @throws IllegalArgumentException If type is null + */ + public Builder with(Type type) throws IllegalArgumentException { + Validate.notNull(type, "Cannot have null type"); + this.type = type; + return this; + } + + /** + * Add a flicker to the firework effect. + * + * @return This object, for chaining + */ + public Builder withFlicker() { + flicker = true; + return this; + } + + /** + * Set whether the firework effect should flicker. + * + * @param flicker true if it should flicker, false if not + * @return This object, for chaining + */ + public Builder flicker(boolean flicker) { + this.flicker = flicker; + return this; + } + + /** + * Add a trail to the firework effect. + * + * @return This object, for chaining + */ + public Builder withTrail() { + trail = true; + return this; + } + + /** + * Set whether the firework effect should have a trail. + * + * @param trail true if it should have a trail, false for no trail + * @return This object, for chaining + */ + public Builder trail(boolean trail) { + this.trail = trail; + return this; + } + + /** + * Add a primary color to the firework effect. + * + * @param color The color to add + * @return This object, for chaining + * @throws IllegalArgumentException If color is null + */ + public Builder withColor(Color color) throws IllegalArgumentException { + Validate.notNull(color, "Cannot have null color"); + + colors.add(color); + + return this; + } + + /** + * Add several primary colors to the firework effect. + * + * @param colors The colors to add + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withColor(Color...colors) throws IllegalArgumentException { + Validate.notNull(colors, "Cannot have null colors"); + if (colors.length == 0) { + return this; + } + + ImmutableList.Builder list = this.colors; + for (Color color : colors) { + Validate.notNull(color, "Color cannot be null"); + list.add(color); + } + + return this; + } + + /** + * Add several primary colors to the firework effect. + * + * @param colors An iterable object whose iterator yields the desired + * colors + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withColor(Iterable colors) throws IllegalArgumentException { + Validate.notNull(colors, "Cannot have null colors"); + + ImmutableList.Builder list = this.colors; + for (Object color : colors) { + if (!(color instanceof Color)) { + throw new IllegalArgumentException(color + " is not a Color in " + colors); + } + list.add((Color) color); + } + + return this; + } + + /** + * Add a fade color to the firework effect. + * + * @param color The color to add + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withFade(Color color) throws IllegalArgumentException { + Validate.notNull(color, "Cannot have null color"); + + if (fadeColors == null) { + fadeColors = ImmutableList.builder(); + } + + fadeColors.add(color); + + return this; + } + + /** + * Add several fade colors to the firework effect. + * + * @param colors The colors to add + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withFade(Color...colors) throws IllegalArgumentException { + Validate.notNull(colors, "Cannot have null colors"); + if (colors.length == 0) { + return this; + } + + ImmutableList.Builder list = this.fadeColors; + if (list == null) { + list = this.fadeColors = ImmutableList.builder(); + } + + for (Color color : colors) { + Validate.notNull(color, "Color cannot be null"); + list.add(color); + } + + return this; + } + + /** + * Add several fade colors to the firework effect. + * + * @param colors An iterable object whose iterator yields the desired + * colors + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withFade(Iterable colors) throws IllegalArgumentException { + Validate.notNull(colors, "Cannot have null colors"); + + ImmutableList.Builder list = this.fadeColors; + if (list == null) { + list = this.fadeColors = ImmutableList.builder(); + } + + for (Object color : colors) { + if (!(color instanceof Color)) { + throw new IllegalArgumentException(color + " is not a Color in " + colors); + } + list.add((Color) color); + } + + return this; + } + + /** + * Create a {@link FireworkEffect} from the current contents of this + * builder. + *

+ * To successfully build, you must have specified at least one color. + * + * @return The representative firework effect + */ + public FireworkEffect build() { + return new FireworkEffect( + flicker, + trail, + colors.build(), + fadeColors == null ? ImmutableList.of() : fadeColors.build(), + type + ); + } + } + + private static final String FLICKER = "flicker"; + private static final String TRAIL = "trail"; + private static final String COLORS = "colors"; + private static final String FADE_COLORS = "fade-colors"; + private static final String TYPE = "type"; + + private final boolean flicker; + private final boolean trail; + private final ImmutableList colors; + private final ImmutableList fadeColors; + private final Type type; + private String string = null; + + FireworkEffect(boolean flicker, boolean trail, ImmutableList colors, ImmutableList fadeColors, Type type) { + if (colors.isEmpty()) { + throw new IllegalStateException("Cannot make FireworkEffect without any color"); + } + this.flicker = flicker; + this.trail = trail; + this.colors = colors; + this.fadeColors = fadeColors; + this.type = type; + } + + /** + * Get whether the firework effect flickers. + * + * @return true if it flickers, false if not + */ + public boolean hasFlicker() { + return flicker; + } + + /** + * Get whether the firework effect has a trail. + * + * @return true if it has a trail, false if not + */ + public boolean hasTrail() { + return trail; + } + + /** + * Get the primary colors of the firework effect. + * + * @return An immutable list of the primary colors + */ + public List getColors() { + return colors; + } + + /** + * Get the fade colors of the firework effect. + * + * @return An immutable list of the fade colors + */ + public List getFadeColors() { + return fadeColors; + } + + /** + * Get the type of the firework effect. + * + * @return The effect type + */ + public Type getType() { + return type; + } + + /** + * @see ConfigurationSerializable + */ + public static ConfigurationSerializable deserialize(Map map) { + Type type = Type.valueOf((String) map.get(TYPE)); + if (type == null) { + throw new IllegalArgumentException(map.get(TYPE) + " is not a valid Type"); + } + + return builder() + .flicker((Boolean) map.get(FLICKER)) + .trail((Boolean) map.get(TRAIL)) + .withColor((Iterable) map.get(COLORS)) + .withFade((Iterable) map.get(FADE_COLORS)) + .with(type) + .build(); + } + + public Map serialize() { + return ImmutableMap.of( + FLICKER, flicker, + TRAIL, trail, + COLORS, colors, + FADE_COLORS, fadeColors, + TYPE, type.name() + ); + } + + @Override + public String toString() { + final String string = this.string; + if (string == null) { + return this.string = "FireworkEffect:" + serialize(); + } + return string; + } + + @Override + public int hashCode() { + /** + * TRUE and FALSE as per boolean.hashCode() + */ + final int PRIME = 31, TRUE = 1231, FALSE = 1237; + int hash = 1; + hash = hash * PRIME + (flicker ? TRUE : FALSE); + hash = hash * PRIME + (trail ? TRUE : FALSE); + hash = hash * PRIME + type.hashCode(); + hash = hash * PRIME + colors.hashCode(); + hash = hash * PRIME + fadeColors.hashCode(); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (!(obj instanceof FireworkEffect)) { + return false; + } + + FireworkEffect that = (FireworkEffect) obj; + return this.flicker == that.flicker + && this.trail == that.trail + && this.type == that.type + && this.colors.equals(that.colors) + && this.fadeColors.equals(that.fadeColors); + } +} diff --git a/src/main/java/org/bukkit/GameMode.java b/src/main/java/org/bukkit/GameMode.java new file mode 100644 index 0000000..47b2d90 --- /dev/null +++ b/src/main/java/org/bukkit/GameMode.java @@ -0,0 +1,66 @@ +package org.bukkit; + +import java.util.Map; + +import org.bukkit.entity.HumanEntity; + +import com.google.common.collect.Maps; + +/** + * Represents the various type of game modes that {@link HumanEntity}s may + * have + */ +public enum GameMode { + /** + * Creative mode may fly, build instantly, become invulnerable and create + * free items. + */ + CREATIVE(1), + + /** + * Survival mode is the "normal" gameplay type, with no special features. + */ + SURVIVAL(0), + + /** + * Adventure mode cannot break blocks, use chat, use buckets, etc. + */ + ADVENTURE(2); + + private final int value; + private final static Map BY_ID = Maps.newHashMap(); + + private GameMode(final int value) { + this.value = value; + } + + /** + * Gets the mode value associated with this GameMode + * + * @return An integer value of this gamemode + * @deprecated Magic value + */ + @Deprecated + public int getValue() { + return value; + } + + /** + * Gets the GameMode represented by the specified value + * + * @param value Value to check + * @return Associative {@link GameMode} with the given value, or null if + * it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static GameMode getByValue(final int value) { + return BY_ID.get(value); + } + + static { + for (GameMode mode : values()) { + BY_ID.put(mode.getValue(), mode); + } + } +} diff --git a/src/main/java/org/bukkit/GrassSpecies.java b/src/main/java/org/bukkit/GrassSpecies.java new file mode 100644 index 0000000..1111515 --- /dev/null +++ b/src/main/java/org/bukkit/GrassSpecies.java @@ -0,0 +1,61 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +/** + * Represents the different types of grass. + */ +public enum GrassSpecies { + + /** + * Represents the dead looking grass. + */ + DEAD(0x0), + /** + * Represents the normal grass species. + */ + NORMAL(0x1), + /** + * Represents the fern-looking grass species. + */ + FERN_LIKE(0x2); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + private GrassSpecies(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this species + * + * @return A byte containing the data value of this grass species + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the GrassSpecies with the given data value + * + * @param data Data value to fetch + * @return The {@link GrassSpecies} representing the given value, or null + * if it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static GrassSpecies getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (GrassSpecies grassSpecies : values()) { + BY_DATA.put(grassSpecies.getData(), grassSpecies); + } + } +} diff --git a/src/main/java/org/bukkit/Instrument.java b/src/main/java/org/bukkit/Instrument.java new file mode 100644 index 0000000..891a2b1 --- /dev/null +++ b/src/main/java/org/bukkit/Instrument.java @@ -0,0 +1,67 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +public enum Instrument { + + /** + * Piano is the standard instrument for a note block. + */ + PIANO(0x0), + /** + * Bass drum is normally played when a note block is on top of a + * stone-like block + */ + BASS_DRUM(0x1), + /** + * Snare drum is normally played when a note block is on top of a sandy + * block. + */ + SNARE_DRUM(0x2), + /** + * Sticks are normally played when a note block is on top of a glass + * block. + */ + STICKS(0x3), + /** + * Bass guitar is normally played when a note block is on top of a wooden + * block. + */ + BASS_GUITAR(0x4); + + private final byte type; + private final static Map BY_DATA = Maps.newHashMap(); + + private Instrument(final int type) { + this.type = (byte) type; + } + + /** + * @return The type ID of this instrument. + * @deprecated Magic value + */ + @Deprecated + public byte getType() { + return this.type; + } + + /** + * Get an instrument by its type ID. + * + * @param type The type ID + * @return The instrument + * @deprecated Magic value + */ + @Deprecated + public static Instrument getByType(final byte type) { + return BY_DATA.get(type); + } + + static { + for (Instrument instrument : Instrument.values()) { + BY_DATA.put(instrument.getType(), instrument); + } + } +} diff --git a/src/main/java/org/bukkit/Location.java b/src/main/java/org/bukkit/Location.java new file mode 100644 index 0000000..9e1e604 --- /dev/null +++ b/src/main/java/org/bukkit/Location.java @@ -0,0 +1,560 @@ +package org.bukkit; + +import org.bukkit.block.Block; +import org.bukkit.util.NumberConversions; +import org.bukkit.util.Vector; + +/** + * Represents a 3-dimensional position in a world + */ +public class Location implements Cloneable { + private World world; + private double x; + private double y; + private double z; + private float pitch; + private float yaw; + + /** + * Constructs a new Location with the given coordinates + * + * @param world The world in which this location resides + * @param x The x-coordinate of this new location + * @param y The y-coordinate of this new location + * @param z The z-coordinate of this new location + */ + public Location(final World world, final double x, final double y, final double z) { + this(world, x, y, z, 0, 0); + } + + /** + * Constructs a new Location with the given coordinates and direction + * + * @param world The world in which this location resides + * @param x The x-coordinate of this new location + * @param y The y-coordinate of this new location + * @param z The z-coordinate of this new location + * @param yaw The absolute rotation on the x-plane, in degrees + * @param pitch The absolute rotation on the y-plane, in degrees + */ + public Location(final World world, final double x, final double y, final double z, final float yaw, final float pitch) { + this.world = world; + this.x = x; + this.y = y; + this.z = z; + this.pitch = pitch; + this.yaw = yaw; + } + + /** + * Sets the world that this location resides in + * + * @param world New world that this location resides in + */ + public void setWorld(World world) { + this.world = world; + } + + /** + * Gets the world that this location resides in + * + * @return World that contains this location + */ + public World getWorld() { + return world; + } + + /** + * Gets the chunk at the represented location + * + * @return Chunk at the represented location + */ + public Chunk getChunk() { + return world.getChunkAt(this); + } + + /** + * Gets the block at the represented location + * + * @return Block at the represented location + */ + public Block getBlock() { + return world.getBlockAt(this); + } + + /** + * Sets the x-coordinate of this location + * + * @param x X-coordinate + */ + public void setX(double x) { + this.x = x; + } + + /** + * Gets the x-coordinate of this location + * + * @return x-coordinate + */ + public double getX() { + return x; + } + + /** + * Gets the floored value of the X component, indicating the block that + * this location is contained with. + * + * @return block X + */ + public int getBlockX() { + return locToBlock(x); + } + + /** + * Sets the y-coordinate of this location + * + * @param y y-coordinate + */ + public void setY(double y) { + this.y = y; + } + + /** + * Gets the y-coordinate of this location + * + * @return y-coordinate + */ + public double getY() { + return y; + } + + /** + * Gets the floored value of the Y component, indicating the block that + * this location is contained with. + * + * @return block y + */ + public int getBlockY() { + return locToBlock(y); + } + + /** + * Sets the z-coordinate of this location + * + * @param z z-coordinate + */ + public void setZ(double z) { + this.z = z; + } + + /** + * Gets the z-coordinate of this location + * + * @return z-coordinate + */ + public double getZ() { + return z; + } + + /** + * Gets the floored value of the Z component, indicating the block that + * this location is contained with. + * + * @return block z + */ + public int getBlockZ() { + return locToBlock(z); + } + + /** + * Sets the yaw of this location, measured in degrees. + *

    + *
  • A yaw of 0 or 360 represents the positive z direction. + *
  • A yaw of 180 represents the negative z direction. + *
  • A yaw of 90 represents the negative x direction. + *
  • A yaw of 270 represents the positive x direction. + *
+ * Increasing yaw values are the equivalent of turning to your + * right-facing, increasing the scale of the next respective axis, and + * decreasing the scale of the previous axis. + * + * @param yaw new rotation's yaw + */ + public void setYaw(float yaw) { + this.yaw = yaw; + } + + /** + * Gets the yaw of this location, measured in degrees. + *
    + *
  • A yaw of 0 or 360 represents the positive z direction. + *
  • A yaw of 180 represents the negative z direction. + *
  • A yaw of 90 represents the negative x direction. + *
  • A yaw of 270 represents the positive x direction. + *
+ * Increasing yaw values are the equivalent of turning to your + * right-facing, increasing the scale of the next respective axis, and + * decreasing the scale of the previous axis. + * + * @return the rotation's yaw + */ + public float getYaw() { + return yaw; + } + + /** + * Sets the pitch of this location, measured in degrees. + *
    + *
  • A pitch of 0 represents level forward facing. + *
  • A pitch of 90 represents downward facing, or negative y + * direction. + *
  • A pitch of -90 represents upward facing, or positive y direction. + *
      + * Increasing pitch values the equivalent of looking down. + * + * @param pitch new incline's pitch + */ + public void setPitch(float pitch) { + this.pitch = pitch; + } + + /** + * Sets the pitch of this location, measured in degrees. + *
        + *
      • A pitch of 0 represents level forward facing. + *
      • A pitch of 90 represents downward facing, or negative y + * direction. + *
      • A pitch of -90 represents upward facing, or positive y direction. + *
          + * Increasing pitch values the equivalent of looking down. + * + * @return the incline's pitch + */ + public float getPitch() { + return pitch; + } + + /** + * Gets a unit-vector pointing in the direction that this Location is + * facing. + * + * @return a vector pointing the direction of this location's {@link + * #getPitch() pitch} and {@link #getYaw() yaw} + */ + public Vector getDirection() { + Vector vector = new Vector(); + + double rotX = this.getYaw(); + double rotY = this.getPitch(); + + vector.setY(-Math.sin(Math.toRadians(rotY))); + + double xz = Math.cos(Math.toRadians(rotY)); + + vector.setX(-xz * Math.sin(Math.toRadians(rotX))); + vector.setZ(xz * Math.cos(Math.toRadians(rotX))); + + return vector; + } + + /** + * Sets the {@link #getYaw() yaw} and {@link #getPitch() pitch} to point + * in the direction of the vector. + */ + public Location setDirection(Vector vector) { + /* + * Sin = Opp / Hyp + * Cos = Adj / Hyp + * Tan = Opp / Adj + * + * x = -Opp + * z = Adj + */ + final double _2PI = 2 * Math.PI; + final double x = vector.getX(); + final double z = vector.getZ(); + + if (x == 0 && z == 0) { + pitch = vector.getY() > 0 ? -90 : 90; + return this; + } + + double theta = Math.atan2(-x, z); + yaw = (float) Math.toDegrees((theta + _2PI) % _2PI); + + double x2 = NumberConversions.square(x); + double z2 = NumberConversions.square(z); + double xz = Math.sqrt(x2 + z2); + pitch = (float) Math.toDegrees(Math.atan(-vector.getY() / xz)); + + return this; + } + + /** + * Adds the location by another. + * + * @see Vector + * @param vec The other location + * @return the same location + * @throws IllegalArgumentException for differing worlds + */ + public Location add(Location vec) { + if (vec == null || vec.getWorld() != getWorld()) { + throw new IllegalArgumentException("Cannot add Locations of differing worlds"); + } + + x += vec.x; + y += vec.y; + z += vec.z; + return this; + } + + /** + * Adds the location by a vector. + * + * @see Vector + * @param vec Vector to use + * @return the same location + */ + public Location add(Vector vec) { + this.x += vec.getX(); + this.y += vec.getY(); + this.z += vec.getZ(); + return this; + } + + /** + * Adds the location by another. Not world-aware. + * + * @see Vector + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return the same location + */ + public Location add(double x, double y, double z) { + this.x += x; + this.y += y; + this.z += z; + return this; + } + + /** + * Subtracts the location by another. + * + * @see Vector + * @param vec The other location + * @return the same location + * @throws IllegalArgumentException for differing worlds + */ + public Location subtract(Location vec) { + if (vec == null || vec.getWorld() != getWorld()) { + throw new IllegalArgumentException("Cannot add Locations of differing worlds"); + } + + x -= vec.x; + y -= vec.y; + z -= vec.z; + return this; + } + + /** + * Subtracts the location by a vector. + * + * @see Vector + * @param vec The vector to use + * @return the same location + */ + public Location subtract(Vector vec) { + this.x -= vec.getX(); + this.y -= vec.getY(); + this.z -= vec.getZ(); + return this; + } + + /** + * Subtracts the location by another. Not world-aware and + * orientation independent. + * + * @see Vector + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return the same location + */ + public Location subtract(double x, double y, double z) { + this.x -= x; + this.y -= y; + this.z -= z; + return this; + } + + /** + * Gets the magnitude of the location, defined as sqrt(x^2+y^2+z^2). The + * value of this method is not cached and uses a costly square-root + * function, so do not repeatedly call this method to get the location's + * magnitude. NaN will be returned if the inner result of the sqrt() + * function overflows, which will be caused if the length is too long. Not + * world-aware and orientation independent. + * + * @see Vector + * @return the magnitude + */ + public double length() { + return Math.sqrt(NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z)); + } + + /** + * Gets the magnitude of the location squared. Not world-aware and + * orientation independent. + * + * @see Vector + * @return the magnitude + */ + public double lengthSquared() { + return NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z); + } + + /** + * Get the distance between this location and another. The value of this + * method is not cached and uses a costly square-root function, so do not + * repeatedly call this method to get the location's magnitude. NaN will + * be returned if the inner result of the sqrt() function overflows, which + * will be caused if the distance is too long. + * + * @see Vector + * @param o The other location + * @return the distance + * @throws IllegalArgumentException for differing worlds + */ + public double distance(Location o) { + return Math.sqrt(distanceSquared(o)); + } + + /** + * Get the squared distance between this location and another. + * + * @see Vector + * @param o The other location + * @return the distance + * @throws IllegalArgumentException for differing worlds + */ + public double distanceSquared(Location o) { + if (o == null) { + throw new IllegalArgumentException("Cannot measure distance to a null location"); + } else if (o.getWorld() == null || getWorld() == null) { + throw new IllegalArgumentException("Cannot measure distance to a null world"); + } else if (o.getWorld() != getWorld()) { + throw new IllegalArgumentException("Cannot measure distance between " + getWorld().getName() + " and " + o.getWorld().getName()); + } + + return NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z); + } + + /** + * Performs scalar multiplication, multiplying all components with a + * scalar. Not world-aware. + * + * @param m The factor + * @see Vector + * @return the same location + */ + public Location multiply(double m) { + x *= m; + y *= m; + z *= m; + return this; + } + + /** + * Zero this location's components. Not world-aware. + * + * @see Vector + * @return the same location + */ + public Location zero() { + x = 0; + y = 0; + z = 0; + return this; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Location other = (Location) obj; + + if (this.world != other.world && (this.world == null || !this.world.equals(other.world))) { + return false; + } + if (Double.doubleToLongBits(this.x) != Double.doubleToLongBits(other.x)) { + return false; + } + if (Double.doubleToLongBits(this.y) != Double.doubleToLongBits(other.y)) { + return false; + } + if (Double.doubleToLongBits(this.z) != Double.doubleToLongBits(other.z)) { + return false; + } + if (Float.floatToIntBits(this.pitch) != Float.floatToIntBits(other.pitch)) { + return false; + } + if (Float.floatToIntBits(this.yaw) != Float.floatToIntBits(other.yaw)) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 3; + + hash = 19 * hash + (this.world != null ? this.world.hashCode() : 0); + hash = 19 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32)); + hash = 19 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32)); + hash = 19 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32)); + hash = 19 * hash + Float.floatToIntBits(this.pitch); + hash = 19 * hash + Float.floatToIntBits(this.yaw); + return hash; + } + + @Override + public String toString() { + return "Location{" + "world=" + world + ",x=" + x + ",y=" + y + ",z=" + z + ",pitch=" + pitch + ",yaw=" + yaw + '}'; + } + + /** + * Constructs a new {@link Vector} based on this Location + * + * @return New Vector containing the coordinates represented by this + * Location + */ + public Vector toVector() { + return new Vector(x, y, z); + } + + @Override + public Location clone() { + try { + return (Location) super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } + + /** + * Safely converts a double (location coordinate) to an int (block + * coordinate) + * + * @param loc Precise coordinate + * @return Block coordinate + */ + public static int locToBlock(double loc) { + return NumberConversions.floor(loc); + } +} diff --git a/src/main/java/org/bukkit/Material.java b/src/main/java/org/bukkit/Material.java new file mode 100644 index 0000000..c45c180 --- /dev/null +++ b/src/main/java/org/bukkit/Material.java @@ -0,0 +1,1034 @@ +package org.bukkit; + +import java.lang.reflect.Constructor; +import java.util.Map; + +import org.apache.commons.lang.Validate; +import org.bukkit.map.MapView; +import org.bukkit.material.Bed; +import org.bukkit.material.Button; +import org.bukkit.material.Cake; +import org.bukkit.material.Cauldron; +import org.bukkit.material.Chest; +import org.bukkit.material.Coal; +import org.bukkit.material.CocoaPlant; +import org.bukkit.material.Command; +import org.bukkit.material.Crops; +import org.bukkit.material.DetectorRail; +import org.bukkit.material.Diode; +import org.bukkit.material.Dispenser; +import org.bukkit.material.Door; +import org.bukkit.material.Dye; +import org.bukkit.material.EnderChest; +import org.bukkit.material.FlowerPot; +import org.bukkit.material.Furnace; +import org.bukkit.material.Gate; +import org.bukkit.material.Ladder; +import org.bukkit.material.Lever; +import org.bukkit.material.LongGrass; +import org.bukkit.material.MaterialData; +import org.bukkit.material.MonsterEggs; +import org.bukkit.material.Mushroom; +import org.bukkit.material.NetherWarts; +import org.bukkit.material.PistonBaseMaterial; +import org.bukkit.material.PistonExtensionMaterial; +import org.bukkit.material.PoweredRail; +import org.bukkit.material.PressurePlate; +import org.bukkit.material.Pumpkin; +import org.bukkit.material.Rails; +import org.bukkit.material.RedstoneTorch; +import org.bukkit.material.RedstoneWire; +import org.bukkit.material.Sandstone; +import org.bukkit.material.Sign; +import org.bukkit.material.Skull; +import org.bukkit.material.SmoothBrick; +import org.bukkit.material.SpawnEgg; +import org.bukkit.material.Stairs; +import org.bukkit.material.Step; +import org.bukkit.material.Torch; +import org.bukkit.material.TrapDoor; +import org.bukkit.material.Tree; +import org.bukkit.material.Tripwire; +import org.bukkit.material.TripwireHook; +import org.bukkit.material.Vine; +import org.bukkit.material.WoodenStep; +import org.bukkit.material.Wool; +import org.bukkit.potion.Potion; +import org.bukkit.util.Java15Compat; + +import com.google.common.collect.Maps; + +/** + * An enum of all material IDs accepted by the official server and client + */ +public enum Material { + AIR(0, 0), + STONE(1), + GRASS(2), + DIRT(3), + COBBLESTONE(4), + WOOD(5, Tree.class), + SAPLING(6, Tree.class), + BEDROCK(7), + WATER(8, MaterialData.class), + STATIONARY_WATER(9, MaterialData.class), + LAVA(10, MaterialData.class), + STATIONARY_LAVA(11, MaterialData.class), + SAND(12), + GRAVEL(13), + GOLD_ORE(14), + IRON_ORE(15), + COAL_ORE(16), + LOG(17, Tree.class), + LEAVES(18, Tree.class), + SPONGE(19), + GLASS(20), + LAPIS_ORE(21), + LAPIS_BLOCK(22), + DISPENSER(23, Dispenser.class), + SANDSTONE(24, Sandstone.class), + NOTE_BLOCK(25), + BED_BLOCK(26, Bed.class), + POWERED_RAIL(27, PoweredRail.class), + DETECTOR_RAIL(28, DetectorRail.class), + PISTON_STICKY_BASE(29, PistonBaseMaterial.class), + WEB(30), + LONG_GRASS(31, LongGrass.class), + DEAD_BUSH(32), + PISTON_BASE(33, PistonBaseMaterial.class), + PISTON_EXTENSION(34, PistonExtensionMaterial.class), + WOOL(35, Wool.class), + PISTON_MOVING_PIECE(36), + YELLOW_FLOWER(37), + RED_ROSE(38), + BROWN_MUSHROOM(39), + RED_MUSHROOM(40), + GOLD_BLOCK(41), + IRON_BLOCK(42), + DOUBLE_STEP(43, Step.class), + STEP(44, Step.class), + BRICK(45), + TNT(46), + BOOKSHELF(47), + MOSSY_COBBLESTONE(48), + OBSIDIAN(49), + TORCH(50, Torch.class), + FIRE(51), + MOB_SPAWNER(52), + WOOD_STAIRS(53, Stairs.class), + CHEST(54, Chest.class), + REDSTONE_WIRE(55, RedstoneWire.class), + DIAMOND_ORE(56), + DIAMOND_BLOCK(57), + WORKBENCH(58), + CROPS(59, Crops.class), + SOIL(60, MaterialData.class), + FURNACE(61, Furnace.class), + BURNING_FURNACE(62, Furnace.class), + SIGN_POST(63, 64, Sign.class), + WOODEN_DOOR(64, Door.class), + LADDER(65, Ladder.class), + RAILS(66, Rails.class), + COBBLESTONE_STAIRS(67, Stairs.class), + WALL_SIGN(68, 64, Sign.class), + LEVER(69, Lever.class), + STONE_PLATE(70, PressurePlate.class), + IRON_DOOR_BLOCK(71, Door.class), + WOOD_PLATE(72, PressurePlate.class), + REDSTONE_ORE(73), + GLOWING_REDSTONE_ORE(74), + REDSTONE_TORCH_OFF(75, RedstoneTorch.class), + REDSTONE_TORCH_ON(76, RedstoneTorch.class), + STONE_BUTTON(77, Button.class), + SNOW(78), + ICE(79), + SNOW_BLOCK(80), + CACTUS(81, MaterialData.class), + CLAY(82), + SUGAR_CANE_BLOCK(83, MaterialData.class), + JUKEBOX(84), + FENCE(85), + PUMPKIN(86, Pumpkin.class), + NETHERRACK(87), + SOUL_SAND(88), + GLOWSTONE(89), + PORTAL(90), + JACK_O_LANTERN(91, Pumpkin.class), + CAKE_BLOCK(92, 64, Cake.class), + DIODE_BLOCK_OFF(93, Diode.class), + DIODE_BLOCK_ON(94, Diode.class), + @Deprecated + LOCKED_CHEST(95), + STAINED_GLASS(95), + TRAP_DOOR(96, TrapDoor.class), + MONSTER_EGGS(97, MonsterEggs.class), + SMOOTH_BRICK(98, SmoothBrick.class), + HUGE_MUSHROOM_1(99, Mushroom.class), + HUGE_MUSHROOM_2(100, Mushroom.class), + IRON_FENCE(101), + THIN_GLASS(102), + MELON_BLOCK(103), + PUMPKIN_STEM(104, MaterialData.class), + MELON_STEM(105, MaterialData.class), + VINE(106, Vine.class), + FENCE_GATE(107, Gate.class), + BRICK_STAIRS(108, Stairs.class), + SMOOTH_STAIRS(109, Stairs.class), + MYCEL(110), + WATER_LILY(111), + NETHER_BRICK(112), + NETHER_FENCE(113), + NETHER_BRICK_STAIRS(114, Stairs.class), + NETHER_WARTS(115, NetherWarts.class), + ENCHANTMENT_TABLE(116), + BREWING_STAND(117, MaterialData.class), + CAULDRON(118, Cauldron.class), + ENDER_PORTAL(119), + ENDER_PORTAL_FRAME(120), + ENDER_STONE(121), + DRAGON_EGG(122), + REDSTONE_LAMP_OFF(123), + REDSTONE_LAMP_ON(124), + WOOD_DOUBLE_STEP(125, WoodenStep.class), + WOOD_STEP(126, WoodenStep.class), + COCOA(127, CocoaPlant.class), + SANDSTONE_STAIRS(128, Stairs.class), + EMERALD_ORE(129), + ENDER_CHEST(130, EnderChest.class), + TRIPWIRE_HOOK(131, TripwireHook.class), + TRIPWIRE(132, Tripwire.class), + EMERALD_BLOCK(133), + SPRUCE_WOOD_STAIRS(134, Stairs.class), + BIRCH_WOOD_STAIRS(135, Stairs.class), + JUNGLE_WOOD_STAIRS(136, Stairs.class), + COMMAND(137, Command.class), + BEACON(138), + COBBLE_WALL(139), + FLOWER_POT(140, FlowerPot.class), + CARROT(141), + POTATO(142), + WOOD_BUTTON(143, Button.class), + SKULL(144, Skull.class), + ANVIL(145), + TRAPPED_CHEST(146), + GOLD_PLATE(147), + IRON_PLATE(148), + REDSTONE_COMPARATOR_OFF(149), + REDSTONE_COMPARATOR_ON(150), + DAYLIGHT_DETECTOR(151), + REDSTONE_BLOCK(152), + QUARTZ_ORE(153), + HOPPER(154), + QUARTZ_BLOCK(155), + QUARTZ_STAIRS(156, Stairs.class), + ACTIVATOR_RAIL(157, PoweredRail.class), + DROPPER(158, Dispenser.class), + STAINED_CLAY(159), + STAINED_GLASS_PANE(160), + LEAVES_2(161), + LOG_2(162), + ACACIA_STAIRS(163, Stairs.class), + DARK_OAK_STAIRS(164, Stairs.class), + HAY_BLOCK(170), + CARPET(171), + HARD_CLAY(172), + COAL_BLOCK(173), + PACKED_ICE(174), + DOUBLE_PLANT(175), + // ----- Item Separator ----- + IRON_SPADE(256, 1, 250), + IRON_PICKAXE(257, 1, 250), + IRON_AXE(258, 1, 250), + FLINT_AND_STEEL(259, 1, 64), + APPLE(260), + BOW(261, 1, 384), + ARROW(262), + COAL(263, Coal.class), + DIAMOND(264), + IRON_INGOT(265), + GOLD_INGOT(266), + IRON_SWORD(267, 1, 250), + WOOD_SWORD(268, 1, 59), + WOOD_SPADE(269, 1, 59), + WOOD_PICKAXE(270, 1, 59), + WOOD_AXE(271, 1, 59), + STONE_SWORD(272, 1, 131), + STONE_SPADE(273, 1, 131), + STONE_PICKAXE(274, 1, 131), + STONE_AXE(275, 1, 131), + DIAMOND_SWORD(276, 1, 1561), + DIAMOND_SPADE(277, 1, 1561), + DIAMOND_PICKAXE(278, 1, 1561), + DIAMOND_AXE(279, 1, 1561), + STICK(280), + BOWL(281), + MUSHROOM_SOUP(282, 1), + GOLD_SWORD(283, 1, 32), + GOLD_SPADE(284, 1, 32), + GOLD_PICKAXE(285, 1, 32), + GOLD_AXE(286, 1, 32), + STRING(287), + FEATHER(288), + SULPHUR(289), + WOOD_HOE(290, 1, 59), + STONE_HOE(291, 1, 131), + IRON_HOE(292, 1, 250), + DIAMOND_HOE(293, 1, 1561), + GOLD_HOE(294, 1, 32), + SEEDS(295), + WHEAT(296), + BREAD(297), + LEATHER_HELMET(298, 1, 55), + LEATHER_CHESTPLATE(299, 1, 80), + LEATHER_LEGGINGS(300, 1, 75), + LEATHER_BOOTS(301, 1, 65), + CHAINMAIL_HELMET(302, 1, 165), + CHAINMAIL_CHESTPLATE(303, 1, 240), + CHAINMAIL_LEGGINGS(304, 1, 225), + CHAINMAIL_BOOTS(305, 1, 195), + IRON_HELMET(306, 1, 165), + IRON_CHESTPLATE(307, 1, 240), + IRON_LEGGINGS(308, 1, 225), + IRON_BOOTS(309, 1, 195), + DIAMOND_HELMET(310, 1, 363), + DIAMOND_CHESTPLATE(311, 1, 528), + DIAMOND_LEGGINGS(312, 1, 495), + DIAMOND_BOOTS(313, 1, 429), + GOLD_HELMET(314, 1, 77), + GOLD_CHESTPLATE(315, 1, 112), + GOLD_LEGGINGS(316, 1, 105), + GOLD_BOOTS(317, 1, 91), + FLINT(318), + PORK(319), + GRILLED_PORK(320), + PAINTING(321), + GOLDEN_APPLE(322), + SIGN(323, 16), + WOOD_DOOR(324, 1), + BUCKET(325, 16), + WATER_BUCKET(326, 1), + LAVA_BUCKET(327, 1), + MINECART(328, 1), + SADDLE(329, 1), + IRON_DOOR(330, 1), + REDSTONE(331), + SNOW_BALL(332, 16), + BOAT(333, 1), + LEATHER(334), + MILK_BUCKET(335, 1), + CLAY_BRICK(336), + CLAY_BALL(337), + SUGAR_CANE(338), + PAPER(339), + BOOK(340), + SLIME_BALL(341), + STORAGE_MINECART(342, 1), + POWERED_MINECART(343, 1), + EGG(344, 16), + COMPASS(345), + FISHING_ROD(346, 1, 64), + WATCH(347), + GLOWSTONE_DUST(348), + RAW_FISH(349), + COOKED_FISH(350), + INK_SACK(351, Dye.class), + BONE(352), + SUGAR(353), + CAKE(354, 1), + BED(355, 1), + DIODE(356), + COOKIE(357), + /** + * @see MapView + */ + MAP(358, MaterialData.class), + SHEARS(359, 1, 238), + MELON(360), + PUMPKIN_SEEDS(361), + MELON_SEEDS(362), + RAW_BEEF(363), + COOKED_BEEF(364), + RAW_CHICKEN(365), + COOKED_CHICKEN(366), + ROTTEN_FLESH(367), + ENDER_PEARL(368, 16), + BLAZE_ROD(369), + GHAST_TEAR(370), + GOLD_NUGGET(371), + NETHER_STALK(372), + /** + * @see Potion + */ + POTION(373, 1, MaterialData.class), + GLASS_BOTTLE(374), + SPIDER_EYE(375), + FERMENTED_SPIDER_EYE(376), + BLAZE_POWDER(377), + MAGMA_CREAM(378), + BREWING_STAND_ITEM(379), + CAULDRON_ITEM(380), + EYE_OF_ENDER(381), + SPECKLED_MELON(382), + MONSTER_EGG(383, 64, SpawnEgg.class), + EXP_BOTTLE(384, 64), + FIREBALL(385, 64), + BOOK_AND_QUILL(386, 1), + WRITTEN_BOOK(387, 16), + EMERALD(388, 64), + ITEM_FRAME(389), + FLOWER_POT_ITEM(390), + CARROT_ITEM(391), + POTATO_ITEM(392), + BAKED_POTATO(393), + POISONOUS_POTATO(394), + EMPTY_MAP(395), + GOLDEN_CARROT(396), + SKULL_ITEM(397), + CARROT_STICK(398, 1, 25), + NETHER_STAR(399), + PUMPKIN_PIE(400), + FIREWORK(401), + FIREWORK_CHARGE(402), + ENCHANTED_BOOK(403, 1), + REDSTONE_COMPARATOR(404), + NETHER_BRICK_ITEM(405), + QUARTZ(406), + EXPLOSIVE_MINECART(407, 1), + HOPPER_MINECART(408, 1), + IRON_BARDING(417, 1), + GOLD_BARDING(418, 1), + DIAMOND_BARDING(419, 1), + LEASH(420), + NAME_TAG(421), + COMMAND_MINECART(422, 1), + GOLD_RECORD(2256, 1), + GREEN_RECORD(2257, 1), + RECORD_3(2258, 1), + RECORD_4(2259, 1), + RECORD_5(2260, 1), + RECORD_6(2261, 1), + RECORD_7(2262, 1), + RECORD_8(2263, 1), + RECORD_9(2264, 1), + RECORD_10(2265, 1), + RECORD_11(2266, 1), + RECORD_12(2267, 1), + ; + + private final int id; + private final Constructor ctor; + private static Material[] byId = new Material[383]; + private final static Map BY_NAME = Maps.newHashMap(); + private final int maxStack; + private final short durability; + + private Material(final int id) { + this(id, 64); + } + + private Material(final int id, final int stack) { + this(id, stack, MaterialData.class); + } + + private Material(final int id, final int stack, final int durability) { + this(id, stack, durability, MaterialData.class); + } + + private Material(final int id, final Class data) { + this(id, 64, data); + } + + private Material(final int id, final int stack, final Class data) { + this(id, stack, 0, data); + } + + private Material(final int id, final int stack, final int durability, final Class data) { + this.id = id; + this.durability = (short) durability; + this.maxStack = stack; + // try to cache the constructor for this material + try { + this.ctor = data.getConstructor(int.class, byte.class); + } catch (NoSuchMethodException ex) { + throw new AssertionError(ex); + } catch (SecurityException ex) { + throw new AssertionError(ex); + } + } + + /** + * Gets the item ID or block ID of this Material + * + * @return ID of this material + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets the maximum amount of this material that can be held in a stack + * + * @return Maximum stack size for this material + */ + public int getMaxStackSize() { + return maxStack; + } + + /** + * Gets the maximum durability of this material + * + * @return Maximum durability for this material + */ + public short getMaxDurability() { + return durability; + } + + /** + * Gets the MaterialData class associated with this Material + * + * @return MaterialData associated with this Material + */ + public Class getData() { + return ctor.getDeclaringClass(); + } + + /** + * Constructs a new MaterialData relevant for this Material, with the + * given initial data + * + * @param raw Initial data to construct the MaterialData with + * @return New MaterialData with the given data + * @deprecated Magic value + */ + @Deprecated + public MaterialData getNewData(final byte raw) { + try { + return ctor.newInstance(id, raw); + } catch (InstantiationException ex) { + final Throwable t = ex.getCause(); + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + if (t instanceof Error) { + throw (Error) t; + } + throw new AssertionError(t); + } catch (Throwable t) { + throw new AssertionError(t); + } + } + + /** + * Checks if this Material is a placable block + * + * @return true if this material is a block + */ + public boolean isBlock() { + return id < 256; + } + + /** + * Checks if this Material is edible. + * + * @return true if this Material is edible. + */ + public boolean isEdible() { + switch (this) { + case BREAD: + case CARROT_ITEM: + case BAKED_POTATO: + case POTATO_ITEM: + case POISONOUS_POTATO: + case GOLDEN_CARROT: + case PUMPKIN_PIE: + case COOKIE: + case MELON: + case MUSHROOM_SOUP: + case RAW_CHICKEN: + case COOKED_CHICKEN: + case RAW_BEEF: + case COOKED_BEEF: + case RAW_FISH: + case COOKED_FISH: + case PORK: + case GRILLED_PORK: + case APPLE: + case GOLDEN_APPLE: + case ROTTEN_FLESH: + case SPIDER_EYE: + return true; + default: + return false; + } + } + + /** + * Attempts to get the Material with the given ID + * + * @param id ID of the material to get + * @return Material if found, or null + * @deprecated Magic value + */ + @Deprecated + public static Material getMaterial(final int id) { + if (byId.length > id && id >= 0) { + return byId[id]; + } else { + return null; + } + } + + /** + * Attempts to get the Material with the given name. + *

          + * This is a normal lookup, names must be the precise name they are given + * in the enum. + * + * @param name Name of the material to get + * @return Material if found, or null + */ + public static Material getMaterial(final String name) { + return BY_NAME.get(name); + } + + /** + * Attempts to match the Material with the given name. + *

          + * This is a match lookup; names will be converted to uppercase, then + * stripped of special characters in an attempt to format it like the + * enum. + *

          + * Using this for match by ID is deprecated. + * + * @param name Name of the material to get + * @return Material if found, or null + */ + public static Material matchMaterial(final String name) { + Validate.notNull(name, "Name cannot be null"); + + Material result = null; + + try { + result = getMaterial(Integer.parseInt(name)); + } catch (NumberFormatException ex) {} + + if (result == null) { + String filtered = name.toUpperCase(); + + filtered = filtered.replaceAll("\\s+", "_").replaceAll("\\W", ""); + result = BY_NAME.get(filtered); + } + + return result; + } + + static { + for (Material material : values()) { + if (byId.length > material.id) { + byId[material.id] = material; + } else { + byId = Java15Compat.Arrays_copyOfRange(byId, 0, material.id + 2); + byId[material.id] = material; + } + BY_NAME.put(material.name(), material); + } + } + + /** + * @return True if this material represents a playable music disk. + */ + public boolean isRecord() { + return id >= GOLD_RECORD.id && id <= RECORD_12.id; + } + + /** + * Check if the material is a block and solid (cannot be passed through by + * a player) + * + * @return True if this material is a block and solid + */ + public boolean isSolid() { + if (!isBlock() || id == 0) { + return false; + } + switch (this) { + case STONE: + case GRASS: + case DIRT: + case COBBLESTONE: + case WOOD: + case BEDROCK: + case SAND: + case GRAVEL: + case GOLD_ORE: + case IRON_ORE: + case COAL_ORE: + case LOG: + case LEAVES: + case SPONGE: + case GLASS: + case LAPIS_ORE: + case LAPIS_BLOCK: + case DISPENSER: + case SANDSTONE: + case NOTE_BLOCK: + case BED_BLOCK: + case PISTON_STICKY_BASE: + case PISTON_BASE: + case PISTON_EXTENSION: + case WOOL: + case PISTON_MOVING_PIECE: + case GOLD_BLOCK: + case IRON_BLOCK: + case DOUBLE_STEP: + case STEP: + case BRICK: + case TNT: + case BOOKSHELF: + case MOSSY_COBBLESTONE: + case OBSIDIAN: + case MOB_SPAWNER: + case WOOD_STAIRS: + case CHEST: + case DIAMOND_ORE: + case DIAMOND_BLOCK: + case WORKBENCH: + case SOIL: + case FURNACE: + case BURNING_FURNACE: + case SIGN_POST: + case WOODEN_DOOR: + case COBBLESTONE_STAIRS: + case WALL_SIGN: + case STONE_PLATE: + case IRON_DOOR_BLOCK: + case WOOD_PLATE: + case REDSTONE_ORE: + case GLOWING_REDSTONE_ORE: + case ICE: + case SNOW_BLOCK: + case CACTUS: + case CLAY: + case JUKEBOX: + case FENCE: + case PUMPKIN: + case NETHERRACK: + case SOUL_SAND: + case GLOWSTONE: + case JACK_O_LANTERN: + case CAKE_BLOCK: + case LOCKED_CHEST: + case STAINED_GLASS: + case TRAP_DOOR: + case MONSTER_EGGS: + case SMOOTH_BRICK: + case HUGE_MUSHROOM_1: + case HUGE_MUSHROOM_2: + case IRON_FENCE: + case THIN_GLASS: + case MELON_BLOCK: + case FENCE_GATE: + case BRICK_STAIRS: + case SMOOTH_STAIRS: + case MYCEL: + case NETHER_BRICK: + case NETHER_FENCE: + case NETHER_BRICK_STAIRS: + case ENCHANTMENT_TABLE: + case BREWING_STAND: + case CAULDRON: + case ENDER_PORTAL_FRAME: + case ENDER_STONE: + case DRAGON_EGG: + case REDSTONE_LAMP_OFF: + case REDSTONE_LAMP_ON: + case WOOD_DOUBLE_STEP: + case WOOD_STEP: + case SANDSTONE_STAIRS: + case EMERALD_ORE: + case ENDER_CHEST: + case EMERALD_BLOCK: + case SPRUCE_WOOD_STAIRS: + case BIRCH_WOOD_STAIRS: + case JUNGLE_WOOD_STAIRS: + case COMMAND: + case BEACON: + case COBBLE_WALL: + case ANVIL: + case TRAPPED_CHEST: + case GOLD_PLATE: + case IRON_PLATE: + case DAYLIGHT_DETECTOR: + case REDSTONE_BLOCK: + case QUARTZ_ORE: + case HOPPER: + case QUARTZ_BLOCK: + case QUARTZ_STAIRS: + case DROPPER: + case STAINED_CLAY: + case HAY_BLOCK: + case HARD_CLAY: + case COAL_BLOCK: + case STAINED_GLASS_PANE: + case LEAVES_2: + case LOG_2: + case ACACIA_STAIRS: + case DARK_OAK_STAIRS: + case PACKED_ICE: + return true; + default: + return false; + } + } + + /** + * Check if the material is a block and does not block any light + * + * @return True if this material is a block and does not block any light + */ + public boolean isTransparent() { + if (!isBlock()) { + return false; + } + switch (this) { + case AIR: + case SAPLING: + case POWERED_RAIL: + case DETECTOR_RAIL: + case LONG_GRASS: + case DEAD_BUSH: + case YELLOW_FLOWER: + case RED_ROSE: + case BROWN_MUSHROOM: + case RED_MUSHROOM: + case TORCH: + case FIRE: + case REDSTONE_WIRE: + case CROPS: + case LADDER: + case RAILS: + case LEVER: + case REDSTONE_TORCH_OFF: + case REDSTONE_TORCH_ON: + case STONE_BUTTON: + case SNOW: + case SUGAR_CANE_BLOCK: + case PORTAL: + case DIODE_BLOCK_OFF: + case DIODE_BLOCK_ON: + case PUMPKIN_STEM: + case MELON_STEM: + case VINE: + case WATER_LILY: + case NETHER_WARTS: + case ENDER_PORTAL: + case COCOA: + case TRIPWIRE_HOOK: + case TRIPWIRE: + case FLOWER_POT: + case CARROT: + case POTATO: + case WOOD_BUTTON: + case SKULL: + case REDSTONE_COMPARATOR_OFF: + case REDSTONE_COMPARATOR_ON: + case ACTIVATOR_RAIL: + case CARPET: + case DOUBLE_PLANT: + return true; + default: + return false; + } + } + + /** + * Check if the material is a block and can catch fire + * + * @return True if this material is a block and can catch fire + */ + public boolean isFlammable() { + if (!isBlock()) { + return false; + } + switch (this) { + case WOOD: + case LOG: + case LEAVES: + case NOTE_BLOCK: + case BED_BLOCK: + case LONG_GRASS: + case DEAD_BUSH: + case WOOL: + case TNT: + case BOOKSHELF: + case WOOD_STAIRS: + case CHEST: + case WORKBENCH: + case SIGN_POST: + case WOODEN_DOOR: + case WALL_SIGN: + case WOOD_PLATE: + case JUKEBOX: + case FENCE: + case TRAP_DOOR: + case HUGE_MUSHROOM_1: + case HUGE_MUSHROOM_2: + case VINE: + case FENCE_GATE: + case WOOD_DOUBLE_STEP: + case WOOD_STEP: + case SPRUCE_WOOD_STAIRS: + case BIRCH_WOOD_STAIRS: + case JUNGLE_WOOD_STAIRS: + case TRAPPED_CHEST: + case DAYLIGHT_DETECTOR: + case CARPET: + case LEAVES_2: + case LOG_2: + case ACACIA_STAIRS: + case DARK_OAK_STAIRS: + return true; + default: + return false; + } + } + + /** + * Check if the material is a block and can burn away + * + * @return True if this material is a block and can burn away + */ + public boolean isBurnable() { + if (!isBlock()) { + return false; + } + switch (this) { + case WOOD: + case LOG: + case LEAVES: + case LONG_GRASS: + case WOOL: + case YELLOW_FLOWER: + case RED_ROSE: + case TNT: + case BOOKSHELF: + case WOOD_STAIRS: + case FENCE: + case VINE: + case WOOD_DOUBLE_STEP: + case WOOD_STEP: + case SPRUCE_WOOD_STAIRS: + case BIRCH_WOOD_STAIRS: + case JUNGLE_WOOD_STAIRS: + case HAY_BLOCK: + case COAL_BLOCK: + case LEAVES_2: + case LOG_2: + case CARPET: + case DOUBLE_PLANT: + return true; + default: + return false; + } + } + + /** + * Check if the material is a block and completely blocks vision + * + * @return True if this material is a block and completely blocks vision + */ + public boolean isOccluding() { + if (!isBlock()) { + return false; + } + switch (this) { + case STONE: + case GRASS: + case DIRT: + case COBBLESTONE: + case WOOD: + case BEDROCK: + case SAND: + case GRAVEL: + case GOLD_ORE: + case IRON_ORE: + case COAL_ORE: + case LOG: + case SPONGE: + case LAPIS_ORE: + case LAPIS_BLOCK: + case DISPENSER: + case SANDSTONE: + case NOTE_BLOCK: + case WOOL: + case GOLD_BLOCK: + case IRON_BLOCK: + case DOUBLE_STEP: + case BRICK: + case BOOKSHELF: + case MOSSY_COBBLESTONE: + case OBSIDIAN: + case MOB_SPAWNER: + case DIAMOND_ORE: + case DIAMOND_BLOCK: + case WORKBENCH: + case FURNACE: + case BURNING_FURNACE: + case REDSTONE_ORE: + case GLOWING_REDSTONE_ORE: + case SNOW_BLOCK: + case CLAY: + case JUKEBOX: + case PUMPKIN: + case NETHERRACK: + case SOUL_SAND: + case JACK_O_LANTERN: + case MONSTER_EGGS: + case SMOOTH_BRICK: + case HUGE_MUSHROOM_1: + case HUGE_MUSHROOM_2: + case MELON_BLOCK: + case MYCEL: + case NETHER_BRICK: + case ENDER_PORTAL_FRAME: + case ENDER_STONE: + case REDSTONE_LAMP_OFF: + case REDSTONE_LAMP_ON: + case WOOD_DOUBLE_STEP: + case EMERALD_ORE: + case EMERALD_BLOCK: + case COMMAND: + case QUARTZ_ORE: + case QUARTZ_BLOCK: + case DROPPER: + case STAINED_CLAY: + case HAY_BLOCK: + case HARD_CLAY: + case COAL_BLOCK: + case LOG_2: + case PACKED_ICE: + return true; + default: + return false; + } + } + + /** + * @return True if this material is affected by gravity. + */ + public boolean hasGravity() { + if (!isBlock()) { + return false; + } + switch (this) { + case SAND: + case GRAVEL: + case ANVIL: + return true; + default: + return false; + } + } +} diff --git a/src/main/java/org/bukkit/NetherWartsState.java b/src/main/java/org/bukkit/NetherWartsState.java new file mode 100644 index 0000000..f43209c --- /dev/null +++ b/src/main/java/org/bukkit/NetherWartsState.java @@ -0,0 +1,21 @@ +package org.bukkit; + +public enum NetherWartsState { + + /** + * State when first seeded + */ + SEEDED, + /** + * First growth stage + */ + STAGE_ONE, + /** + * Second growth stage + */ + STAGE_TWO, + /** + * Ready to harvest + */ + RIPE; +} diff --git a/src/main/java/org/bukkit/Note.java b/src/main/java/org/bukkit/Note.java new file mode 100644 index 0000000..417936f --- /dev/null +++ b/src/main/java/org/bukkit/Note.java @@ -0,0 +1,276 @@ +package org.bukkit; + +import java.util.Map; + +import org.apache.commons.lang.Validate; + +import com.google.common.collect.Maps; + +/** + * A note class to store a specific note. + */ +public class Note { + + /** + * An enum holding tones. + */ + public enum Tone { + G(0x1, true), + A(0x3, true), + B(0x5, false), + C(0x6, true), + D(0x8, true), + E(0xA, false), + F(0xB, true); + + private final boolean sharpable; + private final byte id; + + private static final Map BY_DATA = Maps.newHashMap(); + /** The number of tones including sharped tones. */ + public static final byte TONES_COUNT = 12; + + private Tone(int id, boolean sharpable) { + this.id = (byte) (id % TONES_COUNT); + this.sharpable = sharpable; + } + + /** + * Returns the not sharped id of this tone. + * + * @return the not sharped id of this tone. + * @deprecated Magic value + */ + @Deprecated + public byte getId() { + return getId(false); + } + + /** + * Returns the id of this tone. These method allows to return the + * sharped id of the tone. If the tone couldn't be sharped it always + * return the not sharped id of this tone. + * + * @param sharped Set to true to return the sharped id. + * @return the id of this tone. + * @deprecated Magic value + */ + @Deprecated + public byte getId(boolean sharped) { + byte id = (byte) (sharped && sharpable ? this.id + 1 : this.id); + + return (byte) (id % TONES_COUNT); + } + + /** + * Returns if this tone could be sharped. + * + * @return if this tone could be sharped. + */ + public boolean isSharpable() { + return sharpable; + } + + /** + * Returns if this tone id is the sharped id of the tone. + * + * @param id the id of the tone. + * @return if the tone id is the sharped id of the tone. + * @throws IllegalArgumentException if neither the tone nor the + * semitone have the id. + * @deprecated Magic value + */ + @Deprecated + public boolean isSharped(byte id) { + if (id == getId(false)) { + return false; + } else if (id == getId(true)) { + return true; + } else { + // The id isn't matching to the tone! + throw new IllegalArgumentException("The id isn't matching to the tone."); + } + } + + /** + * Returns the tone to id. Also returning the semitones. + * + * @param id the id of the tone. + * @return the tone to id. + * @deprecated Magic value + */ + @Deprecated + public static Tone getById(byte id) { + return BY_DATA.get(id); + } + + static { + for (Tone tone : values()) { + int id = tone.id % TONES_COUNT; + BY_DATA.put((byte) id, tone); + + if (tone.isSharpable()) { + id = (id + 1) % TONES_COUNT; + BY_DATA.put((byte) id, tone); + } + } + } + } + + private final byte note; + + /** + * Creates a new note. + * + * @param note Internal note id. {@link #getId()} always return this + * value. The value has to be in the interval [0; 24]. + */ + public Note(int note) { + Validate.isTrue(note >= 0 && note <= 24, "The note value has to be between 0 and 24."); + + this.note = (byte) note; + } + + /** + * Creates a new note. + * + * @param octave The octave where the note is in. Has to be 0 - 2. + * @param tone The tone within the octave. If the octave is 2 the note has + * to be F#. + * @param sharped Set if the tone is sharped (e.g. for F#). + */ + public Note(int octave, Tone tone, boolean sharped) { + if (sharped && !tone.isSharpable()) { + tone = Tone.values()[tone.ordinal() + 1]; + sharped = false; + } + if (octave < 0 || octave > 2 || (octave == 2 && !(tone == Tone.F && sharped))) { + throw new IllegalArgumentException("Tone and octave have to be between F#0 and F#2"); + } + + this.note = (byte) (octave * Tone.TONES_COUNT + tone.getId(sharped)); + } + + /** + * Creates a new note for a flat tone, such as A-flat. + * + * @param octave The octave where the note is in. Has to be 0 - 1. + * @param tone The tone within the octave. + * @return The new note. + */ + public static Note flat(int octave, Tone tone) { + Validate.isTrue(octave != 2, "Octave cannot be 2 for flats"); + tone = tone == Tone.G ? Tone.F : Tone.values()[tone.ordinal() - 1]; + return new Note(octave, tone, tone.isSharpable()); + } + + /** + * Creates a new note for a sharp tone, such as A-sharp. + * + * @param octave The octave where the note is in. Has to be 0 - 2. + * @param tone The tone within the octave. If the octave is 2 the note has + * to be F#. + * @return The new note. + */ + public static Note sharp(int octave, Tone tone) { + return new Note(octave, tone, true); + } + + /** + * Creates a new note for a natural tone, such as A-natural. + * + * @param octave The octave where the note is in. Has to be 0 - 1. + * @param tone The tone within the octave. + * @return The new note. + */ + public static Note natural(int octave, Tone tone) { + Validate.isTrue(octave != 2, "Octave cannot be 2 for naturals"); + return new Note(octave, tone, false); + } + + /** + * @return The note a semitone above this one. + */ + public Note sharped() { + Validate.isTrue(note < 24, "This note cannot be sharped because it is the highest known note!"); + return new Note(note + 1); + } + + /** + * @return The note a semitone below this one. + */ + public Note flattened() { + Validate.isTrue(note > 0, "This note cannot be flattened because it is the lowest known note!"); + return new Note(note - 1); + } + + /** + * Returns the internal id of this note. + * + * @return the internal id of this note. + * @deprecated Magic value + */ + @Deprecated + public byte getId() { + return note; + } + + /** + * Returns the octave of this note. + * + * @return the octave of this note. + */ + public int getOctave() { + return note / Tone.TONES_COUNT; + } + + private byte getToneByte() { + return (byte) (note % Tone.TONES_COUNT); + } + + /** + * Returns the tone of this note. + * + * @return the tone of this note. + */ + public Tone getTone() { + return Tone.getById(getToneByte()); + } + + /** + * Returns if this note is sharped. + * + * @return if this note is sharped. + */ + public boolean isSharped() { + byte note = getToneByte(); + return Tone.getById(note).isSharped(note); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + note; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Note other = (Note) obj; + if (note != other.note) + return false; + return true; + } + + @Override + public String toString() { + return "Note{" + getTone().toString() + (isSharped() ? "#" : "") + "}"; + } +} diff --git a/src/main/java/org/bukkit/OfflinePlayer.java b/src/main/java/org/bukkit/OfflinePlayer.java new file mode 100644 index 0000000..e98706a --- /dev/null +++ b/src/main/java/org/bukkit/OfflinePlayer.java @@ -0,0 +1,118 @@ +package org.bukkit; + +import java.util.Date; +import java.util.UUID; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.Player; +import org.bukkit.permissions.ServerOperator; + +public interface OfflinePlayer extends ServerOperator, AnimalTamer, ConfigurationSerializable { + + /** + * Checks if this player is currently online + * + * @return true if they are online + */ + public boolean isOnline(); + + /** + * Returns the name of this player + *

          + * Names are no longer unique past a single game session. For persistent storage + * it is recommended that you use {@link #getUniqueId()} instead. + * + * @return Player name or null if we have not seen a name for this player yet + */ + public String getName(); + + /** + * Returns the UUID of this player + * + * @return Player UUID + */ + public UUID getUniqueId(); + + /** + * Checks if this player is banned or not + * + * @return true if banned, otherwise false + */ + public boolean isBanned(); + + /** + * Bans or unbans this player + * + * @param banned true if banned + * @deprecated Use {@link org.bukkit.BanList#addBan(String, String, Date, + * String)} or {@link org.bukkit.BanList#pardon(String)} to enhance + * functionality + */ + @Deprecated + public void setBanned(boolean banned); + + /** + * Checks if this player is whitelisted or not + * + * @return true if whitelisted + */ + public boolean isWhitelisted(); + + /** + * Sets if this player is whitelisted or not + * + * @param value true if whitelisted + */ + public void setWhitelisted(boolean value); + + /** + * Gets a {@link Player} object that this represents, if there is one + *

          + * If the player is online, this will return that player. Otherwise, + * it will return null. + * + * @return Online player + */ + public Player getPlayer(); + + /** + * Gets the first date and time that this player was witnessed on this + * server. + *

          + * If the player has never played before, this will return 0. Otherwise, + * it will be the amount of milliseconds since midnight, January 1, 1970 + * UTC. + * + * @return Date of first log-in for this player, or 0 + */ + public long getFirstPlayed(); + + /** + * Gets the last date and time that this player was witnessed on this + * server. + *

          + * If the player has never played before, this will return 0. Otherwise, + * it will be the amount of milliseconds since midnight, January 1, 1970 + * UTC. + * + * @return Date of last log-in for this player, or 0 + */ + public long getLastPlayed(); + + /** + * Checks if this player has played on this server before. + * + * @return True if the player has played before, otherwise false + */ + public boolean hasPlayedBefore(); + + /** + * Gets the Location where the player will spawn at their bed, null if + * they have not slept in one or their current bed spawn is invalid. + * + * @return Bed Spawn Location if bed exists, otherwise null. + */ + public Location getBedSpawnLocation(); + +} diff --git a/src/main/java/org/bukkit/PortalType.java b/src/main/java/org/bukkit/PortalType.java new file mode 100644 index 0000000..427cfbb --- /dev/null +++ b/src/main/java/org/bukkit/PortalType.java @@ -0,0 +1,22 @@ +package org.bukkit; + +/** + * Represents various types of portals that can be made in a world. + */ +public enum PortalType { + + /** + * This is a Nether portal, made of obsidian. + */ + NETHER, + + /** + * This is an Ender portal. + */ + ENDER, + + /** + * This is a custom Plugin portal. + */ + CUSTOM; +} diff --git a/src/main/java/org/bukkit/Rotation.java b/src/main/java/org/bukkit/Rotation.java new file mode 100644 index 0000000..dfdb0e5 --- /dev/null +++ b/src/main/java/org/bukkit/Rotation.java @@ -0,0 +1,47 @@ +package org.bukkit; + +/** + * An enum to specify a rotation based orientation, like that on a clock. + *

          + * It represents how something is viewed, as opposed to cardinal directions. + */ +public enum Rotation { + + /** + * No rotation + */ + NONE, + /** + * Rotated clockwise by 90 degrees + */ + CLOCKWISE, + /** + * Flipped upside-down, a 180 degree rotation + */ + FLIPPED, + /** + * Rotated counter-clockwise by 90 degrees + */ + COUNTER_CLOCKWISE, + ; + + private static final Rotation [] rotations = values(); + + /** + * Rotate clockwise by 90 degrees. + * + * @return the relative rotation + */ + public Rotation rotateClockwise() { + return rotations[(this.ordinal() + 1) & 0x3]; + } + + /** + * Rotate counter-clockwise by 90 degrees. + * + * @return the relative rotation + */ + public Rotation rotateCounterClockwise() { + return rotations[(this.ordinal() - 1) & 0x3]; + } +} diff --git a/src/main/java/org/bukkit/SandstoneType.java b/src/main/java/org/bukkit/SandstoneType.java new file mode 100644 index 0000000..a9ac16e --- /dev/null +++ b/src/main/java/org/bukkit/SandstoneType.java @@ -0,0 +1,51 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +/** + * Represents the three different types of Sandstone + */ +public enum SandstoneType { + CRACKED(0x0), + GLYPHED(0x1), + SMOOTH(0x2); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + private SandstoneType(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this type of sandstone + * + * @return A byte containing the data value of this sandstone type + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the type of sandstone with the given data value + * + * @param data Data value to fetch + * @return The {@link SandstoneType} representing the given value, or null + * if it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static SandstoneType getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (SandstoneType type : values()) { + BY_DATA.put(type.data, type); + } + } +} diff --git a/src/main/java/org/bukkit/Server.java b/src/main/java/org/bukkit/Server.java new file mode 100644 index 0000000..e14e9f1 --- /dev/null +++ b/src/main/java/org/bukkit/Server.java @@ -0,0 +1,919 @@ +package org.bukkit; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.Serializable; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Logger; + +import org.bukkit.Warning.WarningState; +import org.bukkit.command.CommandException; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.server.ServerListPingEvent; +import org.bukkit.help.HelpMap; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; +import org.bukkit.map.MapView; +import org.bukkit.permissions.Permissible; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.ServicesManager; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.plugin.messaging.PluginMessageRecipient; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scoreboard.ScoreboardManager; +import org.bukkit.util.CachedServerIcon; + +import com.avaje.ebean.config.ServerConfig; +import com.google.common.collect.ImmutableList; + +import org.bukkit.inventory.ItemFactory; +import org.bukkit.inventory.meta.ItemMeta; + +/** + * Represents a server implementation. + */ +public interface Server extends PluginMessageRecipient { + + /** + * Used for all administrative messages, such as an operator using a + * command. + *

          + * For use in {@link #broadcast(java.lang.String, java.lang.String)}. + */ + public static final String BROADCAST_CHANNEL_ADMINISTRATIVE = "bukkit.broadcast.admin"; + + /** + * Used for all announcement messages, such as informing users that a + * player has joined. + *

          + * For use in {@link #broadcast(java.lang.String, java.lang.String)}. + */ + public static final String BROADCAST_CHANNEL_USERS = "bukkit.broadcast.user"; + + /** + * Gets the name of this server implementation. + * + * @return name of this server implementation + */ + public String getName(); + + /** + * Gets the version string of this server implementation. + * + * @return version of this server implementation + */ + public String getVersion(); + + /** + * Gets the Bukkit version that this server is running. + * + * @return version of Bukkit + */ + public String getBukkitVersion(); + + /** + * Gets an array copy of all currently logged in players. + *

          + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @Deprecated superseded by {@link #getOnlinePlayers()} + * @return an array of Players that are currently online + */ + @Deprecated + public Player[] _INVALID_getOnlinePlayers(); + + /** + * Gets a view of all currently logged in players. This {@linkplain + * Collections#unmodifiableCollection(Collection) view} is a reused + * object, making some operations like {@link Collection#size()} + * zero-allocation. + *

          + * The collection is a view backed by the internal representation, such + * that, changes to the internal state of the server will be reflected + * immediately. However, the reuse of the returned collection (identity) + * is not strictly guaranteed for future or all implementations. Casting + * the collection, or relying on interface implementations (like {@link + * Serializable} or {@link List}), is deprecated. + *

          + * Iteration behavior is undefined outside of self-contained main-thread + * uses. Normal and immediate iterator use without consequences that + * affect the collection are fully supported. The effects following + * (non-exhaustive) {@link Entity#teleport(Location) teleportation}, + * {@link Player#setHealth(double) death}, and {@link Player#kickPlayer( + * String) kicking} are undefined. Any use of this collection from + * asynchronous threads is unsafe. + *

          + * For safe consequential iteration or mimicking the old array behavior, + * using {@link Collection#toArray(Object[])} is recommended. For making + * snapshots, {@link ImmutableList#copyOf(Collection)} is recommended. + * + * @return a view of currently online players. + */ + public Collection getOnlinePlayers(); + + /** + * Get the maximum amount of players which can login to this server. + * + * @return the amount of players this server allows + */ + public int getMaxPlayers(); + + /** + * Get the game port that the server runs on. + * + * @return the port number of this server + */ + public int getPort(); + + /** + * Get the view distance from this server. + * + * @return the view distance from this server. + */ + public int getViewDistance(); + + /** + * Get the IP that this server is bound to, or empty string if not + * specified. + * + * @return the IP string that this server is bound to, otherwise empty + * string + */ + public String getIp(); + + /** + * Get the name of this server. + * + * @return the name of this server + */ + public String getServerName(); + + /** + * Get an ID of this server. The ID is a simple generally alphanumeric ID + * that can be used for uniquely identifying this server. + * + * @return the ID of this server + */ + public String getServerId(); + + /** + * Get world type (level-type setting) for default world. + * + * @return the value of level-type (e.g. DEFAULT, FLAT, DEFAULT_1_1) + */ + public String getWorldType(); + + /** + * Get generate-structures setting. + * + * @return true if structure generation is enabled, false otherwise + */ + public boolean getGenerateStructures(); + + /** + * Gets whether this server allows the End or not. + * + * @return whether this server allows the End or not + */ + public boolean getAllowEnd(); + + /** + * Gets whether this server allows the Nether or not. + * + * @return whether this server allows the Nether or not + */ + public boolean getAllowNether(); + + /** + * Gets whether this server has a whitelist or not. + * + * @return whether this server has a whitelist or not + */ + public boolean hasWhitelist(); + + /** + * Sets if the server is whitelisted. + * + * @param value true for whitelist on, false for off + */ + public void setWhitelist(boolean value); + + /** + * Gets a list of whitelisted players. + * + * @return a set containing all whitelisted players + */ + public Set getWhitelistedPlayers(); + + /** + * Reloads the whitelist from disk. + */ + public void reloadWhitelist(); + + /** + * Broadcast a message to all players. + *

          + * This is the same as calling {@link #broadcast(java.lang.String, + * java.lang.String)} to {@link #BROADCAST_CHANNEL_USERS} + * + * @param message the message + * @return the number of players + */ + public int broadcastMessage(String message); + + /** + * Gets the name of the update folder. The update folder is used to safely + * update plugins at the right moment on a plugin load. + *

          + * The update folder name is relative to the plugins folder. + * + * @return the name of the update folder + */ + public String getUpdateFolder(); + + /** + * Gets the update folder. The update folder is used to safely update + * plugins at the right moment on a plugin load. + * + * @return the update folder + */ + public File getUpdateFolderFile(); + + /** + * Gets the value of the connection throttle setting. + * + * @return the value of the connection throttle setting + */ + public long getConnectionThrottle(); + + /** + * Gets default ticks per animal spawns value. + *

          + * Example Usage: + *

            + *
          • A value of 1 will mean the server will attempt to spawn monsters + * every tick. + *
          • A value of 400 will mean the server will attempt to spawn monsters + * every 400th tick. + *
          • A value below 0 will be reset back to Minecraft's default. + *
          + *

          + * Note: If set to 0, animal spawning will be disabled. We + * recommend using spawn-animals to control this instead. + *

          + * Minecraft default: 400. + * + * @return the default ticks per animal spawns value + */ + public int getTicksPerAnimalSpawns(); + + /** + * Gets the default ticks per monster spawns value. + *

          + * Example Usage: + *

            + *
          • A value of 1 will mean the server will attempt to spawn monsters + * every tick. + *
          • A value of 400 will mean the server will attempt to spawn monsters + * every 400th tick. + *
          • A value below 0 will be reset back to Minecraft's default. + *
          + *

          + * Note: If set to 0, monsters spawning will be disabled. We + * recommend using spawn-monsters to control this instead. + *

          + * Minecraft default: 1. + * + * @return the default ticks per monsters spawn value + */ + public int getTicksPerMonsterSpawns(); + + /** + * Gets a player object by the given username. + *

          + * This method may not return objects for offline players. + * + * @deprecated Use {@link #getPlayer(UUID)} as player names are no longer + * guaranteed to be unique + * @param name the name to look up + * @return a player if one was found, null otherwise + */ + @Deprecated + public Player getPlayer(String name); + + /** + * Gets the player with the exact given name, case insensitive. + * + * @deprecated Use {@link #getPlayer(UUID)} as player names are no longer + * guaranteed to be unique + * @param name Exact name of the player to retrieve + * @return a player object if one was found, null otherwise + */ + @Deprecated + public Player getPlayerExact(String name); + + /** + * Attempts to match any players with the given name, and returns a list + * of all possibly matches. + *

          + * This list is not sorted in any particular order. If an exact match is + * found, the returned list will only contain a single result. + * + * @deprecated Use {@link #getPlayer(UUID)} as player names are no longer + * guaranteed to be unique + * @param name the (partial) name to match + * @return list of all possible players + */ + @Deprecated + public List matchPlayer(String name); + + /** + * Gets the player with the given UUID. + * + * @param id UUID of the player to retrieve + * @return a player object if one was found, null otherwise + */ + public Player getPlayer(UUID id); + + /** + * Gets the plugin manager for interfacing with plugins. + * + * @return a plugin manager for this Server instance + */ + public PluginManager getPluginManager(); + + /** + * Gets the scheduler for managing scheduled events. + * + * @return a scheduling service for this server + */ + public BukkitScheduler getScheduler(); + + /** + * Gets a services manager. + * + * @return s services manager + */ + public ServicesManager getServicesManager(); + + /** + * Gets a list of all worlds on this server. + * + * @return a list of worlds + */ + public List getWorlds(); + + /** + * Creates or loads a world with the given name using the specified + * options. + *

          + * If the world is already loaded, it will just return the equivalent of + * getWorld(creator.name()). + * + * @param creator the options to use when creating the world + * @return newly created or loaded world + */ + public World createWorld(WorldCreator creator); + + /** + * Unloads a world with the given name. + * + * @param name Name of the world to unload + * @param save whether to save the chunks before unloading + * @return true if successful, false otherwise + */ + public boolean unloadWorld(String name, boolean save); + + /** + * Unloads the given world. + * + * @param world the world to unload + * @param save whether to save the chunks before unloading + * @return true if successful, false otherwise + */ + public boolean unloadWorld(World world, boolean save); + + /** + * Gets the world with the given name. + * + * @param name the name of the world to retrieve + * @return a world with the given name, or null if none exists + */ + public World getWorld(String name); + + /** + * Gets the world from the given Unique ID. + * + * @param uid a unique-id of the world to retrieve + * @return a world with the given Unique ID, or null if none exists + */ + public World getWorld(UUID uid); + + /** + * Gets the map from the given item ID. + * + * @param id the id of the map to get + * @return a map view if it exists, or null otherwise + * @deprecated Magic value + */ + @Deprecated + public MapView getMap(short id); + + /** + * Create a new map with an automatically assigned ID. + * + * @param world the world the map will belong to + * @return a newly created map view + */ + public MapView createMap(World world); + + /** + * Reloads the server, refreshing settings and plugin information. + */ + public void reload(); + + /** + * Returns the primary logger associated with this server instance. + * + * @return Logger associated with this server + */ + public Logger getLogger(); + + /** + * Gets a {@link PluginCommand} with the given name or alias. + * + * @param name the name of the command to retrieve + * @return a plugin command if found, null otherwise + */ + public PluginCommand getPluginCommand(String name); + + /** + * Writes loaded players to disk. + */ + public void savePlayers(); + + /** + * Dispatches a command on this server, and executes it if found. + * + * @param sender the apparent sender of the command + * @param commandLine the command + arguments. Example: test abc + * 123 + * @return returns false if no target is found + * @throws CommandException thrown when the executor for the given command + * fails with an unhandled exception + */ + public boolean dispatchCommand(CommandSender sender, String commandLine) throws CommandException; + + /** + * Populates a given {@link ServerConfig} with values attributes to this + * server. + * + * @param config the server config to populate + */ + public void configureDbConfig(ServerConfig config); + + /** + * Adds a recipe to the crafting manager. + * + * @param recipe the recipe to add + * @return true if the recipe was added, false if it wasn't for some + * reason + */ + public boolean addRecipe(Recipe recipe); + + /** + * Get a list of all recipes for a given item. The stack size is ignored + * in comparisons. If the durability is -1, it will match any data value. + * + * @param result the item to match against recipe results + * @return a list of recipes with the given result + */ + public List getRecipesFor(ItemStack result); + + /** + * Get an iterator through the list of crafting recipes. + * + * @return an iterator + */ + public Iterator recipeIterator(); + + /** + * Clears the list of crafting recipes. + */ + public void clearRecipes(); + + /** + * Resets the list of crafting recipes to the default. + */ + public void resetRecipes(); + + /** + * Gets a list of command aliases defined in the server properties. + * + * @return a map of aliases to command names + */ + public Map getCommandAliases(); + + /** + * Gets the radius, in blocks, around each worlds spawn point to protect. + * + * @return spawn radius, or 0 if none + */ + public int getSpawnRadius(); + + /** + * Sets the radius, in blocks, around each worlds spawn point to protect. + * + * @param value new spawn radius, or 0 if none + */ + public void setSpawnRadius(int value); + + /** + * Gets whether the Server is in online mode or not. + * + * @return true if the server authenticates clients, false otherwise + */ + public boolean getOnlineMode(); + + /** + * Gets whether this server allows flying or not. + * + * @return true if the server allows flight, false otherwise + */ + public boolean getAllowFlight(); + + /** + * Gets whether the server is in hardcore mode or not. + * + * @return true if the server mode is hardcore, false otherwise + */ + public boolean isHardcore(); + + /** + * Gets whether to use vanilla (false) or exact behaviour (true). + * + *

            + *
          • Vanilla behaviour: check for collisions and move the player if + * needed. + *
          • Exact behaviour: spawn players exactly where they should be. + *
          + * + * @return true if exact location locations are used for spawning, false + * for vanilla collision detection or otherwise + */ + public boolean useExactLoginLocation(); + + /** + * Shutdowns the server, stopping everything. + */ + public void shutdown(); + + /** + * Broadcasts the specified message to every user with the given + * permission name. + * + * @param message message to broadcast + * @param permission the required permission {@link Permissible + * permissibles} must have to receive the broadcast + * @return number of message recipients + */ + public int broadcast(String message, String permission); + + /** + * Gets the player by the given name, regardless if they are offline or + * online. + *

          + * This method may involve a blocking web request to get the UUID for the + * given name. + *

          + * This will return an object even if the player does not exist. To this + * method, all players will exist. + * + * @deprecated Persistent storage of users should be by UUID as names are no longer + * unique past a single session. + * @param name the name the player to retrieve + * @return an offline player + * @see #getOfflinePlayer(java.util.UUID) + */ + @Deprecated + public OfflinePlayer getOfflinePlayer(String name); + + /** + * Gets the player by the given UUID, regardless if they are offline or + * online. + *

          + * This will return an object even if the player does not exist. To this + * method, all players will exist. + * + * @param id the UUID of the player to retrieve + * @return an offline player + */ + public OfflinePlayer getOfflinePlayer(UUID id); + + /** + * Gets a set containing all current IPs that are banned. + * + * @return a set containing banned IP addresses + */ + public Set getIPBans(); + + /** + * Bans the specified address from the server. + * + * @param address the IP address to ban + */ + public void banIP(String address); + + /** + * Unbans the specified address from the server. + * + * @param address the IP address to unban + */ + public void unbanIP(String address); + + /** + * Gets a set containing all banned players. + * + * @return a set containing banned players + */ + public Set getBannedPlayers(); + + /** + * Gets a ban list for the supplied type. + *

          + * Bans by name are no longer supported and this method will return + * null when trying to request them. The replacement is bans by UUID. + * + * @param type the type of list to fetch, cannot be null + * @return a ban list of the specified type + */ + public BanList getBanList(BanList.Type type); + + /** + * Gets a set containing all player operators. + * + * @return a set containing player operators + */ + public Set getOperators(); + + /** + * Gets the default {@link GameMode} for new players. + * + * @return the default game mode + */ + public GameMode getDefaultGameMode(); + + /** + * Sets the default {@link GameMode} for new players. + * + * @param mode the new game mode + */ + public void setDefaultGameMode(GameMode mode); + + /** + * Gets a {@link ConsoleCommandSender} that may be used as an input source + * for this server. + * + * @return a console command sender + */ + public ConsoleCommandSender getConsoleSender(); + + /** + * Gets the folder that contains all of the various {@link World}s. + * + * @return folder that contains all worlds + */ + public File getWorldContainer(); + + /** + * Gets every player that has ever played on this server. + * + * @return an array containing all previous players + */ + public OfflinePlayer[] getOfflinePlayers(); + + /** + * Gets the {@link Messenger} responsible for this server. + * + * @return messenger responsible for this server + */ + public Messenger getMessenger(); + + /** + * Gets the {@link HelpMap} providing help topics for this server. + * + * @return a help map for this server + */ + public HelpMap getHelpMap(); + + /** + * Creates an empty inventory of the specified type. If the type is {@link + * InventoryType#CHEST}, the new inventory has a size of 27; otherwise the + * new inventory has the normal size for its type. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param type the type of inventory to create + * @return a new inventory + */ + Inventory createInventory(InventoryHolder owner, InventoryType type); + + /** + * Creates an empty inventory with the specified type and title. If the type + * is {@link InventoryType#CHEST}, the new inventory has a size of 27; + * otherwise the new inventory has the normal size for its type.
          + * It should be noted that some inventory types do not support titles and + * may not render with said titles on the Minecraft client. + * + * @param owner The holder of the inventory; can be null if there's no holder. + * @param type The type of inventory to create. + * @param title The title of the inventory, to be displayed when it is viewed. + * @return The new inventory. + */ + Inventory createInventory(InventoryHolder owner, InventoryType type, String title); + + /** + * Creates an empty inventory of type {@link InventoryType#CHEST} with the + * specified size. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param size a multiple of 9 as the size of inventory to create + * @return a new inventory + * @throws IllegalArgumentException if the size is not a multiple of 9 + */ + Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException; + + /** + * Creates an empty inventory of type {@link InventoryType#CHEST} with the + * specified size and title. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param size a multiple of 9 as the size of inventory to create + * @param title the title of the inventory, displayed when inventory is + * viewed + * @return a new inventory + * @throws IllegalArgumentException if the size is not a multiple of 9 + */ + Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException; + + /** + * Gets user-specified limit for number of monsters that can spawn in a + * chunk. + * + * @return the monster spawn limit + */ + int getMonsterSpawnLimit(); + + /** + * Gets user-specified limit for number of animals that can spawn in a + * chunk. + * + * @return the animal spawn limit + */ + int getAnimalSpawnLimit(); + + /** + * Gets user-specified limit for number of water animals that can spawn in + * a chunk. + * + * @return the water animal spawn limit + */ + int getWaterAnimalSpawnLimit(); + + /** + * Gets user-specified limit for number of ambient mobs that can spawn in + * a chunk. + * + * @return the ambient spawn limit + */ + int getAmbientSpawnLimit(); + + /** + * Checks the current thread against the expected primary thread for the + * server. + *

          + * Note: this method should not be used to indicate the current + * synchronized state of the runtime. A current thread matching the main + * thread indicates that it is synchronized, but a mismatch does not + * preclude the same assumption. + * + * @return true if the current thread matches the expected primary thread, + * false otherwise + */ + boolean isPrimaryThread(); + + /** + * Gets the message that is displayed on the server list. + * + * @return the servers MOTD + */ + String getMotd(); + + /** + * Gets the default message that is displayed when the server is stopped. + * + * @return the shutdown message + */ + String getShutdownMessage(); + + /** + * Gets the current warning state for the server. + * + * @return the configured warning state + */ + public WarningState getWarningState(); + + /** + * Gets the instance of the item factory (for {@link ItemMeta}). + * + * @return the item factory + * @see ItemFactory + */ + ItemFactory getItemFactory(); + + /** + * Gets the instance of the scoreboard manager. + *

          + * This will only exist after the first world has loaded. + * + * @return the scoreboard manager or null if no worlds are loaded. + */ + ScoreboardManager getScoreboardManager(); + + /** + * Gets an instance of the server's default server-icon. + * + * @return the default server-icon; null values may be used by the + * implementation to indicate no defined icon, but this behavior is + * not guaranteed + */ + CachedServerIcon getServerIcon(); + + /** + * Loads an image from a file, and returns a cached image for the specific + * server-icon. + *

          + * Size and type are implementation defined. An incompatible file is + * guaranteed to throw an implementation-defined {@link Exception}. + * + * @param file the file to load the from + * @throws IllegalArgumentException if image is null + * @throws Exception if the image does not meet current server server-icon + * specifications + * @return a cached server-icon that can be used for a {@link + * ServerListPingEvent#setServerIcon(CachedServerIcon)} + */ + CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception; + + /** + * Creates a cached server-icon for the specific image. + *

          + * Size and type are implementation defined. An incompatible file is + * guaranteed to throw an implementation-defined {@link Exception}. + * + * @param image the image to use + * @throws IllegalArgumentException if image is null + * @throws Exception if the image does not meet current server + * server-icon specifications + * @return a cached server-icon that can be used for a {@link + * ServerListPingEvent#setServerIcon(CachedServerIcon)} + */ + CachedServerIcon loadServerIcon(BufferedImage image) throws IllegalArgumentException, Exception; + + /** + * Set the idle kick timeout. Any players idle for the specified amount of + * time will be automatically kicked. + *

          + * A value of 0 will disable the idle kick timeout. + * + * @param threshold the idle timeout in minutes + */ + public void setIdleTimeout(int threshold); + + /** + * Gets the idle kick timeout. + * + * @return the idle timeout in minutes + */ + public int getIdleTimeout(); + + /** + * @see UnsafeValues + */ + @Deprecated + UnsafeValues getUnsafe(); +} diff --git a/src/main/java/org/bukkit/SkullType.java b/src/main/java/org/bukkit/SkullType.java new file mode 100644 index 0000000..abd07c2 --- /dev/null +++ b/src/main/java/org/bukkit/SkullType.java @@ -0,0 +1,12 @@ +package org.bukkit; + +/** + * Represents the different types of skulls. + */ +public enum SkullType { + SKELETON, + WITHER, + ZOMBIE, + PLAYER, + CREEPER; +} diff --git a/src/main/java/org/bukkit/Sound.java b/src/main/java/org/bukkit/Sound.java new file mode 100644 index 0000000..0913530 --- /dev/null +++ b/src/main/java/org/bukkit/Sound.java @@ -0,0 +1,211 @@ +package org.bukkit; + +/** + * An Enum of Sounds the server is able to send to players. + *

          + * WARNING: At any time, sounds may be added/removed from this Enum or even + * MineCraft itself! There is no guarantee the sounds will play. There is no + * guarantee values will not be removed from this Enum. As such, you should + * not depend on the ordinal values of this class. + */ +public enum Sound { + AMBIENCE_CAVE, + AMBIENCE_RAIN, + AMBIENCE_THUNDER, + ANVIL_BREAK, + ANVIL_LAND, + ANVIL_USE, + ARROW_HIT, + BURP, + CHEST_CLOSE, + CHEST_OPEN, + CLICK, + DOOR_CLOSE, + DOOR_OPEN, + DRINK, + EAT, + EXPLODE, + FALL_BIG, + FALL_SMALL, + FIRE, + FIRE_IGNITE, + FIZZ, + FUSE, + GLASS, + HURT_FLESH, + ITEM_BREAK, + ITEM_PICKUP, + LAVA, + LAVA_POP, + LEVEL_UP, + MINECART_BASE, + MINECART_INSIDE, + NOTE_BASS, + NOTE_PIANO, + NOTE_BASS_DRUM, + NOTE_STICKS, + NOTE_BASS_GUITAR, + NOTE_SNARE_DRUM, + NOTE_PLING, + ORB_PICKUP, + PISTON_EXTEND, + PISTON_RETRACT, + PORTAL, + PORTAL_TRAVEL, + PORTAL_TRIGGER, + SHOOT_ARROW, + SPLASH, + SPLASH2, + STEP_GRASS, + STEP_GRAVEL, + STEP_LADDER, + STEP_SAND, + STEP_SNOW, + STEP_STONE, + STEP_WOOD, + STEP_WOOL, + SWIM, + WATER, + WOOD_CLICK, + // Mob sounds + BAT_DEATH, + BAT_HURT, + BAT_IDLE, + BAT_LOOP, + BAT_TAKEOFF, + BLAZE_BREATH, + BLAZE_DEATH, + BLAZE_HIT, + CAT_HISS, + CAT_HIT, + CAT_MEOW, + CAT_PURR, + CAT_PURREOW, + CHICKEN_IDLE, + CHICKEN_HURT, + CHICKEN_EGG_POP, + CHICKEN_WALK, + COW_IDLE, + COW_HURT, + COW_WALK, + CREEPER_HISS, + CREEPER_DEATH, + ENDERDRAGON_DEATH, + ENDERDRAGON_GROWL, + ENDERDRAGON_HIT, + ENDERDRAGON_WINGS, + ENDERMAN_DEATH, + ENDERMAN_HIT, + ENDERMAN_IDLE, + ENDERMAN_TELEPORT, + ENDERMAN_SCREAM, + ENDERMAN_STARE, + GHAST_SCREAM, + GHAST_SCREAM2, + GHAST_CHARGE, + GHAST_DEATH, + GHAST_FIREBALL, + GHAST_MOAN, + IRONGOLEM_DEATH, + IRONGOLEM_HIT, + IRONGOLEM_THROW, + IRONGOLEM_WALK, + MAGMACUBE_WALK, + MAGMACUBE_WALK2, + MAGMACUBE_JUMP, + PIG_IDLE, + PIG_DEATH, + PIG_WALK, + SHEEP_IDLE, + SHEEP_SHEAR, + SHEEP_WALK, + SILVERFISH_HIT, + SILVERFISH_KILL, + SILVERFISH_IDLE, + SILVERFISH_WALK, + SKELETON_IDLE, + SKELETON_DEATH, + SKELETON_HURT, + SKELETON_WALK, + SLIME_ATTACK, + SLIME_WALK, + SLIME_WALK2, + SPIDER_IDLE, + SPIDER_DEATH, + SPIDER_WALK, + WITHER_DEATH, + WITHER_HURT, + WITHER_IDLE, + WITHER_SHOOT, + WITHER_SPAWN, + WOLF_BARK, + WOLF_DEATH, + WOLF_GROWL, + WOLF_HOWL, + WOLF_HURT, + WOLF_PANT, + WOLF_SHAKE, + WOLF_WALK, + WOLF_WHINE, + ZOMBIE_METAL, + ZOMBIE_WOOD, + ZOMBIE_WOODBREAK, + ZOMBIE_IDLE, + ZOMBIE_DEATH, + ZOMBIE_HURT, + ZOMBIE_INFECT, + ZOMBIE_UNFECT, + ZOMBIE_REMEDY, + ZOMBIE_WALK, + ZOMBIE_PIG_IDLE, + ZOMBIE_PIG_ANGRY, + ZOMBIE_PIG_DEATH, + ZOMBIE_PIG_HURT, + // Dig Sounds + DIG_WOOL, + DIG_GRASS, + DIG_GRAVEL, + DIG_SAND, + DIG_SNOW, + DIG_STONE, + DIG_WOOD, + // Fireworks + FIREWORK_BLAST, + FIREWORK_BLAST2, + FIREWORK_LARGE_BLAST, + FIREWORK_LARGE_BLAST2, + FIREWORK_TWINKLE, + FIREWORK_TWINKLE2, + FIREWORK_LAUNCH, + SUCCESSFUL_HIT, + // Horses + HORSE_ANGRY, + HORSE_ARMOR, + HORSE_BREATHE, + HORSE_DEATH, + HORSE_GALLOP, + HORSE_HIT, + HORSE_IDLE, + HORSE_JUMP, + HORSE_LAND, + HORSE_SADDLE, + HORSE_SOFT, + HORSE_WOOD, + DONKEY_ANGRY, + DONKEY_DEATH, + DONKEY_HIT, + DONKEY_IDLE, + HORSE_SKELETON_DEATH, + HORSE_SKELETON_HIT, + HORSE_SKELETON_IDLE, + HORSE_ZOMBIE_DEATH, + HORSE_ZOMBIE_HIT, + HORSE_ZOMBIE_IDLE, + // Villager + VILLAGER_DEATH, + VILLAGER_HAGGLE, + VILLAGER_HIT, + VILLAGER_IDLE, + VILLAGER_NO, + VILLAGER_YES, +} diff --git a/src/main/java/org/bukkit/Statistic.java b/src/main/java/org/bukkit/Statistic.java new file mode 100644 index 0000000..57df72b --- /dev/null +++ b/src/main/java/org/bukkit/Statistic.java @@ -0,0 +1,108 @@ +package org.bukkit; + +/** + * Represents a countable statistic, which is tracked by the server. + */ +public enum Statistic { + DAMAGE_DEALT, + DAMAGE_TAKEN, + DEATHS, + MOB_KILLS, + PLAYER_KILLS, + FISH_CAUGHT, + ANIMALS_BRED, + TREASURE_FISHED, + JUNK_FISHED, + LEAVE_GAME, + JUMP, + DROP, + PLAY_ONE_TICK, + WALK_ONE_CM, + SWIM_ONE_CM, + FALL_ONE_CM, + CLIMB_ONE_CM, + FLY_ONE_CM, + DIVE_ONE_CM, + MINECART_ONE_CM, + BOAT_ONE_CM, + PIG_ONE_CM, + HORSE_ONE_CM, + MINE_BLOCK(Type.BLOCK), + USE_ITEM(Type.ITEM), + BREAK_ITEM(Type.ITEM), + CRAFT_ITEM(Type.ITEM), + KILL_ENTITY(Type.ENTITY), + ENTITY_KILLED_BY(Type.ENTITY); + + private final Type type; + + private Statistic() { + this(Type.UNTYPED); + } + + private Statistic(Type type) { + this.type = type; + } + + /** + * Gets the type of this statistic. + * + * @return the type of this statistic + */ + public Type getType() { + return type; + } + + /** + * Checks if this is a substatistic. + *

          + * A substatistic exists en masse for each block, item, or entitytype, depending on + * {@link #getType()}. + *

          + * This is a redundant method and equivalent to checking + * getType() != Type.UNTYPED + * + * @return true if this is a substatistic + */ + public boolean isSubstatistic() { + return type != Type.UNTYPED; + } + + /** + * Checks if this is a substatistic dealing with blocks. + *

          + * This is a redundant method and equivalent to checking + * getType() == Type.BLOCK + * + * @return true if this deals with blocks + */ + public boolean isBlock() { + return type == Type.BLOCK; + } + + /** + * The type of statistic. + * + */ + public enum Type { + /** + * Statistics of this type do not require a qualifier. + */ + UNTYPED, + + /** + * Statistics of this type require an Item Material qualifier. + */ + ITEM, + + /** + * Statistics of this type require a Block Material qualifier. + */ + BLOCK, + + /** + * Statistics of this type require an EntityType qualifier. + */ + ENTITY; + } +} diff --git a/src/main/java/org/bukkit/TravelAgent.java b/src/main/java/org/bukkit/TravelAgent.java new file mode 100644 index 0000000..2dfeffa --- /dev/null +++ b/src/main/java/org/bukkit/TravelAgent.java @@ -0,0 +1,94 @@ +package org.bukkit; + +/** + * The Travel Agent handles the creation and the research of Nether and End + * portals when Entities try to use one. + *

          + * It is used in {@link org.bukkit.event.entity.EntityPortalEvent} and in + * {@link org.bukkit.event.player.PlayerPortalEvent} to help developers + * reproduce and/or modify Vanilla behaviour. + */ +public interface TravelAgent { + + /** + * Set the Block radius to search in for available portals. + * + * @param radius the radius in which to search for a portal from the + * location + * @return this travel agent + */ + public TravelAgent setSearchRadius(int radius); + + /** + * Gets the search radius value for finding an available portal. + * + * @return the currently set search radius + */ + public int getSearchRadius(); + + /** + * Sets the maximum radius from the given location to create a portal. + * + * @param radius the radius in which to create a portal from the location + * @return this travel agent + */ + public TravelAgent setCreationRadius(int radius); + + /** + * Gets the maximum radius from the given location to create a portal. + * + * @return the currently set creation radius + */ + public int getCreationRadius(); + + /** + * Returns whether the TravelAgent will attempt to create a destination + * portal or not. + * + * @return whether the TravelAgent should create a destination portal or + * not + */ + public boolean getCanCreatePortal(); + + /** + * Sets whether the TravelAgent should attempt to create a destination + * portal or not. + * + * @param create Sets whether the TravelAgent should create a destination + * portal or not + */ + public void setCanCreatePortal(boolean create); + + /** + * Attempt to find a portal near the given location, if a portal is not + * found it will attempt to create one. + * + * @param location the location where the search for a portal should begin + * @return the location of a portal which has been found or returns the + * location passed to the method if unsuccessful + * @see #createPortal(Location) + */ + public Location findOrCreate(Location location); + + /** + * Attempt to find a portal near the given location. + * + * @param location the desired location of the portal + * @return the location of the nearest portal to the location + */ + public Location findPortal(Location location); + + /** + * Attempt to create a portal near the given location. + *

          + * In the case of a Nether portal teleportation, this will attempt to + * create a Nether portal. + *

          + * In the case of an Ender portal teleportation, this will (re-)create the + * obsidian platform and clean blocks above it. + * + * @param location the desired location of the portal + * @return true if a portal was successfully created + */ + public boolean createPortal(Location location); +} diff --git a/src/main/java/org/bukkit/TreeSpecies.java b/src/main/java/org/bukkit/TreeSpecies.java new file mode 100644 index 0000000..f29062a --- /dev/null +++ b/src/main/java/org/bukkit/TreeSpecies.java @@ -0,0 +1,74 @@ +package org.bukkit; + +import java.util.Map; + +import com.google.common.collect.Maps; + +/** + * Represents the different species of trees regardless of size. + */ +public enum TreeSpecies { + + /** + * Represents the common tree species. + */ + GENERIC(0x0), + /** + * Represents the darker barked/leaved tree species. + */ + REDWOOD(0x1), + /** + * Represents birches. + */ + BIRCH(0x2), + /** + * Represents jungle trees. + */ + JUNGLE(0x3), + /** + * Represents acacia trees. + */ + ACACIA(0x4), + /** + * Represents dark oak trees. + */ + DARK_OAK(0x5), + ; + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + private TreeSpecies(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this species + * + * @return A byte containing the data value of this tree species + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the TreeSpecies with the given data value + * + * @param data Data value to fetch + * @return The {@link TreeSpecies} representing the given value, or null + * if it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static TreeSpecies getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (TreeSpecies species : values()) { + BY_DATA.put(species.data, species); + } + } +} diff --git a/src/main/java/org/bukkit/TreeType.java b/src/main/java/org/bukkit/TreeType.java new file mode 100644 index 0000000..5a5c4d9 --- /dev/null +++ b/src/main/java/org/bukkit/TreeType.java @@ -0,0 +1,72 @@ +package org.bukkit; + +/** + * Tree and organic structure types. + */ +public enum TreeType { + + /** + * Regular tree, no branches + */ + TREE, + /** + * Regular tree, extra tall with branches + */ + BIG_TREE, + /** + * Redwood tree, shaped like a pine tree + */ + REDWOOD, + /** + * Tall redwood tree with just a few leaves at the top + */ + TALL_REDWOOD, + /** + * Birch tree + */ + BIRCH, + /** + * Standard jungle tree; 4 blocks wide and tall + */ + JUNGLE, + /** + * Smaller jungle tree; 1 block wide + */ + SMALL_JUNGLE, + /** + * Jungle tree with cocoa plants; 1 block wide + */ + COCOA_TREE, + /** + * Small bush that grows in the jungle + */ + JUNGLE_BUSH, + /** + * Big red mushroom; short and fat + */ + RED_MUSHROOM, + /** + * Big brown mushroom; tall and umbrella-like + */ + BROWN_MUSHROOM, + /** + * Swamp tree (regular with vines on the side) + */ + SWAMP, + /** + * Acacia tree. + */ + ACACIA, + /** + * Dark Oak tree. + */ + DARK_OAK, + /** + * Mega redwood tree; 4 blocks wide and tall + */ + MEGA_REDWOOD, + /** + * Tall birch tree + */ + TALL_BIRCH, +} diff --git a/src/main/java/org/bukkit/UnsafeValues.java b/src/main/java/org/bukkit/UnsafeValues.java new file mode 100644 index 0000000..fc8a179 --- /dev/null +++ b/src/main/java/org/bukkit/UnsafeValues.java @@ -0,0 +1,33 @@ +package org.bukkit; + +import java.util.List; + +import org.bukkit.inventory.ItemStack; + +/** + * This interface provides value conversions that may be specific to a + * runtime, or have arbitrary meaning (read: magic values). + *

          + * Their existence and behavior is not guaranteed across future versions. They + * may be poorly named, throw exceptions, have misleading parameters, or any + * other bad programming practice. + *

          + * This interface is unsupported and only for internal use. + * + * @deprecated Unsupported & internal use only + */ +@Deprecated +public interface UnsafeValues { + + Material getMaterialFromInternalName(String name); + + List tabCompleteInternalMaterialName(String token, List completions); + + ItemStack modifyItemStack(ItemStack stack, String arguments); + + Statistic getStatisticFromInternalName(String name); + + Achievement getAchievementFromInternalName(String name); + + List tabCompleteInternalStatisticOrAchievementName(String token, List completions); +} diff --git a/src/main/java/org/bukkit/Utility.java b/src/main/java/org/bukkit/Utility.java new file mode 100644 index 0000000..da66853 --- /dev/null +++ b/src/main/java/org/bukkit/Utility.java @@ -0,0 +1,18 @@ +package org.bukkit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation indicates a method (and sometimes constructor) will chain + * its internal operations. + *

          + * This is solely meant for identifying methods that don't need to be + * overridden / handled manually. + */ +@Target({ElementType.CONSTRUCTOR, ElementType.METHOD}) +@Retention(RetentionPolicy.SOURCE) +public @interface Utility { +} diff --git a/src/main/java/org/bukkit/Warning.java b/src/main/java/org/bukkit/Warning.java new file mode 100644 index 0000000..6a2a3b0 --- /dev/null +++ b/src/main/java/org/bukkit/Warning.java @@ -0,0 +1,109 @@ +package org.bukkit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.Map; + +import com.google.common.collect.ImmutableMap; + +/** + * This designates the warning state for a specific item. + *

          + * When the server settings dictate 'default' warnings, warnings are printed + * if the {@link #value()} is true. + */ +@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Warning { + + /** + * This represents the states that server verbose for warnings may be. + */ + public enum WarningState { + + /** + * Indicates all warnings should be printed for deprecated items. + */ + ON, + /** + * Indicates no warnings should be printed for deprecated items. + */ + OFF, + /** + * Indicates each warning would default to the configured {@link + * Warning} annotation, or always if annotation not found. + */ + DEFAULT; + + private static final Map values = ImmutableMap.builder() + .put("off", OFF) + .put("false", OFF) + .put("f", OFF) + .put("no", OFF) + .put("n", OFF) + .put("on", ON) + .put("true", ON) + .put("t", ON) + .put("yes", ON) + .put("y", ON) + .put("", DEFAULT) + .put("d", DEFAULT) + .put("default", DEFAULT) + .build(); + + /** + * This method checks the provided warning should be printed for this + * state + * + * @param warning The warning annotation added to a deprecated item + * @return

            + *
          • ON is always True + *
          • OFF is always false + *
          • DEFAULT is false if and only if annotation is not null and + * specifies false for {@link Warning#value()}, true otherwise. + *
          + */ + public boolean printFor(Warning warning) { + if (this == DEFAULT) { + return warning == null || warning.value(); + } + return this == ON; + } + + /** + * This method returns the corresponding warning state for the given + * string value. + * + * @param value The string value to check + * @return {@link #DEFAULT} if not found, or the respective + * WarningState + */ + public static WarningState value(final String value) { + if (value == null) { + return DEFAULT; + } + WarningState state = values.get(value.toLowerCase()); + if (state == null) { + return DEFAULT; + } + return state; + } + } + + /** + * This sets if the deprecation warnings when registering events gets + * printed when the setting is in the default state. + * + * @return false normally, or true to encourage warning printout + */ + boolean value() default false; + + /** + * This can provide detailed information on why the event is deprecated. + * + * @return The reason an event is deprecated + */ + String reason() default ""; +} diff --git a/src/main/java/org/bukkit/WeatherType.java b/src/main/java/org/bukkit/WeatherType.java new file mode 100644 index 0000000..36b993f --- /dev/null +++ b/src/main/java/org/bukkit/WeatherType.java @@ -0,0 +1,17 @@ +package org.bukkit; + +/** + * An enum of all current weather types + */ +public enum WeatherType { + + /** + * Raining or snowing depending on biome. + */ + DOWNFALL, + /** + * Clear weather, clouds but no rain. + */ + CLEAR, + ; +} diff --git a/src/main/java/org/bukkit/World.java b/src/main/java/org/bukkit/World.java new file mode 100644 index 0000000..9bf2c41 --- /dev/null +++ b/src/main/java/org/bukkit/World.java @@ -0,0 +1,1212 @@ +package org.bukkit; + +import java.io.File; +import org.bukkit.generator.ChunkGenerator; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.block.Biome; +import org.bukkit.block.Block; +import org.bukkit.entity.*; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.Metadatable; +import org.bukkit.plugin.messaging.PluginMessageRecipient; +import org.bukkit.util.Vector; + +/** + * Represents a world, which may contain entities, chunks and blocks + */ +public interface World extends PluginMessageRecipient, Metadatable { + + /** + * Gets the {@link Block} at the given coordinates + * + * @param x X-coordinate of the block + * @param y Y-coordinate of the block + * @param z Z-coordinate of the block + * @return Block at the given coordinates + * @see #getBlockTypeIdAt(int, int, int) Returns the current type ID of + * the block + */ + public Block getBlockAt(int x, int y, int z); + + /** + * Gets the {@link Block} at the given {@link Location} + * + * @param location Location of the block + * @return Block at the given location + * @see #getBlockTypeIdAt(org.bukkit.Location) Returns the current type ID + * of the block + */ + public Block getBlockAt(Location location); + + /** + * Gets the block type ID at the given coordinates + * + * @param x X-coordinate of the block + * @param y Y-coordinate of the block + * @param z Z-coordinate of the block + * @return Type ID of the block at the given coordinates + * @see #getBlockAt(int, int, int) Returns a live Block object at the + * given location + * @deprecated Magic value + */ + @Deprecated + public int getBlockTypeIdAt(int x, int y, int z); + + /** + * Gets the block type ID at the given {@link Location} + * + * @param location Location of the block + * @return Type ID of the block at the given location + * @see #getBlockAt(org.bukkit.Location) Returns a live Block object at + * the given location + * @deprecated Magic value + */ + @Deprecated + public int getBlockTypeIdAt(Location location); + + /** + * Gets the highest non-air coordinate at the given coordinates + * + * @param x X-coordinate of the blocks + * @param z Z-coordinate of the blocks + * @return Y-coordinate of the highest non-air block + */ + public int getHighestBlockYAt(int x, int z); + + /** + * Gets the highest non-air coordinate at the given {@link Location} + * + * @param location Location of the blocks + * @return Y-coordinate of the highest non-air block + */ + public int getHighestBlockYAt(Location location); + + /** + * Gets the highest non-empty block at the given coordinates + * + * @param x X-coordinate of the block + * @param z Z-coordinate of the block + * @return Highest non-empty block + */ + public Block getHighestBlockAt(int x, int z); + + /** + * Gets the highest non-empty block at the given coordinates + * + * @param location Coordinates to get the highest block + * @return Highest non-empty block + */ + public Block getHighestBlockAt(Location location); + + /** + * Gets the {@link Chunk} at the given coordinates + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return Chunk at the given coordinates + */ + public Chunk getChunkAt(int x, int z); + + /** + * Gets the {@link Chunk} at the given {@link Location} + * + * @param location Location of the chunk + * @return Chunk at the given location + */ + public Chunk getChunkAt(Location location); + + /** + * Gets the {@link Chunk} that contains the given {@link Block} + * + * @param block Block to get the containing chunk from + * @return The chunk that contains the given block + */ + public Chunk getChunkAt(Block block); + + /** + * Checks if the specified {@link Chunk} is loaded + * + * @param chunk The chunk to check + * @return true if the chunk is loaded, otherwise false + */ + public boolean isChunkLoaded(Chunk chunk); + + /** + * Gets an array of all loaded {@link Chunk}s + * + * @return Chunk[] containing all loaded chunks + */ + public Chunk[] getLoadedChunks(); + + /** + * Loads the specified {@link Chunk} + * + * @param chunk The chunk to load + */ + public void loadChunk(Chunk chunk); + + /** + * Checks if the {@link Chunk} at the specified coordinates is loaded + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return true if the chunk is loaded, otherwise false + */ + public boolean isChunkLoaded(int x, int z); + + /** + * Checks if the {@link Chunk} at the specified coordinates is loaded and + * in use by one or more players + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return true if the chunk is loaded and in use by one or more players, + * otherwise false + */ + public boolean isChunkInUse(int x, int z); + + /** + * Loads the {@link Chunk} at the specified coordinates + *

          + * If the chunk does not exist, it will be generated. + *

          + * This method is analogous to {@link #loadChunk(int, int, boolean)} where + * generate is true. + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + */ + public void loadChunk(int x, int z); + + /** + * Loads the {@link Chunk} at the specified coordinates + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @param generate Whether or not to generate a chunk if it doesn't + * already exist + * @return true if the chunk has loaded successfully, otherwise false + */ + public boolean loadChunk(int x, int z, boolean generate); + + /** + * Safely unloads and saves the {@link Chunk} at the specified coordinates + *

          + * This method is analogous to {@link #unloadChunk(int, int, boolean, + * boolean)} where safe and saveis true + * + * @param chunk the chunk to unload + * @return true if the chunk has unloaded successfully, otherwise false + */ + public boolean unloadChunk(Chunk chunk); + + /** + * Safely unloads and saves the {@link Chunk} at the specified coordinates + *

          + * This method is analogous to {@link #unloadChunk(int, int, boolean, + * boolean)} where safe and saveis true + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return true if the chunk has unloaded successfully, otherwise false + */ + public boolean unloadChunk(int x, int z); + + /** + * Safely unloads and optionally saves the {@link Chunk} at the specified + * coordinates + *

          + * This method is analogous to {@link #unloadChunk(int, int, boolean, + * boolean)} where save is true + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @param save Whether or not to save the chunk + * @return true if the chunk has unloaded successfully, otherwise false + */ + public boolean unloadChunk(int x, int z, boolean save); + + /** + * Unloads and optionally saves the {@link Chunk} at the specified + * coordinates + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @param save Controls whether the chunk is saved + * @param safe Controls whether to unload the chunk when players are + * nearby + * @return true if the chunk has unloaded successfully, otherwise false + */ + public boolean unloadChunk(int x, int z, boolean save, boolean safe); + + /** + * Safely queues the {@link Chunk} at the specified coordinates for + * unloading + *

          + * This method is analogous to {@link #unloadChunkRequest(int, int, + * boolean)} where safe is true + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return true is the queue attempt was successful, otherwise false + */ + public boolean unloadChunkRequest(int x, int z); + + /** + * Queues the {@link Chunk} at the specified coordinates for unloading + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @param safe Controls whether to queue the chunk when players are nearby + * @return Whether the chunk was actually queued + */ + public boolean unloadChunkRequest(int x, int z, boolean safe); + + /** + * Regenerates the {@link Chunk} at the specified coordinates + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return Whether the chunk was actually regenerated + */ + public boolean regenerateChunk(int x, int z); + + /** + * Resends the {@link Chunk} to all clients + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return Whether the chunk was actually refreshed + */ + public boolean refreshChunk(int x, int z); + + /** + * Drops an item at the specified {@link Location} + * + * @param location Location to drop the item + * @param item ItemStack to drop + * @return ItemDrop entity created as a result of this method + */ + public Item dropItem(Location location, ItemStack item); + + /** + * Drops an item at the specified {@link Location} with a random offset + * + * @param location Location to drop the item + * @param item ItemStack to drop + * @return ItemDrop entity created as a result of this method + */ + public Item dropItemNaturally(Location location, ItemStack item); + + /** + * Creates an {@link Arrow} entity at the given {@link Location} + * + * @param location Location to spawn the arrow + * @param direction Direction to shoot the arrow in + * @param speed Speed of the arrow. A recommend speed is 0.6 + * @param spread Spread of the arrow. A recommend spread is 12 + * @return Arrow entity spawned as a result of this method + */ + public Arrow spawnArrow(Location location, Vector direction, float speed, float spread); + + /** + * Creates a tree at the given {@link Location} + * + * @param location Location to spawn the tree + * @param type Type of the tree to create + * @return true if the tree was created successfully, otherwise false + */ + public boolean generateTree(Location location, TreeType type); + + /** + * Creates a tree at the given {@link Location} + * + * @param loc Location to spawn the tree + * @param type Type of the tree to create + * @param delegate A class to call for each block changed as a result of + * this method + * @return true if the tree was created successfully, otherwise false + */ + public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate); + + /** + * Creates a entity at the given {@link Location} + * + * @param loc The location to spawn the entity + * @param type The entity to spawn + * @return Resulting Entity of this method, or null if it was unsuccessful + */ + public Entity spawnEntity(Location loc, EntityType type); + + /** + * Creates a creature at the given {@link Location} + * + * @param loc The location to spawn the creature + * @param type The creature to spawn + * @return Resulting LivingEntity of this method, or null if it was + * unsuccessful + * @deprecated Has issues spawning non LivingEntities. Use {@link + * #spawnEntity(Location, EntityType) spawnEntity} instead. + */ + @Deprecated + public LivingEntity spawnCreature(Location loc, EntityType type); + + /** + * Creates a creature at the given {@link Location} + * + * @param loc The location to spawn the creature + * @param type The creature to spawn + * @return Resulting LivingEntity of this method, or null if it was + * unsuccessful + */ + @Deprecated + public LivingEntity spawnCreature(Location loc, CreatureType type); + + /** + * Strikes lightning at the given {@link Location} + * + * @param loc The location to strike lightning + * @return The lightning entity. + */ + public LightningStrike strikeLightning(Location loc); + + /** + * Strikes lightning at the given {@link Location} without doing damage + * + * @param loc The location to strike lightning + * @return The lightning entity. + */ + public LightningStrike strikeLightningEffect(Location loc); + + /** + * Get a list of all entities in this World + * + * @return A List of all Entities currently residing in this world + */ + public List getEntities(); + + /** + * Get a list of all living entities in this World + * + * @return A List of all LivingEntities currently residing in this world + */ + public List getLivingEntities(); + + /** + * Get a collection of all entities in this World matching the given + * class/interface + * + * @param classes The classes representing the types of entity to match + * @return A List of all Entities currently residing in this world that + * match the given class/interface + */ + @Deprecated + public Collection getEntitiesByClass(Class... classes); + + /** + * Get a collection of all entities in this World matching the given + * class/interface + * + * @param cls The class representing the type of entity to match + * @return A List of all Entities currently residing in this world that + * match the given class/interface + */ + public Collection getEntitiesByClass(Class cls); + + /** + * Get a collection of all entities in this World matching any of the + * given classes/interfaces + * + * @param classes The classes representing the types of entity to match + * @return A List of all Entities currently residing in this world that + * match one or more of the given classes/interfaces + */ + public Collection getEntitiesByClasses(Class... classes); + + /** + * Get a list of all players in this World + * + * @return A list of all Players currently residing in this world + */ + public List getPlayers(); + + /** + * Gets the unique name of this world + * + * @return Name of this world + */ + public String getName(); + + /** + * Gets the Unique ID of this world + * + * @return Unique ID of this world. + */ + public UUID getUID(); + + /** + * Gets the default spawn {@link Location} of this world + * + * @return The spawn location of this world + */ + public Location getSpawnLocation(); + + /** + * Sets the spawn location of the world + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return True if it was successfully set. + */ + public boolean setSpawnLocation(int x, int y, int z); + + /** + * Gets the relative in-game time of this world. + *

          + * The relative time is analogous to hours * 1000 + * + * @return The current relative time + * @see #getFullTime() Returns an absolute time of this world + */ + public long getTime(); + + /** + * Sets the relative in-game time on the server. + *

          + * The relative time is analogous to hours * 1000 + *

          + * Note that setting the relative time below the current relative time + * will actually move the clock forward a day. If you require to rewind + * time, please see {@link #setFullTime(long)} + * + * @param time The new relative time to set the in-game time to (in + * hours*1000) + * @see #setFullTime(long) Sets the absolute time of this world + */ + public void setTime(long time); + + /** + * Gets the full in-game time on this world + * + * @return The current absolute time + * @see #getTime() Returns a relative time of this world + */ + public long getFullTime(); + + /** + * Sets the in-game time on the server + *

          + * Note that this sets the full time of the world, which may cause adverse + * effects such as breaking redstone clocks and any scheduled events + * + * @param time The new absolute time to set this world to + * @see #setTime(long) Sets the relative time of this world + */ + public void setFullTime(long time); + + /** + * Returns whether the world has an ongoing storm. + * + * @return Whether there is an ongoing storm + */ + public boolean hasStorm(); + + /** + * Set whether there is a storm. A duration will be set for the new + * current conditions. + * + * @param hasStorm Whether there is rain and snow + */ + public void setStorm(boolean hasStorm); + + /** + * Get the remaining time in ticks of the current conditions. + * + * @return Time in ticks + */ + public int getWeatherDuration(); + + /** + * Set the remaining time in ticks of the current conditions. + * + * @param duration Time in ticks + */ + public void setWeatherDuration(int duration); + + /** + * Returns whether there is thunder. + * + * @return Whether there is thunder + */ + public boolean isThundering(); + + /** + * Set whether it is thundering. + * + * @param thundering Whether it is thundering + */ + public void setThundering(boolean thundering); + + /** + * Get the thundering duration. + * + * @return Duration in ticks + */ + public int getThunderDuration(); + + /** + * Set the thundering duration. + * + * @param duration Duration in ticks + */ + public void setThunderDuration(int duration); + + /** + * Creates explosion at given coordinates with given power + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param power The power of explosion, where 4F is TNT + * @return false if explosion was canceled, otherwise true + */ + public boolean createExplosion(double x, double y, double z, float power); + + /** + * Creates explosion at given coordinates with given power and optionally + * setting blocks on fire. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param power The power of explosion, where 4F is TNT + * @param setFire Whether or not to set blocks on fire + * @return false if explosion was canceled, otherwise true + */ + public boolean createExplosion(double x, double y, double z, float power, boolean setFire); + + /** + * Creates explosion at given coordinates with given power and optionally + * setting blocks on fire or breaking blocks. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param power The power of explosion, where 4F is TNT + * @param setFire Whether or not to set blocks on fire + * @param breakBlocks Whether or not to have blocks be destroyed + * @return false if explosion was canceled, otherwise true + */ + public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks); + + /** + * Creates explosion at given coordinates with given power + * + * @param loc Location to blow up + * @param power The power of explosion, where 4F is TNT + * @return false if explosion was canceled, otherwise true + */ + public boolean createExplosion(Location loc, float power); + + /** + * Creates explosion at given coordinates with given power and optionally + * setting blocks on fire. + * + * @param loc Location to blow up + * @param power The power of explosion, where 4F is TNT + * @param setFire Whether or not to set blocks on fire + * @return false if explosion was canceled, otherwise true + */ + public boolean createExplosion(Location loc, float power, boolean setFire); + + /** + * Gets the {@link Environment} type of this world + * + * @return This worlds Environment type + */ + public Environment getEnvironment(); + + /** + * Gets the Seed for this world. + * + * @return This worlds Seed + */ + public long getSeed(); + + /** + * Gets the current PVP setting for this world. + * + * @return True if PVP is enabled + */ + public boolean getPVP(); + + /** + * Sets the PVP setting for this world. + * + * @param pvp True/False whether PVP should be Enabled. + */ + public void setPVP(boolean pvp); + + /** + * Gets the chunk generator for this world + * + * @return ChunkGenerator associated with this world + */ + public ChunkGenerator getGenerator(); + + /** + * Saves world to disk + */ + public void save(); + + /** + * Gets a list of all applied {@link BlockPopulator}s for this World + * + * @return List containing any or none BlockPopulators + */ + public List getPopulators(); + + /** + * Spawn an entity of a specific class at the given {@link Location} + * + * @param location the {@link Location} to spawn the entity at + * @param clazz the class of the {@link Entity} to spawn + * @param the class of the {@link Entity} to spawn + * @return an instance of the spawned {@link Entity} + * @throws IllegalArgumentException if either parameter is null or the + * {@link Entity} requested cannot be spawned + */ + public T spawn(Location location, Class clazz) throws IllegalArgumentException; + + /** + * Spawn a {@link FallingBlock} entity at the given {@link Location} of + * the specified {@link Material}. The material dictates what is falling. + * When the FallingBlock hits the ground, it will place that block. + *

          + * The Material must be a block type, check with {@link Material#isBlock() + * material.isBlock()}. The Material may not be air. + * + * @param location The {@link Location} to spawn the FallingBlock + * @param material The block {@link Material} type + * @param data The block data + * @return The spawned {@link FallingBlock} instance + * @throws IllegalArgumentException if {@link Location} or {@link + * Material} are null or {@link Material} is not a block + * @deprecated Magic value + */ + @Deprecated + public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException; + + /** + * Spawn a {@link FallingBlock} entity at the given {@link Location} of + * the specified blockId (converted to {@link Material}) + * + * @param location The {@link Location} to spawn the FallingBlock + * @param blockId The id of the intended material + * @param blockData The block data + * @return The spawned FallingBlock instance + * @throws IllegalArgumentException if location is null, or blockId is + * invalid + * @see #spawnFallingBlock(org.bukkit.Location, org.bukkit.Material, byte) + * @deprecated Magic value + */ + @Deprecated + public FallingBlock spawnFallingBlock(Location location, int blockId, byte blockData) throws IllegalArgumentException; + + /** + * Plays an effect to all players within a default radius around a given + * location. + * + * @param location the {@link Location} around which players must be to + * hear the sound + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + */ + public void playEffect(Location location, Effect effect, int data); + + /** + * Plays an effect to all players within a given radius around a location. + * + * @param location the {@link Location} around which players must be to + * hear the effect + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + * @param radius the radius around the location + */ + public void playEffect(Location location, Effect effect, int data, int radius); + + /** + * Plays an effect to all players within a default radius around a given + * location. + * + * @param location the {@link Location} around which players must be to + * hear the sound + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + */ + public void playEffect(Location location, Effect effect, T data); + + /** + * Plays an effect to all players within a given radius around a location. + * + * @param location the {@link Location} around which players must be to + * hear the effect + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + * @param radius the radius around the location + */ + public void playEffect(Location location, Effect effect, T data, int radius); + + /** + * Get empty chunk snapshot (equivalent to all air blocks), optionally + * including valid biome data. Used for representing an ungenerated chunk, + * or for fetching only biome data without loading a chunk. + * + * @param x - chunk x coordinate + * @param z - chunk z coordinate + * @param includeBiome - if true, snapshot includes per-coordinate biome + * type + * @param includeBiomeTempRain - if true, snapshot includes per-coordinate + * raw biome temperature and rainfall + * @return The empty snapshot. + */ + public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTempRain); + + /** + * Sets the spawn flags for this. + * + * @param allowMonsters - if true, monsters are allowed to spawn in this + * world. + * @param allowAnimals - if true, animals are allowed to spawn in this + * world. + */ + public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals); + + /** + * Gets whether animals can spawn in this world. + * + * @return whether animals can spawn in this world. + */ + public boolean getAllowAnimals(); + + /** + * Gets whether monsters can spawn in this world. + * + * @return whether monsters can spawn in this world. + */ + public boolean getAllowMonsters(); + + /** + * Gets the biome for the given block coordinates. + * + * @param x X coordinate of the block + * @param z Z coordinate of the block + * @return Biome of the requested block + */ + Biome getBiome(int x, int z); + + /** + * Sets the biome for the given block coordinates + * + * @param x X coordinate of the block + * @param z Z coordinate of the block + * @param bio new Biome type for this block + */ + void setBiome(int x, int z, Biome bio); + + /** + * Gets the temperature for the given block coordinates. + *

          + * It is safe to run this method when the block does not exist, it will + * not create the block. + * + * @param x X coordinate of the block + * @param z Z coordinate of the block + * @return Temperature of the requested block + */ + public double getTemperature(int x, int z); + + /** + * Gets the humidity for the given block coordinates. + *

          + * It is safe to run this method when the block does not exist, it will + * not create the block. + * + * @param x X coordinate of the block + * @param z Z coordinate of the block + * @return Humidity of the requested block + */ + public double getHumidity(int x, int z); + + /** + * Gets the maximum height of this world. + *

          + * If the max height is 100, there are only blocks from y=0 to y=99. + * + * @return Maximum height of the world + */ + public int getMaxHeight(); + + /** + * Gets the sea level for this world. + *

          + * This is often half of {@link #getMaxHeight()} + * + * @return Sea level + */ + public int getSeaLevel(); + + /** + * Gets whether the world's spawn area should be kept loaded into memory + * or not. + * + * @return true if the world's spawn area will be kept loaded into memory. + */ + public boolean getKeepSpawnInMemory(); + + /** + * Sets whether the world's spawn area should be kept loaded into memory + * or not. + * + * @param keepLoaded if true then the world's spawn area will be kept + * loaded into memory. + */ + public void setKeepSpawnInMemory(boolean keepLoaded); + + /** + * Gets whether or not the world will automatically save + * + * @return true if the world will automatically save, otherwise false + */ + public boolean isAutoSave(); + + /** + * Sets whether or not the world will automatically save + * + * @param value true if the world should automatically save, otherwise + * false + */ + public void setAutoSave(boolean value); + + /** + * Sets the Difficulty of the world. + * + * @param difficulty the new difficulty you want to set the world to + */ + public void setDifficulty(Difficulty difficulty); + + /** + * Gets the Difficulty of the world. + * + * @return The difficulty of the world. + */ + public Difficulty getDifficulty(); + + /** + * Gets the folder of this world on disk. + * + * @return The folder of this world. + */ + public File getWorldFolder(); + + /** + * Gets the type of this world. + * + * @return Type of this world. + */ + public WorldType getWorldType(); + + /** + * Gets whether or not structures are being generated. + * + * @return True if structures are being generated. + */ + public boolean canGenerateStructures(); + + /** + * Gets the world's ticks per animal spawns value + *

          + * This value determines how many ticks there are between attempts to + * spawn animals. + *

          + * Example Usage: + *

            + *
          • A value of 1 will mean the server will attempt to spawn animals in + * this world every tick. + *
          • A value of 400 will mean the server will attempt to spawn animals + * in this world every 400th tick. + *
          • A value below 0 will be reset back to Minecraft's default. + *
          + *

          + * Note: + * If set to 0, animal spawning will be disabled for this world. We + * recommend using {@link #setSpawnFlags(boolean, boolean)} to control + * this instead. + *

          + * Minecraft default: 400. + * + * @return The world's ticks per animal spawns value + */ + public long getTicksPerAnimalSpawns(); + + /** + * Sets the world's ticks per animal spawns value + *

          + * This value determines how many ticks there are between attempts to + * spawn animals. + *

          + * Example Usage: + *

            + *
          • A value of 1 will mean the server will attempt to spawn animals in + * this world every tick. + *
          • A value of 400 will mean the server will attempt to spawn animals + * in this world every 400th tick. + *
          • A value below 0 will be reset back to Minecraft's default. + *
          + *

          + * Note: + * If set to 0, animal spawning will be disabled for this world. We + * recommend using {@link #setSpawnFlags(boolean, boolean)} to control + * this instead. + *

          + * Minecraft default: 400. + * + * @param ticksPerAnimalSpawns the ticks per animal spawns value you want + * to set the world to + */ + public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns); + + /** + * Gets the world's ticks per monster spawns value + *

          + * This value determines how many ticks there are between attempts to + * spawn monsters. + *

          + * Example Usage: + *

            + *
          • A value of 1 will mean the server will attempt to spawn monsters in + * this world every tick. + *
          • A value of 400 will mean the server will attempt to spawn monsters + * in this world every 400th tick. + *
          • A value below 0 will be reset back to Minecraft's default. + *
          + *

          + * Note: + * If set to 0, monsters spawning will be disabled for this world. We + * recommend using {@link #setSpawnFlags(boolean, boolean)} to control + * this instead. + *

          + * Minecraft default: 1. + * + * @return The world's ticks per monster spawns value + */ + public long getTicksPerMonsterSpawns(); + + /** + * Sets the world's ticks per monster spawns value + *

          + * This value determines how many ticks there are between attempts to + * spawn monsters. + *

          + * Example Usage: + *

            + *
          • A value of 1 will mean the server will attempt to spawn monsters in + * this world on every tick. + *
          • A value of 400 will mean the server will attempt to spawn monsters + * in this world every 400th tick. + *
          • A value below 0 will be reset back to Minecraft's default. + *
          + *

          + * Note: + * If set to 0, monsters spawning will be disabled for this world. We + * recommend using {@link #setSpawnFlags(boolean, boolean)} to control + * this instead. + *

          + * Minecraft default: 1. + * + * @param ticksPerMonsterSpawns the ticks per monster spawns value you + * want to set the world to + */ + public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns); + + /** + * Gets limit for number of monsters that can spawn in a chunk in this + * world + * + * @return The monster spawn limit + */ + int getMonsterSpawnLimit(); + + /** + * Sets the limit for number of monsters that can spawn in a chunk in this + * world + *

          + * Note: If set to a negative number the world will use the + * server-wide spawn limit instead. + */ + void setMonsterSpawnLimit(int limit); + + /** + * Gets the limit for number of animals that can spawn in a chunk in this + * world + * + * @return The animal spawn limit + */ + int getAnimalSpawnLimit(); + + /** + * Sets the limit for number of animals that can spawn in a chunk in this + * world + *

          + * Note: If set to a negative number the world will use the + * server-wide spawn limit instead. + */ + void setAnimalSpawnLimit(int limit); + + /** + * Gets the limit for number of water animals that can spawn in a chunk in + * this world + * + * @return The water animal spawn limit + */ + int getWaterAnimalSpawnLimit(); + + /** + * Sets the limit for number of water animals that can spawn in a chunk in + * this world + *

          + * Note: If set to a negative number the world will use the + * server-wide spawn limit instead. + */ + void setWaterAnimalSpawnLimit(int limit); + + /** + * Gets the limit for number of ambient mobs that can spawn in a chunk in + * this world + * + * @return The ambient spawn limit + */ + int getAmbientSpawnLimit(); + + /** + * Sets the limit for number of ambient mobs that can spawn in a chunk in + * this world + *

          + * Note: If set to a negative number the world will use the + * server-wide spawn limit instead. + */ + void setAmbientSpawnLimit(int limit); + + /** + * Play a Sound at the provided Location in the World + *

          + * This function will fail silently if Location or Sound are null. + * + * @param location The location to play the sound + * @param sound The sound to play + * @param volume The volume of the sound + * @param pitch The pitch of the sound + */ + void playSound(Location location, Sound sound, float volume, float pitch); + + /** + * Get existing rules + * + * @return An array of rules + */ + public String[] getGameRules(); + + /** + * Gets the current state of the specified rule + *

          + * Will return null if rule passed is null + * + * @param rule Rule to look up value of + * @return String value of rule + */ + public String getGameRuleValue(String rule); + + /** + * Set the specified gamerule to specified value. + *

          + * The rule may attempt to validate the value passed, will return true if + * value was set. + *

          + * If rule is null, the function will return false. + * + * @param rule Rule to set + * @param value Value to set rule to + * @return True if rule was set + */ + public boolean setGameRuleValue(String rule, String value); + + /** + * Checks if string is a valid game rule + * + * @param rule Rule to check + * @return True if rule exists + */ + public boolean isGameRule(String rule); + + /** + * Represents various map environment types that a world may be + */ + public enum Environment { + + /** + * Represents the "normal"/"surface world" map + */ + NORMAL(0), + /** + * Represents a nether based map ("hell") + */ + NETHER(-1), + /** + * Represents the "end" map + */ + THE_END(1); + + private final int id; + private static final Map lookup = new HashMap(); + + private Environment(int id) { + this.id = id; + } + + /** + * Gets the dimension ID of this environment + * + * @return dimension ID + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Get an environment by ID + * + * @param id The ID of the environment + * @return The environment + * @deprecated Magic value + */ + @Deprecated + public static Environment getEnvironment(int id) { + return lookup.get(id); + } + + static { + for (Environment env : values()) { + lookup.put(env.getId(), env); + } + } + } +} diff --git a/src/main/java/org/bukkit/WorldCreator.java b/src/main/java/org/bukkit/WorldCreator.java new file mode 100644 index 0000000..9a5afd2 --- /dev/null +++ b/src/main/java/org/bukkit/WorldCreator.java @@ -0,0 +1,295 @@ +package org.bukkit; + +import java.util.Random; +import org.bukkit.command.CommandSender; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; + +/** + * Represents various types of options that may be used to create a world. + */ +public class WorldCreator { + private final String name; + private long seed; + private World.Environment environment = World.Environment.NORMAL; + private ChunkGenerator generator = null; + private WorldType type = WorldType.NORMAL; + private boolean generateStructures = true; + + /** + * Creates an empty WorldCreationOptions for the given world name + * + * @param name Name of the world that will be created + */ + public WorldCreator(String name) { + if (name == null) { + throw new IllegalArgumentException("World name cannot be null"); + } + + this.name = name; + this.seed = (new Random()).nextLong(); + } + + /** + * Copies the options from the specified world + * + * @param world World to copy options from + * @return This object, for chaining + */ + public WorldCreator copy(World world) { + if (world == null) { + throw new IllegalArgumentException("World cannot be null"); + } + + seed = world.getSeed(); + environment = world.getEnvironment(); + generator = world.getGenerator(); + + return this; + } + + /** + * Copies the options from the specified {@link WorldCreator} + * + * @param creator World creator to copy options from + * @return This object, for chaining + */ + public WorldCreator copy(WorldCreator creator) { + if (creator == null) { + throw new IllegalArgumentException("Creator cannot be null"); + } + + seed = creator.seed(); + environment = creator.environment(); + generator = creator.generator(); + + return this; + } + + /** + * Gets the name of the world that is to be loaded or created. + * + * @return World name + */ + public String name() { + return name; + } + + /** + * Gets the seed that will be used to create this world + * + * @return World seed + */ + public long seed() { + return seed; + } + + /** + * Sets the seed that will be used to create this world + * + * @param seed World seed + * @return This object, for chaining + */ + public WorldCreator seed(long seed) { + this.seed = seed; + + return this; + } + + /** + * Gets the environment that will be used to create or load the world + * + * @return World environment + */ + public World.Environment environment() { + return environment; + } + + /** + * Sets the environment that will be used to create or load the world + * + * @param env World environment + * @return This object, for chaining + */ + public WorldCreator environment(World.Environment env) { + this.environment = env; + + return this; + } + + /** + * Gets the type of the world that will be created or loaded + * + * @return World type + */ + public WorldType type() { + return type; + } + + /** + * Sets the type of the world that will be created or loaded + * + * @param type World type + * @return This object, for chaining + */ + public WorldCreator type(WorldType type) { + this.type = type; + + return this; + } + + /** + * Gets the generator that will be used to create or load the world. + *

          + * This may be null, in which case the "natural" generator for this + * environment will be used. + * + * @return Chunk generator + */ + public ChunkGenerator generator() { + return generator; + } + + /** + * Sets the generator that will be used to create or load the world. + *

          + * This may be null, in which case the "natural" generator for this + * environment will be used. + * + * @param generator Chunk generator + * @return This object, for chaining + */ + public WorldCreator generator(ChunkGenerator generator) { + this.generator = generator; + + return this; + } + + /** + * Sets the generator that will be used to create or load the world. + *

          + * This may be null, in which case the "natural" generator for this + * environment will be used. + *

          + * If the generator cannot be found for the given name, the natural + * environment generator will be used instead and a warning will be + * printed to the console. + * + * @param generator Name of the generator to use, in "plugin:id" notation + * @return This object, for chaining + */ + public WorldCreator generator(String generator) { + this.generator = getGeneratorForName(name, generator, Bukkit.getConsoleSender()); + + return this; + } + + /** + * Sets the generator that will be used to create or load the world. + *

          + * This may be null, in which case the "natural" generator for this + * environment will be used. + *

          + * If the generator cannot be found for the given name, the natural + * environment generator will be used instead and a warning will be + * printed to the specified output + * + * @param generator Name of the generator to use, in "plugin:id" notation + * @param output {@link CommandSender} that will receive any error + * messages + * @return This object, for chaining + */ + public WorldCreator generator(String generator, CommandSender output) { + this.generator = getGeneratorForName(name, generator, output); + + return this; + } + + /** + * Sets whether or not worlds created or loaded with this creator will + * have structures. + * + * @param generate Whether to generate structures + * @return This object, for chaining + */ + public WorldCreator generateStructures(boolean generate) { + this.generateStructures = generate; + + return this; + } + + /** + * Gets whether or not structures will be generated in the world. + * + * @return True if structures will be generated + */ + public boolean generateStructures() { + return generateStructures; + } + + /** + * Creates a world with the specified options. + *

          + * If the world already exists, it will be loaded from disk and some + * options may be ignored. + * + * @return Newly created or loaded world + */ + public World createWorld() { + return Bukkit.createWorld(this); + } + + /** + * Creates a new {@link WorldCreator} for the given world name + * + * @param name Name of the world to load or create + * @return Resulting WorldCreator + */ + public static WorldCreator name(String name) { + return new WorldCreator(name); + } + + /** + * Attempts to get the {@link ChunkGenerator} with the given name. + *

          + * If the generator is not found, null will be returned and a message will + * be printed to the specified {@link CommandSender} explaining why. + *

          + * The name must be in the "plugin:id" notation, or optionally just + * "plugin", where "plugin" is the safe-name of a plugin and "id" is an + * optional unique identifier for the generator you wish to request from + * the plugin. + * + * @param world Name of the world this will be used for + * @param name Name of the generator to retrieve + * @param output Where to output if errors are present + * @return Resulting generator, or null + */ + public static ChunkGenerator getGeneratorForName(String world, String name, CommandSender output) { + ChunkGenerator result = null; + + if (world == null) { + throw new IllegalArgumentException("World name must be specified"); + } + + if (output == null) { + output = Bukkit.getConsoleSender(); + } + + if (name != null) { + String[] split = name.split(":", 2); + String id = (split.length > 1) ? split[1] : null; + Plugin plugin = Bukkit.getPluginManager().getPlugin(split[0]); + + if (plugin == null) { + output.sendMessage("Could not set generator for world '" + world + "': Plugin '" + split[0] + "' does not exist"); + } else if (!plugin.isEnabled()) { + output.sendMessage("Could not set generator for world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' is not enabled"); + } else { + result = plugin.getDefaultWorldGenerator(world, id); + } + } + + return result; + } +} diff --git a/src/main/java/org/bukkit/WorldType.java b/src/main/java/org/bukkit/WorldType.java new file mode 100644 index 0000000..201852d --- /dev/null +++ b/src/main/java/org/bukkit/WorldType.java @@ -0,0 +1,47 @@ +package org.bukkit; + +import com.google.common.collect.Maps; +import java.util.Map; + +/** + * Represents various types of worlds that may exist + */ +public enum WorldType { + NORMAL("DEFAULT"), + FLAT("FLAT"), + VERSION_1_1("DEFAULT_1_1"), + LARGE_BIOMES("LARGEBIOMES"), + AMPLIFIED("AMPLIFIED"); + + private final static Map BY_NAME = Maps.newHashMap(); + private final String name; + + private WorldType(String name) { + this.name = name; + } + + /** + * Gets the name of this WorldType + * + * @return Name of this type + */ + public String getName() { + return name; + } + + /** + * Gets a Worldtype by its name + * + * @param name Name of the WorldType to get + * @return Requested WorldType, or null if not found + */ + public static WorldType getByName(String name) { + return BY_NAME.get(name.toUpperCase()); + } + + static { + for (WorldType type : values()) { + BY_NAME.put(type.name, type); + } + } +} diff --git a/src/main/java/org/bukkit/block/Beacon.java b/src/main/java/org/bukkit/block/Beacon.java new file mode 100644 index 0000000..2de0583 --- /dev/null +++ b/src/main/java/org/bukkit/block/Beacon.java @@ -0,0 +1,9 @@ +package org.bukkit.block; + +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a beacon. + */ +public interface Beacon extends BlockState, InventoryHolder { +} diff --git a/src/main/java/org/bukkit/block/Biome.java b/src/main/java/org/bukkit/block/Biome.java new file mode 100644 index 0000000..8b902f4 --- /dev/null +++ b/src/main/java/org/bukkit/block/Biome.java @@ -0,0 +1,68 @@ +package org.bukkit.block; + +/** + * Holds all accepted Biomes in the default server + */ +public enum Biome { + SWAMPLAND, + FOREST, + TAIGA, + DESERT, + PLAINS, + HELL, + SKY, + OCEAN, + RIVER, + EXTREME_HILLS, + FROZEN_OCEAN, + FROZEN_RIVER, + ICE_PLAINS, + ICE_MOUNTAINS, + MUSHROOM_ISLAND, + MUSHROOM_SHORE, + BEACH, + DESERT_HILLS, + FOREST_HILLS, + TAIGA_HILLS, + SMALL_MOUNTAINS, + JUNGLE, + JUNGLE_HILLS, + JUNGLE_EDGE, + DEEP_OCEAN, + STONE_BEACH, + COLD_BEACH, + BIRCH_FOREST, + BIRCH_FOREST_HILLS, + ROOFED_FOREST, + COLD_TAIGA, + COLD_TAIGA_HILLS, + MEGA_TAIGA, + MEGA_TAIGA_HILLS, + EXTREME_HILLS_PLUS, + SAVANNA, + SAVANNA_PLATEAU, + MESA, + MESA_PLATEAU_FOREST, + MESA_PLATEAU, + SUNFLOWER_PLAINS, + DESERT_MOUNTAINS, + FLOWER_FOREST, + TAIGA_MOUNTAINS, + SWAMPLAND_MOUNTAINS, + ICE_PLAINS_SPIKES, + JUNGLE_MOUNTAINS, + JUNGLE_EDGE_MOUNTAINS, + COLD_TAIGA_MOUNTAINS, + SAVANNA_MOUNTAINS, + SAVANNA_PLATEAU_MOUNTAINS, + MESA_BRYCE, + MESA_PLATEAU_FOREST_MOUNTAINS, + MESA_PLATEAU_MOUNTAINS, + BIRCH_FOREST_MOUNTAINS, + BIRCH_FOREST_HILLS_MOUNTAINS, + ROOFED_FOREST_MOUNTAINS, + MEGA_SPRUCE_TAIGA, + EXTREME_HILLS_MOUNTAINS, + EXTREME_HILLS_PLUS_MOUNTAINS, + MEGA_SPRUCE_TAIGA_HILLS, +} diff --git a/src/main/java/org/bukkit/block/Block.java b/src/main/java/org/bukkit/block/Block.java new file mode 100644 index 0000000..4a53109 --- /dev/null +++ b/src/main/java/org/bukkit/block/Block.java @@ -0,0 +1,384 @@ +package org.bukkit.block; + +import java.util.Collection; + +import org.bukkit.Chunk; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.Metadatable; + +/** + * Represents a block. This is a live object, and only one Block may exist for + * any given location in a world. The state of the block may change + * concurrently to your own handling of it; use block.getState() to get a + * snapshot state of a block which will not be modified. + */ +public interface Block extends Metadatable { + + /** + * Gets the metadata for this block + * + * @return block specific metadata + * @deprecated Magic value + */ + @Deprecated + byte getData(); + + /** + * Gets the block at the given offsets + * + * @param modX X-coordinate offset + * @param modY Y-coordinate offset + * @param modZ Z-coordinate offset + * @return Block at the given offsets + */ + Block getRelative(int modX, int modY, int modZ); + + /** + * Gets the block at the given face + *

          + * This method is equal to getRelative(face, 1) + * + * @param face Face of this block to return + * @return Block at the given face + * @see #getRelative(BlockFace, int) + */ + Block getRelative(BlockFace face); + + /** + * Gets the block at the given distance of the given face + *

          + * For example, the following method places water at 100,102,100; two + * blocks above 100,100,100. + * + *

          +     * Block block = world.getBlockAt(100, 100, 100);
          +     * Block shower = block.getRelative(BlockFace.UP, 2);
          +     * shower.setType(Material.WATER);
          +     * 
          + * + * @param face Face of this block to return + * @param distance Distance to get the block at + * @return Block at the given face + */ + Block getRelative(BlockFace face, int distance); + + /** + * Gets the type of this block + * + * @return block type + */ + Material getType(); + + /** + * Gets the type-id of this block + * + * @return block type-id + * @deprecated Magic value + */ + @Deprecated + int getTypeId(); + + /** + * Gets the light level between 0-15 + * + * @return light level + */ + byte getLightLevel(); + + /** + * Get the amount of light at this block from the sky. + *

          + * Any light given from other sources (such as blocks like torches) will + * be ignored. + * + * @return Sky light level + */ + byte getLightFromSky(); + + /** + * Get the amount of light at this block from nearby blocks. + *

          + * Any light given from other sources (such as the sun) will be ignored. + * + * @return Block light level + */ + byte getLightFromBlocks(); + + /** + * Gets the world which contains this Block + * + * @return World containing this block + */ + World getWorld(); + + /** + * Gets the x-coordinate of this block + * + * @return x-coordinate + */ + int getX(); + + /** + * Gets the y-coordinate of this block + * + * @return y-coordinate + */ + int getY(); + + /** + * Gets the z-coordinate of this block + * + * @return z-coordinate + */ + int getZ(); + + /** + * Gets the Location of the block + * + * @return Location of block + */ + Location getLocation(); + + /** + * Stores the location of the block in the provided Location object. + *

          + * If the provided Location is null this method does nothing and returns + * null. + * + * @return The Location object provided or null + */ + Location getLocation(Location loc); + + /** + * Gets the chunk which contains this block + * + * @return Containing Chunk + */ + Chunk getChunk(); + + /** + * Sets the metadata for this block + * + * @param data New block specific metadata + * @deprecated Magic value + */ + @Deprecated + void setData(byte data); + + /** + * Sets the metadata for this block + * + * @param data New block specific metadata + * @param applyPhysics False to cancel physics from the changed block. + * @deprecated Magic value + */ + @Deprecated + void setData(byte data, boolean applyPhysics); + + /** + * Sets the type of this block + * + * @param type Material to change this block to + */ + void setType(Material type); + + /** + * Sets the type-id of this block + * + * @param type Type-Id to change this block to + * @return whether the block was changed + * @deprecated Magic value + */ + @Deprecated + boolean setTypeId(int type); + + /** + * Sets the type-id of this block + * + * @param type Type-Id to change this block to + * @param applyPhysics False to cancel physics on the changed block. + * @return whether the block was changed + * @deprecated Magic value + */ + @Deprecated + boolean setTypeId(int type, boolean applyPhysics); + + /** + * Sets the type-id of this block + * + * @param type Type-Id to change this block to + * @param data The data value to change this block to + * @param applyPhysics False to cancel physics on the changed block + * @return whether the block was changed + * @deprecated Magic value + */ + @Deprecated + boolean setTypeIdAndData(int type, byte data, boolean applyPhysics); + + /** + * Gets the face relation of this block compared to the given block + *

          + * For example: + *

          +     * Block current = world.getBlockAt(100, 100, 100);
          +     * Block target = world.getBlockAt(100, 101, 100);
          +     *
          +     * current.getFace(target) == BlockFace.Up;
          +     * 
          + *
          + * If the given block is not connected to this block, null may be returned + * + * @param block Block to compare against this block + * @return BlockFace of this block which has the requested block, or null + */ + BlockFace getFace(Block block); + + /** + * Captures the current state of this block. You may then cast that state + * into any accepted type, such as Furnace or Sign. + *

          + * The returned object will never be updated, and you are not guaranteed + * that (for example) a sign is still a sign after you capture its state. + * + * @return BlockState with the current state of this block. + */ + BlockState getState(); + + /** + * Returns the biome that this block resides in + * + * @return Biome type containing this block + */ + Biome getBiome(); + + /** + * Sets the biome that this block resides in + * + * @param bio new Biome type for this block + */ + void setBiome(Biome bio); + + /** + * Returns true if the block is being powered by Redstone. + * + * @return True if the block is powered. + */ + boolean isBlockPowered(); + + /** + * Returns true if the block is being indirectly powered by Redstone. + * + * @return True if the block is indirectly powered. + */ + boolean isBlockIndirectlyPowered(); + + /** + * Returns true if the block face is being powered by Redstone. + * + * @param face The block face + * @return True if the block face is powered. + */ + boolean isBlockFacePowered(BlockFace face); + + /** + * Returns true if the block face is being indirectly powered by Redstone. + * + * @param face The block face + * @return True if the block face is indirectly powered. + */ + boolean isBlockFaceIndirectlyPowered(BlockFace face); + + /** + * Returns the redstone power being provided to this block face + * + * @param face the face of the block to query or BlockFace.SELF for the + * block itself + * @return The power level. + */ + int getBlockPower(BlockFace face); + + /** + * Returns the redstone power being provided to this block + * + * @return The power level. + */ + int getBlockPower(); + + /** + * Checks if this block is empty. + *

          + * A block is considered empty when {@link #getType()} returns {@link + * Material#AIR}. + * + * @return true if this block is empty + */ + boolean isEmpty(); + + /** + * Checks if this block is liquid. + *

          + * A block is considered liquid when {@link #getType()} returns {@link + * Material#WATER}, {@link Material#STATIONARY_WATER}, {@link + * Material#LAVA} or {@link Material#STATIONARY_LAVA}. + * + * @return true if this block is liquid + */ + boolean isLiquid(); + + /** + * Gets the temperature of the biome of this block + * + * @return Temperature of this block + */ + double getTemperature(); + + /** + * Gets the humidity of the biome of this block + * + * @return Humidity of this block + */ + double getHumidity(); + + /** + * Returns the reaction of the block when moved by a piston + * + * @return reaction + */ + PistonMoveReaction getPistonMoveReaction(); + + /** + * Breaks the block and spawns items as if a player had digged it + * + * @return true if the block was destroyed + */ + boolean breakNaturally(); + + /** + * Breaks the block and spawns items as if a player had digged it with a + * specific tool + * + * @param tool The tool or item in hand used for digging + * @return true if the block was destroyed + */ + boolean breakNaturally(ItemStack tool); + + /** + * Returns a list of items which would drop by destroying this block + * + * @return a list of dropped items for this type of block + */ + Collection getDrops(); + + /** + * Returns a list of items which would drop by destroying this block with + * a specific tool + * + * @param tool The tool or item in hand used for digging + * @return a list of dropped items for this type of block + */ + Collection getDrops(ItemStack tool); + +} diff --git a/src/main/java/org/bukkit/block/BlockFace.java b/src/main/java/org/bukkit/block/BlockFace.java new file mode 100644 index 0000000..58fb195 --- /dev/null +++ b/src/main/java/org/bukkit/block/BlockFace.java @@ -0,0 +1,132 @@ +package org.bukkit.block; + +/** + * Represents the face of a block + */ +public enum BlockFace { + NORTH(0, 0, -1), + EAST(1, 0, 0), + SOUTH(0, 0, 1), + WEST(-1, 0, 0), + UP(0, 1, 0), + DOWN(0, -1, 0), + NORTH_EAST(NORTH, EAST), + NORTH_WEST(NORTH, WEST), + SOUTH_EAST(SOUTH, EAST), + SOUTH_WEST(SOUTH, WEST), + WEST_NORTH_WEST(WEST, NORTH_WEST), + NORTH_NORTH_WEST(NORTH, NORTH_WEST), + NORTH_NORTH_EAST(NORTH, NORTH_EAST), + EAST_NORTH_EAST(EAST, NORTH_EAST), + EAST_SOUTH_EAST(EAST, SOUTH_EAST), + SOUTH_SOUTH_EAST(SOUTH, SOUTH_EAST), + SOUTH_SOUTH_WEST(SOUTH, SOUTH_WEST), + WEST_SOUTH_WEST(WEST, SOUTH_WEST), + SELF(0, 0, 0); + + private final int modX; + private final int modY; + private final int modZ; + + private BlockFace(final int modX, final int modY, final int modZ) { + this.modX = modX; + this.modY = modY; + this.modZ = modZ; + } + + private BlockFace(final BlockFace face1, final BlockFace face2) { + this.modX = face1.getModX() + face2.getModX(); + this.modY = face1.getModY() + face2.getModY(); + this.modZ = face1.getModZ() + face2.getModZ(); + } + + /** + * Get the amount of X-coordinates to modify to get the represented block + * + * @return Amount of X-coordinates to modify + */ + public int getModX() { + return modX; + } + + /** + * Get the amount of Y-coordinates to modify to get the represented block + * + * @return Amount of Y-coordinates to modify + */ + public int getModY() { + return modY; + } + + /** + * Get the amount of Z-coordinates to modify to get the represented block + * + * @return Amount of Z-coordinates to modify + */ + public int getModZ() { + return modZ; + } + + public BlockFace getOppositeFace() { + switch (this) { + case NORTH: + return BlockFace.SOUTH; + + case SOUTH: + return BlockFace.NORTH; + + case EAST: + return BlockFace.WEST; + + case WEST: + return BlockFace.EAST; + + case UP: + return BlockFace.DOWN; + + case DOWN: + return BlockFace.UP; + + case NORTH_EAST: + return BlockFace.SOUTH_WEST; + + case NORTH_WEST: + return BlockFace.SOUTH_EAST; + + case SOUTH_EAST: + return BlockFace.NORTH_WEST; + + case SOUTH_WEST: + return BlockFace.NORTH_EAST; + + case WEST_NORTH_WEST: + return BlockFace.EAST_SOUTH_EAST; + + case NORTH_NORTH_WEST: + return BlockFace.SOUTH_SOUTH_EAST; + + case NORTH_NORTH_EAST: + return BlockFace.SOUTH_SOUTH_WEST; + + case EAST_NORTH_EAST: + return BlockFace.WEST_SOUTH_WEST; + + case EAST_SOUTH_EAST: + return BlockFace.WEST_NORTH_WEST; + + case SOUTH_SOUTH_EAST: + return BlockFace.NORTH_NORTH_WEST; + + case SOUTH_SOUTH_WEST: + return BlockFace.NORTH_NORTH_EAST; + + case WEST_SOUTH_WEST: + return BlockFace.EAST_NORTH_EAST; + + case SELF: + return BlockFace.SELF; + } + + return BlockFace.SELF; + } +} diff --git a/src/main/java/org/bukkit/block/BlockState.java b/src/main/java/org/bukkit/block/BlockState.java new file mode 100644 index 0000000..ca57173 --- /dev/null +++ b/src/main/java/org/bukkit/block/BlockState.java @@ -0,0 +1,194 @@ +package org.bukkit.block; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.material.MaterialData; +import org.bukkit.metadata.Metadatable; + +/** + * Represents a captured state of a block, which will not change + * automatically. + *

          + * Unlike Block, which only one object can exist per coordinate, BlockState + * can exist multiple times for any given Block. Note that another plugin may + * change the state of the block and you will not know, or they may change the + * block to another type entirely, causing your BlockState to become invalid. + */ +public interface BlockState extends Metadatable { + + /** + * Gets the block represented by this BlockState + * + * @return Block that this BlockState represents + */ + Block getBlock(); + + /** + * Gets the metadata for this block + * + * @return block specific metadata + */ + MaterialData getData(); + + /** + * Gets the type of this block + * + * @return block type + */ + Material getType(); + + /** + * Gets the type-id of this block + * + * @return block type-id + * @deprecated Magic value + */ + @Deprecated + int getTypeId(); + + /** + * Gets the light level between 0-15 + * + * @return light level + */ + byte getLightLevel(); + + /** + * Gets the world which contains this Block + * + * @return World containing this block + */ + World getWorld(); + + /** + * Gets the x-coordinate of this block + * + * @return x-coordinate + */ + int getX(); + + /** + * Gets the y-coordinate of this block + * + * @return y-coordinate + */ + int getY(); + + /** + * Gets the z-coordinate of this block + * + * @return z-coordinate + */ + int getZ(); + + /** + * Gets the location of this block + * + * @return location + */ + Location getLocation(); + + /** + * Stores the location of this block in the provided Location object. + *

          + * If the provided Location is null this method does nothing and returns + * null. + * + * @return The Location object provided or null + */ + Location getLocation(Location loc); + + /** + * Gets the chunk which contains this block + * + * @return Containing Chunk + */ + Chunk getChunk(); + + /** + * Sets the metadata for this block + * + * @param data New block specific metadata + */ + void setData(MaterialData data); + + /** + * Sets the type of this block + * + * @param type Material to change this block to + */ + void setType(Material type); + + /** + * Sets the type-id of this block + * + * @param type Type-Id to change this block to + * @return Whether it worked? + * @deprecated Magic value + */ + @Deprecated + boolean setTypeId(int type); + + /** + * Attempts to update the block represented by this state, setting it to + * the new values as defined by this state. + *

          + * This has the same effect as calling update(false). That is to say, + * this will not modify the state of a block if it is no longer the same + * type as it was when this state was taken. It will return false in this + * eventuality. + * + * @return true if the update was successful, otherwise false + * @see #update(boolean) + */ + boolean update(); + + /** + * Attempts to update the block represented by this state, setting it to + * the new values as defined by this state. + *

          + * This has the same effect as calling update(force, true). That is to + * say, this will trigger a physics update to surrounding blocks. + * + * @param force true to forcefully set the state + * @return true if the update was successful, otherwise false + */ + boolean update(boolean force); + + /** + * Attempts to update the block represented by this state, setting it to + * the new values as defined by this state. + *

          + * Unless force is true, this will not modify the state of a block if it + * is no longer the same type as it was when this state was taken. It will + * return false in this eventuality. + *

          + * If force is true, it will set the type of the block to match the new + * state, set the state data and then return true. + *

          + * If applyPhysics is true, it will trigger a physics update on + * surrounding blocks which could cause them to update or disappear. + * + * @param force true to forcefully set the state + * @param applyPhysics false to cancel updating physics on surrounding + * blocks + * @return true if the update was successful, otherwise false + */ + boolean update(boolean force, boolean applyPhysics); + + /** + * @return The data as a raw byte. + * @deprecated Magic value + */ + @Deprecated + public byte getRawData(); + + /** + * @param data The new data value for the block. + * @deprecated Magic value + */ + @Deprecated + public void setRawData(byte data); +} diff --git a/src/main/java/org/bukkit/block/BrewingStand.java b/src/main/java/org/bukkit/block/BrewingStand.java new file mode 100644 index 0000000..c66a51c --- /dev/null +++ b/src/main/java/org/bukkit/block/BrewingStand.java @@ -0,0 +1,25 @@ +package org.bukkit.block; + +import org.bukkit.inventory.BrewerInventory; + +/** + * Represents a brewing stand. + */ +public interface BrewingStand extends BlockState, ContainerBlock { + + /** + * How much time is left in the brewing cycle + * + * @return Brew Time + */ + int getBrewingTime(); + + /** + * Set the time left before brewing completes. + * + * @param brewTime Brewing time + */ + void setBrewingTime(int brewTime); + + public BrewerInventory getInventory(); +} diff --git a/src/main/java/org/bukkit/block/Chest.java b/src/main/java/org/bukkit/block/Chest.java new file mode 100644 index 0000000..125d5e7 --- /dev/null +++ b/src/main/java/org/bukkit/block/Chest.java @@ -0,0 +1,17 @@ +package org.bukkit.block; + +import org.bukkit.inventory.Inventory; + +/** + * Represents a chest. + */ +public interface Chest extends BlockState, ContainerBlock { + + /** + * Returns the chest's inventory. If this is a double chest, it returns + * just the portion of the inventory linked to this half of the chest. + * + * @return The inventory. + */ + Inventory getBlockInventory(); +} diff --git a/src/main/java/org/bukkit/block/CommandBlock.java b/src/main/java/org/bukkit/block/CommandBlock.java new file mode 100644 index 0000000..85d5345 --- /dev/null +++ b/src/main/java/org/bukkit/block/CommandBlock.java @@ -0,0 +1,40 @@ +package org.bukkit.block; + +public interface CommandBlock extends BlockState { + + /** + * Gets the command that this CommandBlock will run when powered. + * This will never return null. If the CommandBlock does not have a + * command, an empty String will be returned instead. + * + * @return Command that this CommandBlock will run when powered. + */ + public String getCommand(); + + /** + * Sets the command that this CommandBlock will run when powered. + * Setting the command to null is the same as setting it to an empty + * String. + * + * @param command Command that this CommandBlock will run when powered. + */ + public void setCommand(String command); + + /** + * Gets the name of this CommandBlock. The name is used with commands + * that this CommandBlock executes. This name will never be null, and + * by default is "@". + * + * @return Name of this CommandBlock. + */ + public String getName(); + + /** + * Sets the name of this CommandBlock. The name is used with commands + * that this CommandBlock executes. Setting the name to null is the + * same as setting it to "@". + * + * @param name New name for this CommandBlock. + */ + public void setName(String name); +} diff --git a/src/main/java/org/bukkit/block/ContainerBlock.java b/src/main/java/org/bukkit/block/ContainerBlock.java new file mode 100644 index 0000000..c69ac9e --- /dev/null +++ b/src/main/java/org/bukkit/block/ContainerBlock.java @@ -0,0 +1,11 @@ +package org.bukkit.block; + +import org.bukkit.inventory.InventoryHolder; + +/** + * Indicates a block type that has inventory. + * + * @deprecated in favour of {@link InventoryHolder} + */ +@Deprecated +public interface ContainerBlock extends InventoryHolder {} diff --git a/src/main/java/org/bukkit/block/CreatureSpawner.java b/src/main/java/org/bukkit/block/CreatureSpawner.java new file mode 100644 index 0000000..e54d997 --- /dev/null +++ b/src/main/java/org/bukkit/block/CreatureSpawner.java @@ -0,0 +1,88 @@ +package org.bukkit.block; + +import org.bukkit.entity.CreatureType; +import org.bukkit.entity.EntityType; + +/** + * Represents a creature spawner. + */ +public interface CreatureSpawner extends BlockState { + + /** + * Get the spawner's creature type. + * + * @return The creature type. + * @deprecated In favour of {@link #getSpawnedType()}. + */ + @Deprecated + public CreatureType getCreatureType(); + + /** + * Get the spawner's creature type. + * + * @return The creature type. + */ + public EntityType getSpawnedType(); + + /** + * Set the spawner's creature type. + * + * @param creatureType The creature type. + */ + public void setSpawnedType(EntityType creatureType); + + /** + * Set the spawner creature type. + * + * @param creatureType The creature type. + * @deprecated In favour of {@link #setSpawnedType(EntityType)}. + */ + @Deprecated + public void setCreatureType(CreatureType creatureType); + + /** + * Get the spawner's creature type. + * + * @return The creature type's name. + * @deprecated Use {@link #getCreatureTypeName()}. + */ + @Deprecated + public String getCreatureTypeId(); + + /** + * Set the spawner mob type. + * + * @param creatureType The creature type's name. + */ + public void setCreatureTypeByName(String creatureType); + + /** + * Get the spawner's creature type. + * + * @return The creature type's name. + */ + public String getCreatureTypeName(); + + /** + * Set the spawner mob type. + * + * @param creatureType The creature type's name. + * @deprecated Use {@link #setCreatureTypeByName(String)}. + */ + @Deprecated + public void setCreatureTypeId(String creatureType); + + /** + * Get the spawner's delay. + * + * @return The delay. + */ + public int getDelay(); + + /** + * Set the spawner's delay. + * + * @param delay The delay. + */ + public void setDelay(int delay); +} diff --git a/src/main/java/org/bukkit/block/Dispenser.java b/src/main/java/org/bukkit/block/Dispenser.java new file mode 100644 index 0000000..bba753e --- /dev/null +++ b/src/main/java/org/bukkit/block/Dispenser.java @@ -0,0 +1,27 @@ +package org.bukkit.block; + +import org.bukkit.projectiles.BlockProjectileSource; + +/** + * Represents a dispenser. + */ +public interface Dispenser extends BlockState, ContainerBlock { + + /** + * Gets the BlockProjectileSource object for this dispenser. + *

          + * If the block is no longer a dispenser, this will return null. + * + * @return a BlockProjectileSource if valid, otherwise null + */ + public BlockProjectileSource getBlockProjectileSource(); + + /** + * Attempts to dispense the contents of this block. + *

          + * If the block is no longer a dispenser, this will return false. + * + * @return true if successful, otherwise false + */ + public boolean dispense(); +} diff --git a/src/main/java/org/bukkit/block/DoubleChest.java b/src/main/java/org/bukkit/block/DoubleChest.java new file mode 100644 index 0000000..148099c --- /dev/null +++ b/src/main/java/org/bukkit/block/DoubleChest.java @@ -0,0 +1,50 @@ +package org.bukkit.block; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.inventory.DoubleChestInventory; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a double chest. + */ +public class DoubleChest implements InventoryHolder { + private DoubleChestInventory inventory; + + public DoubleChest(DoubleChestInventory chest) { + inventory = chest; + } + + public Inventory getInventory() { + return inventory; + } + + public InventoryHolder getLeftSide() { + return inventory.getLeftSide().getHolder(); + } + + public InventoryHolder getRightSide() { + return inventory.getRightSide().getHolder(); + } + + public Location getLocation() { + return new Location(getWorld(), getX(), getY(), getZ()); + } + + public World getWorld() { + return ((Chest)getLeftSide()).getWorld(); + } + + public double getX() { + return 0.5 * (((Chest)getLeftSide()).getX() + ((Chest)getRightSide()).getX()); + } + + public double getY() { + return 0.5 * (((Chest)getLeftSide()).getY() + ((Chest)getRightSide()).getY()); + } + + public double getZ() { + return 0.5 * (((Chest)getLeftSide()).getZ() + ((Chest)getRightSide()).getZ()); + } +} diff --git a/src/main/java/org/bukkit/block/Dropper.java b/src/main/java/org/bukkit/block/Dropper.java new file mode 100644 index 0000000..21fbedc --- /dev/null +++ b/src/main/java/org/bukkit/block/Dropper.java @@ -0,0 +1,25 @@ +package org.bukkit.block; + +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a dropper. + */ +public interface Dropper extends BlockState, InventoryHolder { + /** + * Tries to drop a randomly selected item from the Dropper's inventory, + * following the normal behavior of a Dropper. + *

          + * Normal behavior of a Dropper is as follows: + *

          + * If the block that the Dropper is facing is an InventoryHolder or + * ContainerBlock the randomly selected ItemStack is placed within that + * Inventory in the first slot that's available, starting with 0 and + * counting up. If the inventory is full, nothing happens. + *

          + * If the block that the Dropper is facing is not an InventoryHolder or + * ContainerBlock, the randomly selected ItemStack is dropped on + * the ground in the form of an {@link org.bukkit.entity.Item Item}. + */ + public void drop(); +} diff --git a/src/main/java/org/bukkit/block/Furnace.java b/src/main/java/org/bukkit/block/Furnace.java new file mode 100644 index 0000000..94af85e --- /dev/null +++ b/src/main/java/org/bukkit/block/Furnace.java @@ -0,0 +1,39 @@ +package org.bukkit.block; + +import org.bukkit.inventory.FurnaceInventory; + +/** + * Represents a furnace. + */ +public interface Furnace extends BlockState, ContainerBlock { + + /** + * Get burn time. + * + * @return Burn time + */ + public short getBurnTime(); + + /** + * Set burn time. + * + * @param burnTime Burn time + */ + public void setBurnTime(short burnTime); + + /** + * Get cook time. + * + * @return Cook time + */ + public short getCookTime(); + + /** + * Set cook time. + * + * @param cookTime Cook time + */ + public void setCookTime(short cookTime); + + public FurnaceInventory getInventory(); +} diff --git a/src/main/java/org/bukkit/block/Hopper.java b/src/main/java/org/bukkit/block/Hopper.java new file mode 100644 index 0000000..e097157 --- /dev/null +++ b/src/main/java/org/bukkit/block/Hopper.java @@ -0,0 +1,10 @@ +package org.bukkit.block; + +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a hopper. + */ +public interface Hopper extends BlockState, InventoryHolder { + +} diff --git a/src/main/java/org/bukkit/block/Jukebox.java b/src/main/java/org/bukkit/block/Jukebox.java new file mode 100644 index 0000000..7b45b83 --- /dev/null +++ b/src/main/java/org/bukkit/block/Jukebox.java @@ -0,0 +1,36 @@ +package org.bukkit.block; + +import org.bukkit.Material; + +/** + * Represents a Jukebox + */ +public interface Jukebox extends BlockState { + /** + * Get the record currently playing + * + * @return The record Material, or AIR if none is playing + */ + public Material getPlaying(); + + /** + * Set the record currently playing + * + * @param record The record Material, or null/AIR to stop playing + */ + public void setPlaying(Material record); + + /** + * Check if the jukebox is currently playing a record + * + * @return True if there is a record playing + */ + public boolean isPlaying(); + + /** + * Stop the jukebox playing and eject the current record + * + * @return True if a record was ejected; false if there was none playing + */ + public boolean eject(); +} diff --git a/src/main/java/org/bukkit/block/NoteBlock.java b/src/main/java/org/bukkit/block/NoteBlock.java new file mode 100644 index 0000000..8380068 --- /dev/null +++ b/src/main/java/org/bukkit/block/NoteBlock.java @@ -0,0 +1,72 @@ +package org.bukkit.block; + +import org.bukkit.Instrument; +import org.bukkit.Note; + +/** + * Represents a note. + */ +public interface NoteBlock extends BlockState { + + /** + * Gets the note. + * + * @return The note. + */ + public Note getNote(); + + /** + * Gets the note. + * + * @return The note ID. + * @deprecated Magic value + */ + @Deprecated + public byte getRawNote(); + + /** + * Set the note. + * + * @param note The note. + */ + public void setNote(Note note); + + /** + * Set the note. + * + * @param note The note ID. + * @deprecated Magic value + */ + @Deprecated + public void setRawNote(byte note); + + /** + * Attempts to play the note at block + *

          + * If the block is no longer a note block, this will return false + * + * @return true if successful, otherwise false + */ + public boolean play(); + + /** + * Plays an arbitrary note with an arbitrary instrument + * + * @param instrument Instrument ID + * @param note Note ID + * @return true if successful, otherwise false + * @deprecated Magic value + */ + @Deprecated + public boolean play(byte instrument, byte note); + + /** + * Plays an arbitrary note with an arbitrary instrument + * + * @param instrument The instrument + * @param note The note + * @return true if successful, otherwise false + * @see Instrument Note + */ + public boolean play(Instrument instrument, Note note); +} diff --git a/src/main/java/org/bukkit/block/PistonMoveReaction.java b/src/main/java/org/bukkit/block/PistonMoveReaction.java new file mode 100644 index 0000000..e5279f7 --- /dev/null +++ b/src/main/java/org/bukkit/block/PistonMoveReaction.java @@ -0,0 +1,51 @@ +package org.bukkit.block; + +import java.util.HashMap; +import java.util.Map; + +public enum PistonMoveReaction { + + /** + * Indicates that the block can be pushed or pulled. + */ + MOVE(0), + /** + * Indicates the block is fragile and will break if pushed on. + */ + BREAK(1), + /** + * Indicates that the block will resist being pushed or pulled. + */ + BLOCK(2); + + private int id; + private static Map byId = new HashMap(); + static { + for (PistonMoveReaction reaction : PistonMoveReaction.values()) { + byId.put(reaction.id, reaction); + } + } + + private PistonMoveReaction(int id) { + this.id = id; + } + + /** + * @return The ID of the move reaction + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return this.id; + } + + /** + * @param id An ID + * @return The move reaction with that ID + * @deprecated Magic value + */ + @Deprecated + public static PistonMoveReaction getById(int id) { + return byId.get(id); + } +} diff --git a/src/main/java/org/bukkit/block/Sign.java b/src/main/java/org/bukkit/block/Sign.java new file mode 100644 index 0000000..5d7a633 --- /dev/null +++ b/src/main/java/org/bukkit/block/Sign.java @@ -0,0 +1,37 @@ +package org.bukkit.block; + +/** + * Represents either a SignPost or a WallSign + */ +public interface Sign extends BlockState { + + /** + * Gets all the lines of text currently on this sign. + * + * @return Array of Strings containing each line of text + */ + public String[] getLines(); + + /** + * Gets the line of text at the specified index. + *

          + * For example, getLine(0) will return the first line of text. + * + * @param index Line number to get the text from, starting at 0 + * @throws IndexOutOfBoundsException Thrown when the line does not exist + * @return Text on the given line + */ + public String getLine(int index) throws IndexOutOfBoundsException; + + /** + * Sets the line of text at the specified index. + *

          + * For example, setLine(0, "Line One") will set the first line of text to + * "Line One". + * + * @param index Line number to set the text at, starting from 0 + * @param line New text to set at the specified index + * @throws IndexOutOfBoundsException If the index is out of the range 0..3 + */ + public void setLine(int index, String line) throws IndexOutOfBoundsException; +} diff --git a/src/main/java/org/bukkit/block/Skull.java b/src/main/java/org/bukkit/block/Skull.java new file mode 100644 index 0000000..4f4896f --- /dev/null +++ b/src/main/java/org/bukkit/block/Skull.java @@ -0,0 +1,62 @@ +package org.bukkit.block; + +import org.bukkit.SkullType; + +/** + * Represents a Skull + */ +public interface Skull extends BlockState { + + /** + * Checks to see if the skull has an owner + * + * @return true if the skull has an owner + */ + public boolean hasOwner(); + + /** + * Gets the owner of the skull, if one exists + * + * @return the owner of the skull or null if the skull does not have an owner + */ + public String getOwner(); + + /** + * Sets the owner of the skull + *

          + * Involves a potentially blocking web request to acquire the profile data for + * the provided name. + * + * @param name the new owner of the skull + * @return true if the owner was successfully set + */ + public boolean setOwner(String name); + + /** + * Gets the rotation of the skull in the world + * + * @return the rotation of the skull + */ + public BlockFace getRotation(); + + /** + * Sets the rotation of the skull in the world + * + * @param rotation the rotation of the skull + */ + public void setRotation(BlockFace rotation); + + /** + * Gets the type of skull + * + * @return the type of skull + */ + public SkullType getSkullType(); + + /** + * Sets the type of skull + * + * @param skullType the type of skull + */ + public void setSkullType(SkullType skullType); +} diff --git a/src/main/java/org/bukkit/command/BlockCommandSender.java b/src/main/java/org/bukkit/command/BlockCommandSender.java new file mode 100644 index 0000000..ce229d2 --- /dev/null +++ b/src/main/java/org/bukkit/command/BlockCommandSender.java @@ -0,0 +1,13 @@ +package org.bukkit.command; + +import org.bukkit.block.Block; + +public interface BlockCommandSender extends CommandSender { + + /** + * Returns the block this command sender belongs to + * + * @return Block for the command sender + */ + public Block getBlock(); +} diff --git a/src/main/java/org/bukkit/command/Command.java b/src/main/java/org/bukkit/command/Command.java new file mode 100644 index 0000000..87c33d9 --- /dev/null +++ b/src/main/java/org/bukkit/command/Command.java @@ -0,0 +1,396 @@ +package org.bukkit.command; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.entity.minecart.CommandMinecart; +import org.bukkit.permissions.Permissible; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +/** + * Represents a Command, which executes various tasks upon user input + */ +public abstract class Command { + private final String name; + private String nextLabel; + private String label; + private List aliases; + private List activeAliases; + private CommandMap commandMap = null; + protected String description = ""; + protected String usageMessage; + private String permission; + private String permissionMessage; + + protected Command(String name) { + this(name, "", "/" + name, new ArrayList()); + } + + protected Command(String name, String description, String usageMessage, List aliases) { + this.name = name; + this.nextLabel = name; + this.label = name; + this.description = description; + this.usageMessage = usageMessage; + this.aliases = aliases; + this.activeAliases = new ArrayList(aliases); + } + + /** + * Executes the command, returning its success + * + * @param sender Source object which is executing this command + * @param commandLabel The alias of the command used + * @param args All arguments passed to the command, split via ' ' + * @return true if the command was successful, otherwise false + */ + public abstract boolean execute(CommandSender sender, String commandLabel, String[] args); + + /** + * @deprecated This method is not supported and returns null + */ + @Deprecated + public List tabComplete(CommandSender sender, String[] args) { + return null; + } + + /** + * Executed on tab completion for this command, returning a list of + * options the player can tab through. + * + * @param sender Source object which is executing this command + * @param alias the alias being used + * @param args All arguments passed to the command, split via ' ' + * @return a list of tab-completions for the specified arguments. This + * will never be null. List may be immutable. + * @throws IllegalArgumentException if sender, alias, or args is null + */ + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 0) { + return ImmutableList.of(); + } + + String lastWord = args[args.length - 1]; + + Player senderPlayer = sender instanceof Player ? (Player) sender : null; + + ArrayList matchedPlayers = new ArrayList(); + for (Player player : sender.getServer().getOnlinePlayers()) { + String name = player.getName(); + if ((senderPlayer == null || senderPlayer.canSee(player)) && StringUtil.startsWithIgnoreCase(name, lastWord)) { + matchedPlayers.add(name); + } + } + + Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); + return matchedPlayers; + } + + /** + * Returns the name of this command + * + * @return Name of this command + */ + public String getName() { + return name; + } + + /** + * Gets the permission required by users to be able to perform this + * command + * + * @return Permission name, or null if none + */ + public String getPermission() { + return permission; + } + + /** + * Sets the permission required by users to be able to perform this + * command + * + * @param permission Permission name or null + */ + public void setPermission(String permission) { + this.permission = permission; + } + + /** + * Tests the given {@link CommandSender} to see if they can perform this + * command. + *

          + * If they do not have permission, they will be informed that they cannot + * do this. + * + * @param target User to test + * @return true if they can use it, otherwise false + */ + public boolean testPermission(CommandSender target) { + if (testPermissionSilent(target)) { + return true; + } + + if (permissionMessage == null) { + target.sendMessage(ChatColor.RED + "I'm sorry, but you do not have permission to perform this command. Please contact the server administrators if you believe that this is in error."); + } else if (permissionMessage.length() != 0) { + for (String line : permissionMessage.replace("", permission).split("\n")) { + target.sendMessage(line); + } + } + + return false; + } + + /** + * Tests the given {@link CommandSender} to see if they can perform this + * command. + *

          + * No error is sent to the sender. + * + * @param target User to test + * @return true if they can use it, otherwise false + */ + public boolean testPermissionSilent(CommandSender target) { + if ((permission == null) || (permission.length() == 0)) { + return true; + } + + for (String p : permission.split(";")) { + if (target.hasPermission(p)) { + return true; + } + } + + return false; + } + + /** + * Returns the current label for this command + * + * @return Label of this command or null if not registered + */ + public String getLabel() { + return label; + } + + /** + * Sets the label of this command. + *

          + * If the command is currently registered the label change will only take + * effect after its been re-registered e.g. after a /reload + * + * @param name The command's name + * @return returns true if the name change happened instantly or false if + * it was scheduled for re-registration + */ + public boolean setLabel(String name) { + this.nextLabel = name; + if (!isRegistered()) { + this.label = name; + return true; + } + return false; + } + + /** + * Registers this command to a CommandMap. + * Once called it only allows changes the registered CommandMap + * + * @param commandMap the CommandMap to register this command to + * @return true if the registration was successful (the current registered + * CommandMap was the passed CommandMap or null) false otherwise + */ + public boolean register(CommandMap commandMap) { + if (allowChangesFrom(commandMap)) { + this.commandMap = commandMap; + return true; + } + + return false; + } + + /** + * Unregisters this command from the passed CommandMap applying any + * outstanding changes + * + * @param commandMap the CommandMap to unregister + * @return true if the unregistration was successfull (the current + * registered CommandMap was the passed CommandMap or null) false + * otherwise + */ + public boolean unregister(CommandMap commandMap) { + if (allowChangesFrom(commandMap)) { + this.commandMap = null; + this.activeAliases = new ArrayList(this.aliases); + this.label = this.nextLabel; + return true; + } + + return false; + } + + private boolean allowChangesFrom(CommandMap commandMap) { + return (null == this.commandMap || this.commandMap == commandMap); + } + + /** + * Returns the current registered state of this command + * + * @return true if this command is currently registered false otherwise + */ + public boolean isRegistered() { + return (null != this.commandMap); + } + + /** + * Returns a list of active aliases of this command + * + * @return List of aliases + */ + public List getAliases() { + return activeAliases; + } + + /** + * Returns a message to be displayed on a failed permission check for this + * command + * + * @return Permission check failed message + */ + public String getPermissionMessage() { + return permissionMessage; + } + + /** + * Gets a brief description of this command + * + * @return Description of this command + */ + public String getDescription() { + return description; + } + + /** + * Gets an example usage of this command + * + * @return One or more example usages + */ + public String getUsage() { + return usageMessage; + } + + /** + * Sets the list of aliases to request on registration for this command. + * This is not effective outside of defining aliases in the {@link + * PluginDescriptionFile#getCommands()} (under the + * `aliases' node) is equivalent to this method. + * + * @param aliases aliases to register to this command + * @return this command object, for chaining + */ + public Command setAliases(List aliases) { + this.aliases = aliases; + if (!isRegistered()) { + this.activeAliases = new ArrayList(aliases); + } + return this; + } + + /** + * Sets a brief description of this command. Defining a description in the + * {@link PluginDescriptionFile#getCommands()} (under the + * `description' node) is equivalent to this method. + * + * @param description new command description + * @return this command object, for chaining + */ + public Command setDescription(String description) { + this.description = description; + return this; + } + + /** + * Sets the message sent when a permission check fails + * + * @param permissionMessage new permission message, null to indicate + * default message, or an empty string to indicate no message + * @return this command object, for chaining + */ + public Command setPermissionMessage(String permissionMessage) { + this.permissionMessage = permissionMessage; + return this; + } + + /** + * Sets the example usage of this command + * + * @param usage new example usage + * @return this command object, for chaining + */ + public Command setUsage(String usage) { + this.usageMessage = usage; + return this; + } + + public static void broadcastCommandMessage(CommandSender source, String message) { + broadcastCommandMessage(source, message, true); + } + + public static void broadcastCommandMessage(CommandSender source, String message, boolean sendToSource) { + String result = source.getName() + ": " + message; + + if (source instanceof BlockCommandSender) { + BlockCommandSender blockCommandSender = (BlockCommandSender) source; + + if (blockCommandSender.getBlock().getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { + Bukkit.getConsoleSender().sendMessage(result); + return; + } + } else if (source instanceof CommandMinecart) { + CommandMinecart commandMinecart = (CommandMinecart) source; + + if (commandMinecart.getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { + Bukkit.getConsoleSender().sendMessage(result); + return; + } + } + + Set users = Bukkit.getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_ADMINISTRATIVE); + String colored = ChatColor.GRAY + "" + ChatColor.ITALIC + "[" + result + ChatColor.GRAY + ChatColor.ITALIC + "]"; + + if (sendToSource && !(source instanceof ConsoleCommandSender)) { + source.sendMessage(message); + } + + for (Permissible user : users) { + if (user instanceof CommandSender) { + CommandSender target = (CommandSender) user; + + if (target instanceof ConsoleCommandSender) { + target.sendMessage(result); + } else if (target != source) { + target.sendMessage(colored); + } + } + } + } + + @Override + public String toString() { + return getClass().getName() + '(' + name + ')'; + } +} diff --git a/src/main/java/org/bukkit/command/CommandException.java b/src/main/java/org/bukkit/command/CommandException.java new file mode 100644 index 0000000..b63015f --- /dev/null +++ b/src/main/java/org/bukkit/command/CommandException.java @@ -0,0 +1,28 @@ +package org.bukkit.command; + +/** + * Thrown when an unhandled exception occurs during the execution of a Command + */ +@SuppressWarnings("serial") +public class CommandException extends RuntimeException { + + /** + * Creates a new instance of CommandException without detail + * message. + */ + public CommandException() {} + + /** + * Constructs an instance of CommandException with the + * specified detail message. + * + * @param msg the detail message. + */ + public CommandException(String msg) { + super(msg); + } + + public CommandException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/src/main/java/org/bukkit/command/CommandExecutor.java b/src/main/java/org/bukkit/command/CommandExecutor.java new file mode 100644 index 0000000..c75586f --- /dev/null +++ b/src/main/java/org/bukkit/command/CommandExecutor.java @@ -0,0 +1,18 @@ +package org.bukkit.command; + +/** + * Represents a class which contains a single method for executing commands + */ +public interface CommandExecutor { + + /** + * Executes the given command, returning its success + * + * @param sender Source of the command + * @param command Command which was executed + * @param label Alias of the command which was used + * @param args Passed command arguments + * @return true if a valid command, otherwise false + */ + public boolean onCommand(CommandSender sender, Command command, String label, String[] args); +} diff --git a/src/main/java/org/bukkit/command/CommandMap.java b/src/main/java/org/bukkit/command/CommandMap.java new file mode 100644 index 0000000..e7e20d8 --- /dev/null +++ b/src/main/java/org/bukkit/command/CommandMap.java @@ -0,0 +1,109 @@ +package org.bukkit.command; + +import java.util.List; + +public interface CommandMap { + + /** + * Registers all the commands belonging to a certain plugin. + *

          + * Caller can use:- + *

            + *
          • command.getName() to determine the label registered for this + * command + *
          • command.getAliases() to determine the aliases which where + * registered + *
          + * + * @param fallbackPrefix a prefix which is prepended to each command with + * a ':' one or more times to make the command unique + * @param commands a list of commands to register + */ + public void registerAll(String fallbackPrefix, List commands); + + /** + * Registers a command. Returns true on success; false if name is already + * taken and fallback had to be used. + *

          + * Caller can use:- + *

            + *
          • command.getName() to determine the label registered for this + * command + *
          • command.getAliases() to determine the aliases which where + * registered + *
          + * + * @param label the label of the command, without the '/'-prefix. + * @param fallbackPrefix a prefix which is prepended to the command with a + * ':' one or more times to make the command unique + * @param command the command to register + * @return true if command was registered with the passed in label, false + * otherwise, which indicates the fallbackPrefix was used one or more + * times + */ + public boolean register(String label, String fallbackPrefix, Command command); + + /** + * Registers a command. Returns true on success; false if name is already + * taken and fallback had to be used. + *

          + * Caller can use:- + *

            + *
          • command.getName() to determine the label registered for this + * command + *
          • command.getAliases() to determine the aliases which where + * registered + *
          + * + * @param fallbackPrefix a prefix which is prepended to the command with a + * ':' one or more times to make the command unique + * @param command the command to register, from which label is determined + * from the command name + * @return true if command was registered with the passed in label, false + * otherwise, which indicates the fallbackPrefix was used one or more + * times + */ + public boolean register(String fallbackPrefix, Command command); + + /** + * Looks for the requested command and executes it if found. + * + * @param sender The command's sender + * @param cmdLine command + arguments. Example: "/test abc 123" + * @return returns false if no target is found, true otherwise. + * @throws CommandException Thrown when the executor for the given command + * fails with an unhandled exception + */ + public boolean dispatch(CommandSender sender, String cmdLine) throws CommandException; + + /** + * Clears all registered commands. + */ + public void clearCommands(); + + /** + * Gets the command registered to the specified name + * + * @param name Name of the command to retrieve + * @return Command with the specified name or null if a command with that + * label doesn't exist + */ + public Command getCommand(String name); + + + /** + * Looks for the requested command and executes an appropriate + * tab-completer if found. This method will also tab-complete partial + * commands. + * + * @param sender The command's sender. + * @param cmdLine The entire command string to tab-complete, excluding + * initial slash. + * @return a list of possible tab-completions. This list may be immutable. + * Will be null if no matching command of which sender has permission. + * @throws CommandException Thrown when the tab-completer for the given + * command fails with an unhandled exception + * @throws IllegalArgumentException if either sender or cmdLine are null + */ + public List tabComplete(CommandSender sender, String cmdLine) throws IllegalArgumentException; +} diff --git a/src/main/java/org/bukkit/command/CommandSender.java b/src/main/java/org/bukkit/command/CommandSender.java new file mode 100644 index 0000000..148756b --- /dev/null +++ b/src/main/java/org/bukkit/command/CommandSender.java @@ -0,0 +1,35 @@ +package org.bukkit.command; + +import org.bukkit.Server; +import org.bukkit.permissions.Permissible; + +public interface CommandSender extends Permissible { + + /** + * Sends this sender a message + * + * @param message Message to be displayed + */ + public void sendMessage(String message); + + /** + * Sends this sender multiple messages + * + * @param messages An array of messages to be displayed + */ + public void sendMessage(String[] messages); + + /** + * Returns the server instance that this command is running on + * + * @return Server instance + */ + public Server getServer(); + + /** + * Gets the name of this command sender + * + * @return Name of the sender + */ + public String getName(); +} diff --git a/src/main/java/org/bukkit/command/ConsoleCommandSender.java b/src/main/java/org/bukkit/command/ConsoleCommandSender.java new file mode 100644 index 0000000..f309c2e --- /dev/null +++ b/src/main/java/org/bukkit/command/ConsoleCommandSender.java @@ -0,0 +1,6 @@ +package org.bukkit.command; + +import org.bukkit.conversations.Conversable; + +public interface ConsoleCommandSender extends CommandSender, Conversable { +} diff --git a/src/main/java/org/bukkit/command/FormattedCommandAlias.java b/src/main/java/org/bukkit/command/FormattedCommandAlias.java new file mode 100644 index 0000000..3f07d7f --- /dev/null +++ b/src/main/java/org/bukkit/command/FormattedCommandAlias.java @@ -0,0 +1,124 @@ +package org.bukkit.command; + +import java.util.ArrayList; +import java.util.logging.Level; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.server.RemoteServerCommandEvent; +import org.bukkit.event.server.ServerCommandEvent; + +public class FormattedCommandAlias extends Command { + private final String[] formatStrings; + + public FormattedCommandAlias(String alias, String[] formatStrings) { + super(alias); + this.formatStrings = formatStrings; + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + boolean result = false; + ArrayList commands = new ArrayList(); + for (String formatString : formatStrings) { + try { + commands.add(buildCommand(formatString, args)); + } catch (Throwable throwable) { + if (throwable instanceof IllegalArgumentException) { + sender.sendMessage(throwable.getMessage()); + } else { + sender.sendMessage(org.bukkit.ChatColor.RED + "An internal error occurred while attempting to perform this command"); + } + return false; + } + } + + for (String command : commands) { + result |= Bukkit.dispatchCommand(sender, command); + } + + return result; + } + + private String buildCommand(String formatString, String[] args) { + int index = formatString.indexOf("$"); + while (index != -1) { + int start = index; + + if (index > 0 && formatString.charAt(start - 1) == '\\') { + formatString = formatString.substring(0, start - 1) + formatString.substring(start); + index = formatString.indexOf("$", index); + continue; + } + + boolean required = false; + if (formatString.charAt(index + 1) == '$') { + required = true; + // Move index past the second $ + index++; + } + + // Move index past the $ + index++; + int argStart = index; + while (index < formatString.length() && inRange(((int) formatString.charAt(index)) - 48, 0, 9)) { + // Move index past current digit + index++; + } + + // No numbers found + if (argStart == index) { + throw new IllegalArgumentException("Invalid replacement token"); + } + + int position = Integer.valueOf(formatString.substring(argStart, index)); + + // Arguments are not 0 indexed + if (position == 0) { + throw new IllegalArgumentException("Invalid replacement token"); + } + + // Convert position to 0 index + position--; + + boolean rest = false; + if (index < formatString.length() && formatString.charAt(index) == '-') { + rest = true; + // Move index past the - + index++; + } + + int end = index; + + if (required && position >= args.length) { + throw new IllegalArgumentException("Missing required argument " + (position + 1)); + } + + StringBuilder replacement = new StringBuilder(); + if (rest && position < args.length) { + for (int i = position; i < args.length; i++) { + if (i != position) { + replacement.append(' '); + } + replacement.append(args[i]); + } + } else if (position < args.length) { + replacement.append(args[position]); + } + + formatString = formatString.substring(0, start) + replacement.toString() + formatString.substring(end); + // Move index past the replaced data so we don't process it again + index = start + replacement.length(); + + // Move to the next replacement token + index = formatString.indexOf("$", index); + } + + return formatString; + } + + private static boolean inRange(int i, int j, int k) { + return i >= j && i <= k; + } +} diff --git a/src/main/java/org/bukkit/command/MultipleCommandAlias.java b/src/main/java/org/bukkit/command/MultipleCommandAlias.java new file mode 100644 index 0000000..a0a4129 --- /dev/null +++ b/src/main/java/org/bukkit/command/MultipleCommandAlias.java @@ -0,0 +1,33 @@ +package org.bukkit.command; + +/** + * Represents a command that delegates to one or more other commands + */ +public class MultipleCommandAlias extends Command { + private Command[] commands; + + public MultipleCommandAlias(String name, Command[] commands) { + super(name); + this.commands = commands; + } + + /** + * Gets the commands associated with the multi-command alias. + * + * @return commands associated with alias + */ + public Command[] getCommands() { + return commands; + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + boolean result = false; + + for (Command command : commands) { + result |= command.execute(sender, commandLabel, args); + } + + return result; + } +} diff --git a/src/main/java/org/bukkit/command/PluginCommand.java b/src/main/java/org/bukkit/command/PluginCommand.java new file mode 100644 index 0000000..3bfa31f --- /dev/null +++ b/src/main/java/org/bukkit/command/PluginCommand.java @@ -0,0 +1,160 @@ +package org.bukkit.command; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.Plugin; + +/** + * Represents a {@link Command} belonging to a plugin + */ +public final class PluginCommand extends Command implements PluginIdentifiableCommand { + private final Plugin owningPlugin; + private CommandExecutor executor; + private TabCompleter completer; + + protected PluginCommand(String name, Plugin owner) { + super(name); + this.executor = owner; + this.owningPlugin = owner; + this.usageMessage = ""; + } + + /** + * Executes the command, returning its success + * + * @param sender Source object which is executing this command + * @param commandLabel The alias of the command used + * @param args All arguments passed to the command, split via ' ' + * @return true if the command was successful, otherwise false + */ + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + boolean success = false; + + if (!owningPlugin.isEnabled()) { + return false; + } + + if (!testPermission(sender)) { + return true; + } + + try { + success = executor.onCommand(sender, this, commandLabel, args); + } catch (Throwable ex) { + throw new CommandException("Unhandled exception executing command '" + commandLabel + "' in plugin " + owningPlugin.getDescription().getFullName(), ex); + } + + if (!success && usageMessage.length() > 0) { + for (String line : usageMessage.replace("", commandLabel).split("\n")) { + sender.sendMessage(line); + } + } + + return success; + } + + /** + * Sets the {@link CommandExecutor} to run when parsing this command + * + * @param executor New executor to run + */ + public void setExecutor(CommandExecutor executor) { + this.executor = executor == null ? owningPlugin : executor; + } + + /** + * Gets the {@link CommandExecutor} associated with this command + * + * @return CommandExecutor object linked to this command + */ + public CommandExecutor getExecutor() { + return executor; + } + + /** + * Sets the {@link TabCompleter} to run when tab-completing this command. + *

          + * If no TabCompleter is specified, and the command's executor implements + * TabCompleter, then the executor will be used for tab completion. + * + * @param completer New tab completer + */ + public void setTabCompleter(TabCompleter completer) { + this.completer = completer; + } + + /** + * Gets the {@link TabCompleter} associated with this command. + * + * @return TabCompleter object linked to this command + */ + public TabCompleter getTabCompleter() { + return completer; + } + + /** + * Gets the owner of this PluginCommand + * + * @return Plugin that owns this command + */ + public Plugin getPlugin() { + return owningPlugin; + } + + /** + * {@inheritDoc} + *

          + * Delegates to the tab completer if present. + *

          + * If it is not present or returns null, will delegate to the current + * command executor if it implements {@link TabCompleter}. If a non-null + * list has not been found, will default to standard player name + * completion in {@link + * Command#tabComplete(CommandSender, String, String[])}. + *

          + * This method does not consider permissions. + * + * @throws CommandException if the completer or executor throw an + * exception during the process of tab-completing. + * @throws IllegalArgumentException if sender, alias, or args is null + */ + @Override + public java.util.List tabComplete(CommandSender sender, String alias, String[] args) throws CommandException, IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + List completions = null; + try { + if (completer != null) { + completions = completer.onTabComplete(sender, this, alias, args); + } + if (completions == null && executor instanceof TabCompleter) { + completions = ((TabCompleter) executor).onTabComplete(sender, this, alias, args); + } + } catch (Throwable ex) { + StringBuilder message = new StringBuilder(); + message.append("Unhandled exception during tab completion for command '/").append(alias).append(' '); + for (String arg : args) { + message.append(arg).append(' '); + } + message.deleteCharAt(message.length() - 1).append("' in plugin ").append(owningPlugin.getDescription().getFullName()); + throw new CommandException(message.toString(), ex); + } + + if (completions == null) { + return super.tabComplete(sender, alias, args); + } + return completions; + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder(super.toString()); + stringBuilder.deleteCharAt(stringBuilder.length() - 1); + stringBuilder.append(", ").append(owningPlugin.getDescription().getFullName()).append(')'); + return stringBuilder.toString(); + } +} diff --git a/src/main/java/org/bukkit/command/PluginCommandYamlParser.java b/src/main/java/org/bukkit/command/PluginCommandYamlParser.java new file mode 100644 index 0000000..5854583 --- /dev/null +++ b/src/main/java/org/bukkit/command/PluginCommandYamlParser.java @@ -0,0 +1,76 @@ +package org.bukkit.command; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +public class PluginCommandYamlParser { + + public static List parse(Plugin plugin) { + List pluginCmds = new ArrayList(); + + Map> map = plugin.getDescription().getCommands(); + + if (map == null) { + return pluginCmds; + } + + for (Entry> entry : map.entrySet()) { + if (entry.getKey().contains(":")) { + Bukkit.getServer().getLogger().severe("Could not load command " + entry.getKey() + " for plugin " + plugin.getName() + ": Illegal Characters"); + continue; + } + Command newCmd = new PluginCommand(entry.getKey(), plugin); + Object description = entry.getValue().get("description"); + Object usage = entry.getValue().get("usage"); + Object aliases = entry.getValue().get("aliases"); + Object permission = entry.getValue().get("permission"); + Object permissionMessage = entry.getValue().get("permission-message"); + + if (description != null) { + newCmd.setDescription(description.toString()); + } + + if (usage != null) { + newCmd.setUsage(usage.toString()); + } + + if (aliases != null) { + List aliasList = new ArrayList(); + + if (aliases instanceof List) { + for (Object o : (List) aliases) { + if (o.toString().contains(":")) { + Bukkit.getServer().getLogger().severe("Could not load alias " + o.toString() + " for plugin " + plugin.getName() + ": Illegal Characters"); + continue; + } + aliasList.add(o.toString()); + } + } else { + if (aliases.toString().contains(":")) { + Bukkit.getServer().getLogger().severe("Could not load alias " + aliases.toString() + " for plugin " + plugin.getName() + ": Illegal Characters"); + } else { + aliasList.add(aliases.toString()); + } + } + + newCmd.setAliases(aliasList); + } + + if (permission != null) { + newCmd.setPermission(permission.toString()); + } + + if (permissionMessage != null) { + newCmd.setPermissionMessage(permissionMessage.toString()); + } + + pluginCmds.add(newCmd); + } + return pluginCmds; + } +} diff --git a/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java b/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java new file mode 100644 index 0000000..c5e0d2c --- /dev/null +++ b/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java @@ -0,0 +1,19 @@ +package org.bukkit.command; + +import org.bukkit.plugin.Plugin; + +/** + * This interface is used by the help system to group commands into + * sub-indexes based on the {@link Plugin} they are a part of. Custom command + * implementations will need to implement this interface to have a sub-index + * automatically generated on the plugin's behalf. + */ +public interface PluginIdentifiableCommand { + + /** + * Gets the owner of this PluginIdentifiableCommand. + * + * @return Plugin that owns this PluginIdentifiableCommand. + */ + public Plugin getPlugin(); +} diff --git a/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java b/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java new file mode 100644 index 0000000..dc3bc1d --- /dev/null +++ b/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java @@ -0,0 +1,4 @@ +package org.bukkit.command; + +public interface RemoteConsoleCommandSender extends CommandSender { +} diff --git a/src/main/java/org/bukkit/command/SimpleCommandMap.java b/src/main/java/org/bukkit/command/SimpleCommandMap.java new file mode 100644 index 0000000..d75380c --- /dev/null +++ b/src/main/java/org/bukkit/command/SimpleCommandMap.java @@ -0,0 +1,301 @@ +package org.bukkit.command; + +import static org.bukkit.util.Java15Compat.Arrays_copyOfRange; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import org.apache.commons.lang.Validate; +import org.bukkit.Server; +import org.bukkit.command.defaults.*; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +public class SimpleCommandMap implements CommandMap { + private static final Pattern PATTERN_ON_SPACE = Pattern.compile(" ", Pattern.LITERAL); + protected final Map knownCommands = new HashMap(); + private final Server server; + + public SimpleCommandMap(final Server server) { + this.server = server; + setDefaultCommands(); + } + + private void setDefaultCommands() { + register("bukkit", new SaveCommand()); + register("bukkit", new SaveOnCommand()); + register("bukkit", new SaveOffCommand()); + register("bukkit", new StopCommand()); + register("bukkit", new VersionCommand("version")); + register("bukkit", new ReloadCommand("reload")); + register("bukkit", new PluginsCommand("plugins")); + register("bukkit", new TimingsCommand("timings")); + } + + public void setFallbackCommands() { + register("bukkit", new ListCommand()); + register("bukkit", new OpCommand()); + register("bukkit", new DeopCommand()); + register("bukkit", new BanIpCommand()); + register("bukkit", new PardonIpCommand()); + register("bukkit", new BanCommand()); + register("bukkit", new PardonCommand()); + register("bukkit", new KickCommand()); + register("bukkit", new TeleportCommand()); + register("bukkit", new GiveCommand()); + register("bukkit", new TimeCommand()); + register("bukkit", new SayCommand()); + register("bukkit", new WhitelistCommand()); + register("bukkit", new TellCommand()); + register("bukkit", new MeCommand()); + register("bukkit", new KillCommand()); + register("bukkit", new GameModeCommand()); + register("bukkit", new HelpCommand()); + register("bukkit", new ExpCommand()); + register("bukkit", new ToggleDownfallCommand()); + register("bukkit", new BanListCommand()); + register("bukkit", new DefaultGameModeCommand()); + register("bukkit", new SeedCommand()); + register("bukkit", new DifficultyCommand()); + register("bukkit", new WeatherCommand()); + register("bukkit", new SpawnpointCommand()); + register("bukkit", new ClearCommand()); + register("bukkit", new GameRuleCommand()); + register("bukkit", new EnchantCommand()); + register("bukkit", new TestForCommand()); + register("bukkit", new EffectCommand()); + register("bukkit", new ScoreboardCommand()); + register("bukkit", new PlaySoundCommand()); + register("bukkit", new SpreadPlayersCommand()); + register("bukkit", new SetWorldSpawnCommand()); + register("bukkit", new SetIdleTimeoutCommand()); + register("bukkit", new AchievementCommand()); + } + + /** + * {@inheritDoc} + */ + public void registerAll(String fallbackPrefix, List commands) { + if (commands != null) { + for (Command c : commands) { + register(fallbackPrefix, c); + } + } + } + + /** + * {@inheritDoc} + */ + public boolean register(String fallbackPrefix, Command command) { + return register(command.getName(), fallbackPrefix, command); + } + + /** + * {@inheritDoc} + */ + public boolean register(String label, String fallbackPrefix, Command command) { + label = label.toLowerCase().trim(); + fallbackPrefix = fallbackPrefix.toLowerCase().trim(); + boolean registered = register(label, command, false, fallbackPrefix); + + Iterator iterator = command.getAliases().iterator(); + while (iterator.hasNext()) { + if (!register(iterator.next(), command, true, fallbackPrefix)) { + iterator.remove(); + } + } + + // If we failed to register under the real name, we need to set the command label to the direct address + if (!registered) { + command.setLabel(fallbackPrefix + ":" + label); + } + + // Register to us so further updates of the commands label and aliases are postponed until its reregistered + command.register(this); + + return registered; + } + + /** + * Registers a command with the given name is possible. Also uses + * fallbackPrefix to create a unique name. + * + * @param label the name of the command, without the '/'-prefix. + * @param command the command to register + * @param isAlias whether the command is an alias + * @param fallbackPrefix a prefix which is prepended to the command for a + * unique address + * @return true if command was registered, false otherwise. + */ + private synchronized boolean register(String label, Command command, boolean isAlias, String fallbackPrefix) { + knownCommands.put(fallbackPrefix + ":" + label, command); + if ((command instanceof VanillaCommand || isAlias) && knownCommands.containsKey(label)) { + // Request is for an alias/fallback command and it conflicts with + // a existing command or previous alias ignore it + // Note: This will mean it gets removed from the commands list of active aliases + return false; + } + + boolean registered = true; + + // If the command exists but is an alias we overwrite it, otherwise we return + Command conflict = knownCommands.get(label); + if (conflict != null && conflict.getLabel().equals(label)) { + return false; + } + + if (!isAlias) { + command.setLabel(label); + } + knownCommands.put(label, command); + + return registered; + } + + /** + * {@inheritDoc} + */ + public boolean dispatch(CommandSender sender, String commandLine) throws CommandException { + String[] args = PATTERN_ON_SPACE.split(commandLine); + + if (args.length == 0) { + return false; + } + + String sentCommandLabel = args[0].toLowerCase(); + Command target = getCommand(sentCommandLabel); + + if (target == null) { + return false; + } + + try { + // Note: we don't return the result of target.execute as thats success / failure, we return handled (true) or not handled (false) + target.execute(sender, sentCommandLabel, Arrays_copyOfRange(args, 1, args.length)); + } catch (CommandException ex) { + throw ex; + } catch (Throwable ex) { + throw new CommandException("Unhandled exception executing '" + commandLine + "' in " + target, ex); + } + + // return true as command was handled + return true; + } + + public synchronized void clearCommands() { + for (Map.Entry entry : knownCommands.entrySet()) { + entry.getValue().unregister(this); + } + knownCommands.clear(); + setDefaultCommands(); + } + + public Command getCommand(String name) { + Command target = knownCommands.get(name.toLowerCase()); + return target; + } + + public List tabComplete(CommandSender sender, String cmdLine) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(cmdLine, "Command line cannot null"); + + int spaceIndex = cmdLine.indexOf(' '); + + if (spaceIndex == -1) { + ArrayList completions = new ArrayList(); + Map knownCommands = this.knownCommands; + + final String prefix = (sender instanceof Player ? "/" : ""); + + for (Map.Entry commandEntry : knownCommands.entrySet()) { + Command command = commandEntry.getValue(); + + if (!command.testPermissionSilent(sender)) { + continue; + } + + String name = commandEntry.getKey(); // Use the alias, not command name + + if (StringUtil.startsWithIgnoreCase(name, cmdLine)) { + completions.add(prefix + name); + } + } + + Collections.sort(completions, String.CASE_INSENSITIVE_ORDER); + return completions; + } + + String commandName = cmdLine.substring(0, spaceIndex); + Command target = getCommand(commandName); + + if (target == null) { + return null; + } + + if (!target.testPermissionSilent(sender)) { + return null; + } + + String argLine = cmdLine.substring(spaceIndex + 1, cmdLine.length()); + String[] args = PATTERN_ON_SPACE.split(argLine, -1); + + try { + return target.tabComplete(sender, commandName, args); + } catch (CommandException ex) { + throw ex; + } catch (Throwable ex) { + throw new CommandException("Unhandled exception executing tab-completer for '" + cmdLine + "' in " + target, ex); + } + } + + public Collection getCommands() { + return Collections.unmodifiableCollection(knownCommands.values()); + } + + public void registerServerAliases() { + Map values = server.getCommandAliases(); + + for (String alias : values.keySet()) { + if (alias.contains(":") || alias.contains(" ")) { + server.getLogger().warning("Could not register alias " + alias + " because it contains illegal characters"); + continue; + } + + String[] commandStrings = values.get(alias); + List targets = new ArrayList(); + StringBuilder bad = new StringBuilder(); + + for (String commandString : commandStrings) { + String[] commandArgs = commandString.split(" "); + Command command = getCommand(commandArgs[0]); + + if (command == null) { + if (bad.length() > 0) { + bad.append(", "); + } + bad.append(commandString); + } else { + targets.add(commandString); + } + } + + if (bad.length() > 0) { + server.getLogger().warning("Could not register alias " + alias + " because it contains commands that do not exist: " + bad); + continue; + } + + // We register these as commands so they have absolute priority. + if (targets.size() > 0) { + knownCommands.put(alias.toLowerCase(), new FormattedCommandAlias(alias.toLowerCase(), targets.toArray(new String[targets.size()]))); + } else { + knownCommands.remove(alias.toLowerCase()); + } + } + } +} diff --git a/src/main/java/org/bukkit/command/TabCommandExecutor.java b/src/main/java/org/bukkit/command/TabCommandExecutor.java new file mode 100644 index 0000000..d24d795 --- /dev/null +++ b/src/main/java/org/bukkit/command/TabCommandExecutor.java @@ -0,0 +1,16 @@ +package org.bukkit.command; + +import java.util.List; + +/** + * Represents a class which can handle command tab completion and commands + * + * @deprecated Remains for plugins that would have implemented it even without + * functionality + * @see TabExecutor + */ +@Deprecated +public interface TabCommandExecutor extends CommandExecutor { + public List onTabComplete(); + +} diff --git a/src/main/java/org/bukkit/command/TabCompleter.java b/src/main/java/org/bukkit/command/TabCompleter.java new file mode 100644 index 0000000..6d61e3a --- /dev/null +++ b/src/main/java/org/bukkit/command/TabCompleter.java @@ -0,0 +1,22 @@ +package org.bukkit.command; + +import java.util.List; + +/** + * Represents a class which can suggest tab completions for commands. + */ +public interface TabCompleter { + + /** + * Requests a list of possible completions for a command argument. + * + * @param sender Source of the command + * @param command Command which was executed + * @param alias The alias used + * @param args The arguments passed to the command, including final + * partial argument to be completed and command label + * @return A List of possible completions for the final argument, or null + * to default to the command executor + */ + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args); +} diff --git a/src/main/java/org/bukkit/command/TabExecutor.java b/src/main/java/org/bukkit/command/TabExecutor.java new file mode 100644 index 0000000..6b8e3fb --- /dev/null +++ b/src/main/java/org/bukkit/command/TabExecutor.java @@ -0,0 +1,8 @@ +package org.bukkit.command; + +/** + * This class is provided as a convenience to implement both TabCompleter and + * CommandExecutor. + */ +public interface TabExecutor extends TabCompleter, CommandExecutor { +} diff --git a/src/main/java/org/bukkit/command/defaults/AchievementCommand.java b/src/main/java/org/bukkit/command/defaults/AchievementCommand.java new file mode 100644 index 0000000..d490732 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/AchievementCommand.java @@ -0,0 +1,187 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Achievement; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Statistic; +import org.bukkit.Material; +import org.bukkit.Statistic.Type; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerAchievementAwardedEvent; +import org.bukkit.event.player.PlayerStatisticIncrementEvent; + +import com.google.common.collect.ImmutableList; + +public class AchievementCommand extends VanillaCommand { + public AchievementCommand() { + super("achievement"); + this.description = "Gives the specified player an achievement or changes a statistic value. Use '*' to give all achievements."; + this.usageMessage = "/achievement give [player]"; + this.setPermission("bukkit.command.achievement"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + if (!args[0].equalsIgnoreCase("give")) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + String statisticString = args[1]; + Player player = null; + + if (args.length > 2) { + player = Bukkit.getPlayer(args[1]); + } else if (sender instanceof Player) { + player = (Player) sender; + } + + if (player == null) { + sender.sendMessage("You must specify which player you wish to perform this action on."); + return true; + } + + if (statisticString.equals("*")) { + for (Achievement achievement : Achievement.values()) { + if (player.hasAchievement(achievement)) { + continue; + } + PlayerAchievementAwardedEvent event = new PlayerAchievementAwardedEvent(player, achievement); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + player.awardAchievement(achievement); + } + } + Command.broadcastCommandMessage(sender, String.format("Successfully given all achievements to %s", player.getName())); + return true; + } + + Achievement achievement = Bukkit.getUnsafe().getAchievementFromInternalName(statisticString); + Statistic statistic = Bukkit.getUnsafe().getStatisticFromInternalName(statisticString); + + if (achievement != null) { + if (player.hasAchievement(achievement)) { + sender.sendMessage(String.format("%s already has achievement %s", player.getName(), statisticString)); + return true; + } + + PlayerAchievementAwardedEvent event = new PlayerAchievementAwardedEvent(player, achievement); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + sender.sendMessage(String.format("Unable to award %s the achievement %s", player.getName(), statisticString)); + return true; + } + player.awardAchievement(achievement); + + Command.broadcastCommandMessage(sender, String.format("Successfully given %s the stat %s", player.getName(), statisticString)); + return true; + } + + if (statistic == null) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + + if (statistic.getType() == Type.UNTYPED) { + PlayerStatisticIncrementEvent event = new PlayerStatisticIncrementEvent(player, statistic, player.getStatistic(statistic), player.getStatistic(statistic) + 1); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + sender.sendMessage(String.format("Unable to increment %s for %s", statisticString, player.getName())); + return true; + } + player.incrementStatistic(statistic); + Command.broadcastCommandMessage(sender, String.format("Successfully given %s the stat %s", player.getName(), statisticString)); + return true; + } + + if (statistic.getType() == Type.ENTITY) { + EntityType entityType = EntityType.fromName(statisticString.substring(statisticString.lastIndexOf(".") + 1)); + + if (entityType == null) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + + PlayerStatisticIncrementEvent event = new PlayerStatisticIncrementEvent(player, statistic, player.getStatistic(statistic), player.getStatistic(statistic) + 1, entityType); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + sender.sendMessage(String.format("Unable to increment %s for %s", statisticString, player.getName())); + return true; + } + + try { + player.incrementStatistic(statistic, entityType); + } catch (IllegalArgumentException e) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + } else { + int id; + try { + id = getInteger(sender, statisticString.substring(statisticString.lastIndexOf(".") + 1), 0, Integer.MAX_VALUE, true); + } catch (NumberFormatException e) { + sender.sendMessage(e.getMessage()); + return true; + } + + Material material = Material.getMaterial(id); + + if (material == null) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + + PlayerStatisticIncrementEvent event = new PlayerStatisticIncrementEvent(player, statistic, player.getStatistic(statistic), player.getStatistic(statistic) + 1, material); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + sender.sendMessage(String.format("Unable to increment %s for %s", statisticString, player.getName())); + return true; + } + + try { + player.incrementStatistic(statistic, material); + } catch (IllegalArgumentException e) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + } + + Command.broadcastCommandMessage(sender, String.format("Successfully given %s the stat %s", player.getName(), statisticString)); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return Arrays.asList("give"); + } + + if (args.length == 2) { + return Bukkit.getUnsafe().tabCompleteInternalStatisticOrAchievementName(args[1], new ArrayList()); + } + + if (args.length == 3) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/BanCommand.java b/src/main/java/org/bukkit/command/defaults/BanCommand.java new file mode 100644 index 0000000..df891b8 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/BanCommand.java @@ -0,0 +1,55 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class BanCommand extends VanillaCommand { + public BanCommand() { + super("ban"); + this.description = "Prevents the specified player from using this server"; + this.usageMessage = "/ban [reason ...]"; + this.setPermission("bukkit.command.ban.player"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + String reason = args.length > 0 ? StringUtils.join(args, ' ', 1, args.length) : null; + Bukkit.getBanList(BanList.Type.NAME).addBan(args[0], reason, null, sender.getName()); + + Player player = Bukkit.getPlayer(args[0]); + if (player != null) { + player.kickPlayer("Banned by admin."); + } + + Command.broadcastCommandMessage(sender, "Banned player " + args[0]); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length >= 1) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/BanIpCommand.java b/src/main/java/org/bukkit/command/defaults/BanIpCommand.java new file mode 100644 index 0000000..6f7c8bd --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/BanIpCommand.java @@ -0,0 +1,77 @@ +package org.bukkit.command.defaults; + +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class BanIpCommand extends VanillaCommand { + public static final Pattern ipValidity = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + + public BanIpCommand() { + super("ban-ip"); + this.description = "Prevents the specified IP address from using this server"; + this.usageMessage = "/ban-ip [reason ...]"; + this.setPermission("bukkit.command.ban.ip"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + String reason = args.length > 0 ? StringUtils.join(args, ' ', 1, args.length) : null; + + if (ipValidity.matcher(args[0]).matches()) { + processIPBan(args[0], sender, reason); + } else { + Player player = Bukkit.getPlayer(args[0]); + + if (player == null) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + processIPBan(player.getAddress().getAddress().getHostAddress(), sender, reason); + } + + return true; + } + + private void processIPBan(String ip, CommandSender sender, String reason) { + Bukkit.getBanList(BanList.Type.IP).addBan(ip, reason, null, sender.getName()); + + // Find all matching players and kick + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getAddress().getAddress().getHostAddress().equals(ip)) { + player.kickPlayer("You have been IP banned."); + } + } + + Command.broadcastCommandMessage(sender, "Banned IP Address " + ip); + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/BanListCommand.java b/src/main/java/org/bukkit/command/defaults/BanListCommand.java new file mode 100644 index 0000000..dfab7bc --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/BanListCommand.java @@ -0,0 +1,73 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang.Validate; +import org.bukkit.BanEntry; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class BanListCommand extends VanillaCommand { + private static final List BANLIST_TYPES = ImmutableList.of("ips", "players"); + + public BanListCommand() { + super("banlist"); + this.description = "View all players banned from this server"; + this.usageMessage = "/banlist [ips|players]"; + this.setPermission("bukkit.command.ban.list"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + BanList.Type banType = BanList.Type.NAME; + if (args.length > 0) { + if (args[0].equalsIgnoreCase("ips")) { + banType = BanList.Type.IP; + } else if (!args[0].equalsIgnoreCase("players")) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + } + + StringBuilder message = new StringBuilder(); + BanEntry[] banlist = Bukkit.getBanList(banType).getBanEntries().toArray(new BanEntry[0]); + + for (int x = 0; x < banlist.length; x++) { + if (x != 0) { + if (x == banlist.length - 1) { + message.append(" and "); + } else { + message.append(", "); + } + } + + message.append(banlist[x].getTarget()); + } + + sender.sendMessage("There are " + banlist.length + " total banned players:"); + sender.sendMessage(message.toString()); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], BANLIST_TYPES, new ArrayList(BANLIST_TYPES.size())); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/BukkitCommand.java b/src/main/java/org/bukkit/command/defaults/BukkitCommand.java new file mode 100644 index 0000000..23c8580 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/BukkitCommand.java @@ -0,0 +1,15 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.bukkit.command.Command; + +public abstract class BukkitCommand extends Command { + protected BukkitCommand(String name) { + super(name); + } + + protected BukkitCommand(String name, String description, String usageMessage, List aliases) { + super(name, description, usageMessage, aliases); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/ClearCommand.java b/src/main/java/org/bukkit/command/defaults/ClearCommand.java new file mode 100644 index 0000000..a9df4f9 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/ClearCommand.java @@ -0,0 +1,114 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class ClearCommand extends VanillaCommand { + private static List materials; + static { + ArrayList materialList = new ArrayList(); + for (Material material : Material.values()) { + materialList.add(material.name()); + } + Collections.sort(materialList); + materials = ImmutableList.copyOf(materialList); + } + + public ClearCommand() { + super("clear"); + this.description = "Clears the player's inventory. Can specify item and data filters too."; + this.usageMessage = "/clear [item] [data]"; + this.setPermission("bukkit.command.clear"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Player player = null; + if (args.length > 0) { + player = Bukkit.getPlayer(args[0]); + } else if (sender instanceof Player) { + player = (Player) sender; + } + + if (player != null) { + int id; + + if (args.length > 1 && !(args[1].equals("-1"))) { + Material material = Material.matchMaterial(args[1]); + if (material == null) { + sender.sendMessage(ChatColor.RED + "There's no item called " + args[1]); + return false; + } + + id = material.getId(); + } else { + id = -1; + } + + int data = args.length >= 3 ? getInteger(sender, args[2], 0) : -1; + int count = player.getInventory().clear(id, data); + + Command.broadcastCommandMessage(sender, "Cleared the inventory of " + player.getDisplayName() + ", removing " + count + " items"); + } else if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Please provide a player!"); + } else { + sender.sendMessage(ChatColor.RED + "Can't find player " + args[0]); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + if (args.length == 2) { + final String arg = args[1]; + final List materials = ClearCommand.materials; + List completion = null; + + final int size = materials.size(); + int i = Collections.binarySearch(materials, arg, String.CASE_INSENSITIVE_ORDER); + + if (i < 0) { + // Insertion (start) index + i = -1 - i; + } + + for ( ; i < size; i++) { + String material = materials.get(i); + if (StringUtil.startsWithIgnoreCase(material, arg)) { + if (completion == null) { + completion = new ArrayList(); + } + completion.add(material); + } else { + break; + } + } + + if (completion != null) { + return completion; + } + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/DefaultGameModeCommand.java b/src/main/java/org/bukkit/command/defaults/DefaultGameModeCommand.java new file mode 100644 index 0000000..77ba678 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/DefaultGameModeCommand.java @@ -0,0 +1,70 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class DefaultGameModeCommand extends VanillaCommand { + private static final List GAMEMODE_NAMES = ImmutableList.of("adventure", "creative", "survival"); + + public DefaultGameModeCommand() { + super("defaultgamemode"); + this.description = "Set the default gamemode"; + this.usageMessage = "/defaultgamemode "; + this.setPermission("bukkit.command.defaultgamemode"); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage("Usage: " + usageMessage); + return false; + } + + String modeArg = args[0]; + int value = -1; + + try { + value = Integer.parseInt(modeArg); + } catch (NumberFormatException ex) {} + + GameMode mode = GameMode.getByValue(value); + + if (mode == null) { + if (modeArg.equalsIgnoreCase("creative") || modeArg.equalsIgnoreCase("c")) { + mode = GameMode.CREATIVE; + } else if (modeArg.equalsIgnoreCase("adventure") || modeArg.equalsIgnoreCase("a")) { + mode = GameMode.ADVENTURE; + } else { + mode = GameMode.SURVIVAL; + } + } + + Bukkit.getServer().setDefaultGameMode(mode); + Command.broadcastCommandMessage(sender, "Default game mode set to " + mode.toString().toLowerCase()); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], GAMEMODE_NAMES, new ArrayList(GAMEMODE_NAMES.size())); + } + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/DeopCommand.java b/src/main/java/org/bukkit/command/defaults/DeopCommand.java new file mode 100644 index 0000000..1b71d49 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/DeopCommand.java @@ -0,0 +1,62 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class DeopCommand extends VanillaCommand { + public DeopCommand() { + super("deop"); + this.description = "Takes the specified player's operator status"; + this.usageMessage = "/deop "; + this.setPermission("bukkit.command.op.take"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]); + player.setOp(false); + + if (player instanceof Player) { + ((Player) player).sendMessage(ChatColor.YELLOW + "You are no longer op!"); + } + + Command.broadcastCommandMessage(sender, "De-opped " + args[0]); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + List completions = new ArrayList(); + for (OfflinePlayer player : Bukkit.getOfflinePlayers()) { + String playerName = player.getName(); + if (player.isOp() && StringUtil.startsWithIgnoreCase(playerName, args[0])) { + completions.add(playerName); + } + } + return completions; + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/DifficultyCommand.java b/src/main/java/org/bukkit/command/defaults/DifficultyCommand.java new file mode 100644 index 0000000..ca98559 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/DifficultyCommand.java @@ -0,0 +1,81 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; +import org.bukkit.Difficulty; + +import java.util.ArrayList; +import java.util.List; + +public class DifficultyCommand extends VanillaCommand { + private static final List DIFFICULTY_NAMES = ImmutableList.of("peaceful", "easy", "normal", "hard"); + + public DifficultyCommand() { + super("difficulty"); + this.description = "Sets the game difficulty"; + this.usageMessage = "/difficulty "; + this.setPermission("bukkit.command.difficulty"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Difficulty difficulty = Difficulty.getByValue(getDifficultyForString(sender, args[0])); + + if (Bukkit.isHardcore()) { + difficulty = Difficulty.HARD; + } + + Bukkit.getWorlds().get(0).setDifficulty(difficulty); + + int levelCount = 1; + if (Bukkit.getAllowNether()) { + Bukkit.getWorlds().get(levelCount).setDifficulty(difficulty); + levelCount++; + } + + if (Bukkit.getAllowEnd()) { + Bukkit.getWorlds().get(levelCount).setDifficulty(difficulty); + } + + Command.broadcastCommandMessage(sender, "Set difficulty to " + difficulty.toString()); + return true; + } + + protected int getDifficultyForString(CommandSender sender, String name) { + if (name.equalsIgnoreCase("peaceful") || name.equalsIgnoreCase("p")) { + return 0; + } else if (name.equalsIgnoreCase("easy") || name.equalsIgnoreCase("e")) { + return 1; + } else if (name.equalsIgnoreCase("normal") || name.equalsIgnoreCase("n")) { + return 2; + } else if (name.equalsIgnoreCase("hard") || name.equalsIgnoreCase("h")) { + return 3; + } else { + return getInteger(sender, name, 0, 3); + } + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], DIFFICULTY_NAMES, new ArrayList(DIFFICULTY_NAMES.size())); + } + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/EffectCommand.java b/src/main/java/org/bukkit/command/defaults/EffectCommand.java new file mode 100644 index 0000000..7d0662e --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/EffectCommand.java @@ -0,0 +1,119 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.StringUtil; + +public class EffectCommand extends VanillaCommand { + private static final List effects; + + public EffectCommand() { + super("effect"); + this.description = "Adds/Removes effects on players"; + this.usageMessage = "/effect [seconds] [amplifier]"; + this.setPermission("bukkit.command.effect"); + } + + static { + ImmutableList.Builder builder = ImmutableList.builder(); + + for (PotionEffectType type : PotionEffectType.values()) { + if (type != null) { + builder.add(type.getName()); + } + } + + effects = builder.build(); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) { + return true; + } + + if (args.length < 2) { + sender.sendMessage(getUsage()); + return true; + } + + final Player player = sender.getServer().getPlayer(args[0]); + + if (player == null) { + sender.sendMessage(ChatColor.RED + String.format("Player, %s, not found", args[0])); + return true; + } + + if ("clear".equalsIgnoreCase(args[1])) { + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + sender.sendMessage(String.format("Took all effects from %s", args[0])); + return true; + } + + PotionEffectType effect = PotionEffectType.getByName(args[1]); + + if (effect == null) { + effect = PotionEffectType.getById(getInteger(sender, args[1], 0)); + } + + if (effect == null) { + sender.sendMessage(ChatColor.RED + String.format("Effect, %s, not found", args[1])); + return true; + } + + int duration = 600; + int duration_temp = 30; + int amplification = 0; + + if (args.length >= 3) { + duration_temp = getInteger(sender, args[2], 0, 1000000); + if (effect.isInstant()) { + duration = duration_temp; + } else { + duration = duration_temp * 20; + } + } else if (effect.isInstant()) { + duration = 1; + } + + if (args.length >= 4) { + amplification = getInteger(sender, args[3], 0, 255); + } + + if (duration_temp == 0) { + if (!player.hasPotionEffect(effect)) { + sender.sendMessage(String.format("Couldn't take %s from %s as they do not have the effect", effect.getName(), args[0])); + return true; + } + + player.removePotionEffect(effect); + broadcastCommandMessage(sender, String.format("Took %s from %s", effect.getName(), args[0])); + } else { + final PotionEffect applyEffect = new PotionEffect(effect, duration, amplification); + + player.addPotionEffect(applyEffect, true); + broadcastCommandMessage(sender, String.format("Given %s (ID %d) * %d to %s for %d seconds", effect.getName(), effect.getId(), amplification, args[0], duration_temp)); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String commandLabel, String[] args) { + if (args.length == 1) { + return super.tabComplete(sender, commandLabel, args); + } else if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], effects, new ArrayList(effects.size())); + } + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/EnchantCommand.java b/src/main/java/org/bukkit/command/defaults/EnchantCommand.java new file mode 100644 index 0000000..2976649 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/EnchantCommand.java @@ -0,0 +1,169 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.Validate; +import org.apache.commons.lang.WordUtils; +import com.google.common.collect.ImmutableList; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.StringUtil; + +public class EnchantCommand extends VanillaCommand { + private static final List ENCHANTMENT_NAMES = new ArrayList(); + + public EnchantCommand() { + super("enchant"); + this.description = "Adds enchantments to the item the player is currently holding. Specify 0 for the level to remove an enchantment. Specify force to ignore normal enchantment restrictions"; + this.usageMessage = "/enchant [level|max|0] [force]"; + this.setPermission("bukkit.command.enchant"); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + boolean force = false; + if (args.length > 2) { + force = args[args.length > 3 ? 3 : 2].equalsIgnoreCase("force"); + } + + Player player = Bukkit.getPlayerExact(args[0]); + if (player == null) { + sender.sendMessage("Can't find player " + args[0]); + } else { + ItemStack item = player.getItemInHand(); + if (item.getType() == Material.AIR) { + sender.sendMessage("The player isn't holding an item"); + } else { + String itemName = item.getType().toString().replaceAll("_", " "); + itemName = WordUtils.capitalizeFully(itemName); + + Enchantment enchantment = getEnchantment(args[1].toUpperCase()); + if (enchantment == null) { + sender.sendMessage(String.format("Enchantment does not exist: %s", args[1])); + } else { + String enchantmentName = enchantment.getName().replaceAll("_", " "); + enchantmentName = WordUtils.capitalizeFully(enchantmentName); + + if (!force && !enchantment.canEnchantItem(item)) { + sender.sendMessage(String.format("%s cannot be applied to %s", enchantmentName, itemName)); + } else { + int level = 1; + if (args.length > 2) { + Integer integer = getInteger(args[2]); + int minLevel = enchantment.getStartLevel(); + int maxLevel = force ? Short.MAX_VALUE : enchantment.getMaxLevel(); + + if (integer != null) { + if (integer == 0) { + item.removeEnchantment(enchantment); + Command.broadcastCommandMessage(sender, String.format("Removed %s on %s's %s", enchantmentName, player.getName(), itemName)); + return true; + } + + if (integer < minLevel || integer > maxLevel) { + sender.sendMessage(String.format("Level for enchantment %s must be between %d and %d", enchantmentName, minLevel, maxLevel)); + sender.sendMessage("Specify 0 for level to remove an enchantment"); + return true; + } + + level = integer; + } + + if ("max".equals(args[2])) { + level = maxLevel; + } + } + + Map enchantments = item.getEnchantments(); + boolean conflicts = false; + + if (!force && !enchantments.isEmpty()) { // TODO: Improve this to use a "hasEnchantments" call + for (Map.Entry entry : enchantments.entrySet()) { + Enchantment enchant = entry.getKey(); + + if (enchant.equals(enchantment)) continue; + if (enchant.conflictsWith(enchantment)) { + sender.sendMessage(String.format("Can't apply the enchantment %s on an item with the enchantment %s", enchantmentName, WordUtils.capitalizeFully(enchant.getName().replaceAll("_", " ")))); + conflicts = true; + break; + } + } + } + + if (!conflicts) { + item.addUnsafeEnchantment(enchantment, level); + + Command.broadcastCommandMessage(sender, String.format("Applied %s (Lvl %d) on %s's %s", enchantmentName, level, player.getName(), itemName), false); + sender.sendMessage(String.format("Enchanting succeeded, applied %s (Lvl %d) onto your %s", enchantmentName, level, itemName)); + } + } + } + } + } + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], ENCHANTMENT_NAMES, new ArrayList(ENCHANTMENT_NAMES.size())); + } + + if (args.length == 3 || args.length == 4) { + if (!args[args.length - 2].equalsIgnoreCase("force")) { + return ImmutableList.of("force"); + } + } + + return ImmutableList.of(); + } + + private Enchantment getEnchantment(String lookup) { + Enchantment enchantment = Enchantment.getByName(lookup); + + if (enchantment == null) { + Integer id = getInteger(lookup); + if (id != null) { + enchantment = Enchantment.getById(id); + } + } + + return enchantment; + } + + public static void buildEnchantments() { + if (!ENCHANTMENT_NAMES.isEmpty()) { + throw new IllegalStateException("Enchantments have already been built!"); + } + + for (Enchantment enchantment : Enchantment.values()) { + ENCHANTMENT_NAMES.add(enchantment.getName()); + } + + Collections.sort(ENCHANTMENT_NAMES); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/ExpCommand.java b/src/main/java/org/bukkit/command/defaults/ExpCommand.java new file mode 100644 index 0000000..2749760 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/ExpCommand.java @@ -0,0 +1,89 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class ExpCommand extends VanillaCommand { + public ExpCommand() { + super("xp"); + this.description = "Gives the specified player a certain amount of experience. Specify L to give levels instead, with a negative amount resulting in taking levels."; + this.usageMessage = "/xp [player] OR /xp L [player]"; + this.setPermission("bukkit.command.xp"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length > 0) { + String inputAmount = args[0]; + Player player = null; + + boolean isLevel = inputAmount.endsWith("l") || inputAmount.endsWith("L"); + if (isLevel && inputAmount.length() > 1) { + inputAmount = inputAmount.substring(0, inputAmount.length() - 1); + } + + int amount = getInteger(sender, inputAmount, Integer.MIN_VALUE, Integer.MAX_VALUE); + boolean isTaking = amount < 0; + + if (isTaking) { + amount *= -1; + } + + if (args.length > 1) { + player = Bukkit.getPlayer(args[1]); + } else if (sender instanceof Player) { + player = (Player) sender; + } + + if (player != null) { + if (isLevel) { + if (isTaking) { + player.giveExpLevels(-amount); + Command.broadcastCommandMessage(sender, "Taken " + amount + " level(s) from " + player.getName()); + } else { + player.giveExpLevels(amount); + Command.broadcastCommandMessage(sender, "Given " + amount + " level(s) to " + player.getName()); + } + } else { + if (isTaking) { + sender.sendMessage(ChatColor.RED + "Taking experience can only be done by levels, cannot give players negative experience points"); + return false; + } else { + player.giveExp(amount); + Command.broadcastCommandMessage(sender, "Given " + amount + " experience to " + player.getName()); + } + } + } else { + sender.sendMessage("Can't find player, was one provided?\n" + ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + return true; + } + + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 2) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/GameModeCommand.java b/src/main/java/org/bukkit/command/defaults/GameModeCommand.java new file mode 100644 index 0000000..c58f906 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/GameModeCommand.java @@ -0,0 +1,98 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class GameModeCommand extends VanillaCommand { + private static final List GAMEMODE_NAMES = ImmutableList.of("adventure", "creative", "survival"); + + public GameModeCommand() { + super("gamemode"); + this.description = "Changes the player to a specific game mode"; + this.usageMessage = "/gamemode [player]"; + this.setPermission("bukkit.command.gamemode"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + String modeArg = args[0]; + String playerArg = sender.getName(); + + if (args.length == 2) { + playerArg = args[1]; + } + + Player player = Bukkit.getPlayerExact(playerArg); + + if (player != null) { + int value = -1; + + try { + value = Integer.parseInt(modeArg); + } catch (NumberFormatException ex) {} + + GameMode mode = GameMode.getByValue(value); + + if (mode == null) { + if (modeArg.equalsIgnoreCase("creative") || modeArg.equalsIgnoreCase("c")) { + mode = GameMode.CREATIVE; + } else if (modeArg.equalsIgnoreCase("adventure") || modeArg.equalsIgnoreCase("a")) { + mode = GameMode.ADVENTURE; + } else { + mode = GameMode.SURVIVAL; + } + } + + if (mode != player.getGameMode()) { + player.setGameMode(mode); + + if (mode != player.getGameMode()) { + sender.sendMessage("Game mode change for " + player.getName() + " failed!"); + } else { + if (player == sender) { + Command.broadcastCommandMessage(sender, "Set own game mode to " + mode.toString() + " mode"); + } else { + Command.broadcastCommandMessage(sender, "Set " + player.getName() + "'s game mode to " + mode.toString() + " mode"); + } + } + } else { + sender.sendMessage(player.getName() + " already has game mode " + mode.getValue()); + } + } else { + sender.sendMessage("Can't find player " + playerArg); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], GAMEMODE_NAMES, new ArrayList(GAMEMODE_NAMES.size())); + } else if (args.length == 2) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/GameRuleCommand.java b/src/main/java/org/bukkit/command/defaults/GameRuleCommand.java new file mode 100644 index 0000000..40c531b --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/GameRuleCommand.java @@ -0,0 +1,88 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.ChatColor; +import org.bukkit.command.BlockCommandSender; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.entity.HumanEntity; + +public class GameRuleCommand extends VanillaCommand { + private static final List GAMERULE_STATES = ImmutableList.of("true", "false"); + + public GameRuleCommand() { + super("gamerule"); + this.description = "Sets a server's game rules"; + this.usageMessage = "/gamerule OR /gamerule "; + this.setPermission("bukkit.command.gamerule"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length > 0) { + String rule = args[0]; + World world = getGameWorld(sender); + + if (world.isGameRule(rule)) { + if (args.length > 1) { + String value = args[1]; + + world.setGameRuleValue(rule, value); + Command.broadcastCommandMessage(sender, "Game rule " + rule + " has been set to: " + value); + } else { + String value = world.getGameRuleValue(rule); + sender.sendMessage(rule + " = " + value); + } + } else { + sender.sendMessage(ChatColor.RED + "No game rule called " + rule + " is available"); + } + + return true; + } else { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + sender.sendMessage("Rules: " + this.createString(getGameWorld(sender).getGameRules(), 0, ", ")); + + return true; + } + } + + private World getGameWorld(CommandSender sender) { + if (sender instanceof HumanEntity) { + World world = ((HumanEntity) sender).getWorld(); + if (world != null) { + return world; + } + } else if (sender instanceof BlockCommandSender) { + return ((BlockCommandSender) sender).getBlock().getWorld(); + } + + return Bukkit.getWorlds().get(0); + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], Arrays.asList(getGameWorld(sender).getGameRules()), new ArrayList()); + } + + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], GAMERULE_STATES, new ArrayList(GAMERULE_STATES.size())); + } + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/GiveCommand.java b/src/main/java/org/bukkit/command/defaults/GiveCommand.java new file mode 100644 index 0000000..14f27be --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/GiveCommand.java @@ -0,0 +1,129 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.StringUtil; + +import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableList; + +public class GiveCommand extends VanillaCommand { + private static List materials; + static { + ArrayList materialList = new ArrayList(); + for (Material material : Material.values()) { + materialList.add(material.name()); + } + Collections.sort(materialList); + materials = ImmutableList.copyOf(materialList); + } + + public GiveCommand() { + super("give"); + this.description = "Gives the specified player a certain amount of items"; + this.usageMessage = "/give [amount [data]]"; + this.setPermission("bukkit.command.give"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if ((args.length < 2)) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Player player = Bukkit.getPlayerExact(args[0]); + + if (player != null) { + Material material = Material.matchMaterial(args[1]); + + if (material == null) { + material = Bukkit.getUnsafe().getMaterialFromInternalName(args[1]); + } + + if (material != null) { + int amount = 1; + short data = 0; + + if (args.length >= 3) { + amount = this.getInteger(sender, args[2], 1, 64); + + if (args.length >= 4) { + try { + data = Short.parseShort(args[3]); + } catch (NumberFormatException ex) {} + } + } + + ItemStack stack = new ItemStack(material, amount, data); + + if (args.length >= 5) { + try { + stack = Bukkit.getUnsafe().modifyItemStack(stack, Joiner.on(' ').join(Arrays.asList(args).subList(4, args.length))); + } catch (Throwable t) { + player.sendMessage("Not a valid tag"); + return true; + } + } + + player.getInventory().addItem(stack); + + Command.broadcastCommandMessage(sender, "Gave " + player.getName() + " some " + material.getId() + " (" + material + ")"); + } else { + sender.sendMessage("There's no item called " + args[1]); + } + } else { + sender.sendMessage("Can't find player " + args[0]); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + if (args.length == 2) { + final String arg = args[1]; + final List materials = GiveCommand.materials; + List completion = new ArrayList(); + + final int size = materials.size(); + int i = Collections.binarySearch(materials, arg, String.CASE_INSENSITIVE_ORDER); + + if (i < 0) { + // Insertion (start) index + i = -1 - i; + } + + for ( ; i < size; i++) { + String material = materials.get(i); + if (StringUtil.startsWithIgnoreCase(material, arg)) { + completion.add(material); + } else { + break; + } + } + + return Bukkit.getUnsafe().tabCompleteInternalMaterialName(arg, completion); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/HelpCommand.java b/src/main/java/org/bukkit/command/defaults/HelpCommand.java new file mode 100644 index 0000000..ff73b26 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/HelpCommand.java @@ -0,0 +1,228 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.apache.commons.lang.math.NumberUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.help.HelpMap; +import org.bukkit.help.HelpTopic; +import org.bukkit.help.HelpTopicComparator; +import org.bukkit.help.IndexHelpTopic; +import org.bukkit.util.ChatPaginator; + +import com.google.common.collect.ImmutableList; + +public class HelpCommand extends VanillaCommand { + public HelpCommand() { + super("help"); + this.description = "Shows the help menu"; + this.usageMessage = "/help \n/help \n/help "; + this.setAliases(Arrays.asList(new String[] { "?" })); + this.setPermission("bukkit.command.help"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + String command; + int pageNumber; + int pageHeight; + int pageWidth; + + if (args.length == 0) { + command = ""; + pageNumber = 1; + } else if (NumberUtils.isDigits(args[args.length - 1])) { + command = StringUtils.join(ArrayUtils.subarray(args, 0, args.length - 1), " "); + try { + pageNumber = NumberUtils.createInteger(args[args.length - 1]); + } catch (NumberFormatException exception) { + pageNumber = 1; + } + if (pageNumber <= 0) { + pageNumber = 1; + } + } else { + command = StringUtils.join(args, " "); + pageNumber = 1; + } + + if (sender instanceof ConsoleCommandSender) { + pageHeight = ChatPaginator.UNBOUNDED_PAGE_HEIGHT; + pageWidth = ChatPaginator.UNBOUNDED_PAGE_WIDTH; + } else { + pageHeight = ChatPaginator.CLOSED_CHAT_PAGE_HEIGHT - 1; + pageWidth = ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH; + } + + HelpMap helpMap = Bukkit.getServer().getHelpMap(); + HelpTopic topic = helpMap.getHelpTopic(command); + + if (topic == null) { + topic = helpMap.getHelpTopic("/" + command); + } + + if (topic == null) { + topic = findPossibleMatches(command); + } + + if (topic == null || !topic.canSee(sender)) { + sender.sendMessage(ChatColor.RED + "No help for " + command); + return true; + } + + ChatPaginator.ChatPage page = ChatPaginator.paginate(topic.getFullText(sender), pageNumber, pageWidth, pageHeight); + + StringBuilder header = new StringBuilder(); + header.append(ChatColor.YELLOW); + header.append("--------- "); + header.append(ChatColor.WHITE); + header.append("Help: "); + header.append(topic.getName()); + header.append(" "); + if (page.getTotalPages() > 1) { + header.append("("); + header.append(page.getPageNumber()); + header.append("/"); + header.append(page.getTotalPages()); + header.append(") "); + } + header.append(ChatColor.YELLOW); + for (int i = header.length(); i < ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH; i++) { + header.append("-"); + } + sender.sendMessage(header.toString()); + + sender.sendMessage(page.getLines()); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + List matchedTopics = new ArrayList(); + String searchString = args[0]; + for (HelpTopic topic : Bukkit.getServer().getHelpMap().getHelpTopics()) { + String trimmedTopic = topic.getName().startsWith("/") ? topic.getName().substring(1) : topic.getName(); + + if (trimmedTopic.startsWith(searchString)) { + matchedTopics.add(trimmedTopic); + } + } + return matchedTopics; + } + return ImmutableList.of(); + } + + protected HelpTopic findPossibleMatches(String searchString) { + int maxDistance = (searchString.length() / 5) + 3; + Set possibleMatches = new TreeSet(HelpTopicComparator.helpTopicComparatorInstance()); + + if (searchString.startsWith("/")) { + searchString = searchString.substring(1); + } + + for (HelpTopic topic : Bukkit.getServer().getHelpMap().getHelpTopics()) { + String trimmedTopic = topic.getName().startsWith("/") ? topic.getName().substring(1) : topic.getName(); + + if (trimmedTopic.length() < searchString.length()) { + continue; + } + + if (Character.toLowerCase(trimmedTopic.charAt(0)) != Character.toLowerCase(searchString.charAt(0))) { + continue; + } + + if (damerauLevenshteinDistance(searchString, trimmedTopic.substring(0, searchString.length())) < maxDistance) { + possibleMatches.add(topic); + } + } + + if (possibleMatches.size() > 0) { + return new IndexHelpTopic("Search", null, null, possibleMatches, "Search for: " + searchString); + } else { + return null; + } + } + + /** + * Computes the Dameraur-Levenshtein Distance between two strings. Adapted + * from the algorithm at Wikipedia: Damerau–Levenshtein distance + * + * @param s1 The first string being compared. + * @param s2 The second string being compared. + * @return The number of substitutions, deletions, insertions, and + * transpositions required to get from s1 to s2. + */ + protected static int damerauLevenshteinDistance(String s1, String s2) { + if (s1 == null && s2 == null) { + return 0; + } + if (s1 != null && s2 == null) { + return s1.length(); + } + if (s1 == null && s2 != null) { + return s2.length(); + } + + int s1Len = s1.length(); + int s2Len = s2.length(); + int[][] H = new int[s1Len + 2][s2Len + 2]; + + int INF = s1Len + s2Len; + H[0][0] = INF; + for (int i = 0; i <= s1Len; i++) { + H[i + 1][1] = i; + H[i + 1][0] = INF; + } + for (int j = 0; j <= s2Len; j++) { + H[1][j + 1] = j; + H[0][j + 1] = INF; + } + + Map sd = new HashMap(); + for (char Letter : (s1 + s2).toCharArray()) { + if (!sd.containsKey(Letter)) { + sd.put(Letter, 0); + } + } + + for (int i = 1; i <= s1Len; i++) { + int DB = 0; + for (int j = 1; j <= s2Len; j++) { + int i1 = sd.get(s2.charAt(j - 1)); + int j1 = DB; + + if (s1.charAt(i - 1) == s2.charAt(j - 1)) { + H[i + 1][j + 1] = H[i][j]; + DB = j; + } else { + H[i + 1][j + 1] = Math.min(H[i][j], Math.min(H[i + 1][j], H[i][j + 1])) + 1; + } + + H[i + 1][j + 1] = Math.min(H[i + 1][j + 1], H[i1][j1] + (i - i1 - 1) + 1 + (j - j1 - 1)); + } + sd.put(s1.charAt(i - 1), i); + } + + return H[s1Len + 1][s2Len + 1]; + } +} diff --git a/src/main/java/org/bukkit/command/defaults/KickCommand.java b/src/main/java/org/bukkit/command/defaults/KickCommand.java new file mode 100644 index 0000000..b6c3f79 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/KickCommand.java @@ -0,0 +1,59 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class KickCommand extends VanillaCommand { + public KickCommand() { + super("kick"); + this.description = "Removes the specified player from the server"; + this.usageMessage = "/kick [reason ...]"; + this.setPermission("bukkit.command.kick"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Player player = Bukkit.getPlayerExact(args[0]); + + if (player != null) { + String reason = "Kicked by an operator."; + + if (args.length > 1) { + reason = createString(args, 1); + } + + player.kickPlayer(reason); + Command.broadcastCommandMessage(sender, "Kicked player " + player.getName() + ". With reason:\n" + reason); + } else { + sender.sendMessage( args[0] + " not found."); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length >= 1) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/KillCommand.java b/src/main/java/org/bukkit/command/defaults/KillCommand.java new file mode 100644 index 0000000..3270db5 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/KillCommand.java @@ -0,0 +1,50 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageEvent; + +import com.google.common.collect.ImmutableList; + +public class KillCommand extends VanillaCommand { + public KillCommand() { + super("kill"); + this.description = "Commits suicide, only usable as a player"; + this.usageMessage = "/kill"; + this.setPermission("bukkit.command.kill"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (sender instanceof Player) { + Player player = (Player) sender; + + EntityDamageEvent ede = new EntityDamageEvent(player, EntityDamageEvent.DamageCause.SUICIDE, 1000); + Bukkit.getPluginManager().callEvent(ede); + if (ede.isCancelled()) return true; + + ede.getEntity().setLastDamageCause(ede); + player.setHealth(0); + sender.sendMessage("Ouch. That look like it hurt."); + } else { + sender.sendMessage("You can only perform this command as a player"); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/ListCommand.java b/src/main/java/org/bukkit/command/defaults/ListCommand.java new file mode 100644 index 0000000..eb8a6a9 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/ListCommand.java @@ -0,0 +1,54 @@ +package org.bukkit.command.defaults; + +import java.util.Collection; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class ListCommand extends VanillaCommand { + public ListCommand() { + super("list"); + this.description = "Lists all online players"; + this.usageMessage = "/list"; + this.setPermission("bukkit.command.list"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + StringBuilder online = new StringBuilder(); + + final Collection players = Bukkit.getOnlinePlayers(); + + for (Player player : players) { + // If a player is hidden from the sender don't show them in the list + if (sender instanceof Player && !((Player) sender).canSee(player)) + continue; + + if (online.length() > 0) { + online.append(", "); + } + + online.append(player.getDisplayName()); + } + + sender.sendMessage("There are " + players.size() + "/" + Bukkit.getMaxPlayers() + " players online:\n" + online.toString()); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/MeCommand.java b/src/main/java/org/bukkit/command/defaults/MeCommand.java new file mode 100644 index 0000000..ddcd9ad --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/MeCommand.java @@ -0,0 +1,35 @@ +package org.bukkit.command.defaults; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +public class MeCommand extends VanillaCommand { + public MeCommand() { + super("me"); + this.description = "Performs the specified action in chat"; + this.usageMessage = "/me "; + this.setPermission("bukkit.command.me"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + StringBuilder message = new StringBuilder(); + message.append(sender.getName()); + + for (String arg : args) { + message.append(" "); + message.append(arg); + } + + Bukkit.broadcastMessage("* " + message.toString()); + + return true; + } +} diff --git a/src/main/java/org/bukkit/command/defaults/OpCommand.java b/src/main/java/org/bukkit/command/defaults/OpCommand.java new file mode 100644 index 0000000..e1f8452 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/OpCommand.java @@ -0,0 +1,75 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class OpCommand extends VanillaCommand { + public OpCommand() { + super("op"); + this.description = "Gives the specified player operator status"; + this.usageMessage = "/op "; + this.setPermission("bukkit.command.op.give"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]); + player.setOp(true); + + Command.broadcastCommandMessage(sender, "Opped " + args[0]); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + if (!(sender instanceof Player)) { + return ImmutableList.of(); + } + + String lastWord = args[0]; + if (lastWord.length() == 0) { + return ImmutableList.of(); + } + + Player senderPlayer = (Player) sender; + + ArrayList matchedPlayers = new ArrayList(); + for (Player player : sender.getServer().getOnlinePlayers()) { + String name = player.getName(); + if (!senderPlayer.canSee(player) || player.isOp()) { + continue; + } + if (StringUtil.startsWithIgnoreCase(name, lastWord)) { + matchedPlayers.add(name); + } + } + + Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); + return matchedPlayers; + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/PardonCommand.java b/src/main/java/org/bukkit/command/defaults/PardonCommand.java new file mode 100644 index 0000000..82c7a95 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/PardonCommand.java @@ -0,0 +1,56 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class PardonCommand extends VanillaCommand { + public PardonCommand() { + super("pardon"); + this.description = "Allows the specified player to use this server"; + this.usageMessage = "/pardon "; + this.setPermission("bukkit.command.unban.player"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Bukkit.getBanList(BanList.Type.NAME).pardon(args[0]); + Command.broadcastCommandMessage(sender, "Pardoned " + args[0]); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + List completions = new ArrayList(); + for (OfflinePlayer player : Bukkit.getBannedPlayers()) { + String name = player.getName(); + if (StringUtil.startsWithIgnoreCase(name, args[0])) { + completions.add(name); + } + } + return completions; + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/PardonIpCommand.java b/src/main/java/org/bukkit/command/defaults/PardonIpCommand.java new file mode 100644 index 0000000..689a0bd --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/PardonIpCommand.java @@ -0,0 +1,52 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class PardonIpCommand extends VanillaCommand { + public PardonIpCommand() { + super("pardon-ip"); + this.description = "Allows the specified IP address to use this server"; + this.usageMessage = "/pardon-ip

          "; + this.setPermission("bukkit.command.unban.ip"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + if (BanIpCommand.ipValidity.matcher(args[0]).matches()) { + Bukkit.unbanIP(args[0]); + Command.broadcastCommandMessage(sender, "Pardoned ip " + args[0]); + } else { + sender.sendMessage("Invalid ip"); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], Bukkit.getIPBans(), new ArrayList()); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java b/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java new file mode 100644 index 0000000..0cb5ca2 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java @@ -0,0 +1,87 @@ +package org.bukkit.command.defaults; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class PlaySoundCommand extends VanillaCommand { + public PlaySoundCommand() { + super("playsound"); + this.description = "Plays a sound to a given player"; + this.usageMessage = "/playsound [x] [y] [z] [volume] [pitch] [minimumVolume]"; + this.setPermission("bukkit.command.playsound"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) { + return true; + } + + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + final String soundArg = args[0]; + final String playerArg = args[1]; + + final Player player = Bukkit.getPlayerExact(playerArg); + if (player == null) { + sender.sendMessage(ChatColor.RED + "Can't find player " + playerArg); + return false; + } + + final Location location = player.getLocation(); + + double x = Math.floor(location.getX()); + double y = Math.floor(location.getY() + 0.5D); + double z = Math.floor(location.getZ()); + double volume = 1.0D; + double pitch = 1.0D; + double minimumVolume = 0.0D; + + switch (args.length) { + default: + case 8: + minimumVolume = getDouble(sender, args[7], 0.0D, 1.0D); + case 7: + pitch = getDouble(sender, args[6], 0.0D, 2.0D); + case 6: + volume = getDouble(sender, args[5], 0.0D, Float.MAX_VALUE); + case 5: + z = getRelativeDouble(z, sender, args[4]); + case 4: + y = getRelativeDouble(y, sender, args[3]); + case 3: + x = getRelativeDouble(x, sender, args[2]); + case 2: + // Noop + } + + final double fixedVolume = volume > 1.0D ? volume * 16.0D : 16.0D; + final Location soundLocation = new Location(player.getWorld(), x, y, z); + if (location.distanceSquared(soundLocation) > fixedVolume * fixedVolume) { + if (minimumVolume <= 0.0D) { + sender.sendMessage(ChatColor.RED + playerArg + " is too far away to hear the sound"); + return false; + } + + final double deltaX = x - location.getX(); + final double deltaY = y - location.getY(); + final double deltaZ = z - location.getZ(); + final double delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / 2.0D; + + if (delta > 0.0D) { + location.add(deltaX / delta, deltaY / delta, deltaZ / delta); + } + + player.playSound(location, soundArg, (float) minimumVolume, (float) pitch); + } else { + player.playSound(soundLocation, soundArg, (float) volume, (float) pitch); + } + sender.sendMessage(String.format("Played '%s' to %s", soundArg, playerArg)); + return true; + } +} diff --git a/src/main/java/org/bukkit/command/defaults/PluginsCommand.java b/src/main/java/org/bukkit/command/defaults/PluginsCommand.java new file mode 100644 index 0000000..b888da1 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/PluginsCommand.java @@ -0,0 +1,43 @@ +package org.bukkit.command.defaults; + +import java.util.Arrays; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; + +public class PluginsCommand extends BukkitCommand { + public PluginsCommand(String name) { + super(name); + this.description = "Gets a list of plugins running on the server"; + this.usageMessage = "/plugins"; + this.setPermission("bukkit.command.plugins"); + this.setAliases(Arrays.asList("pl")); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + sender.sendMessage("Plugins " + getPluginList()); + return true; + } + + private String getPluginList() { + StringBuilder pluginList = new StringBuilder(); + Plugin[] plugins = Bukkit.getPluginManager().getPlugins(); + + for (Plugin plugin : plugins) { + if (pluginList.length() > 0) { + pluginList.append(ChatColor.WHITE); + pluginList.append(", "); + } + + pluginList.append(plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED); + pluginList.append(plugin.getDescription().getName()); + } + + return "(" + plugins.length + "): " + pluginList.toString(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/ReloadCommand.java b/src/main/java/org/bukkit/command/defaults/ReloadCommand.java new file mode 100644 index 0000000..fb3c90f --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/ReloadCommand.java @@ -0,0 +1,28 @@ +package org.bukkit.command.defaults; + +import java.util.Arrays; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class ReloadCommand extends BukkitCommand { + public ReloadCommand(String name) { + super(name); + this.description = "Reloads the server configuration and plugins"; + this.usageMessage = "/reload"; + this.setPermission("bukkit.command.reload"); + this.setAliases(Arrays.asList("rl")); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Bukkit.reload(); + Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Reload complete."); + + return true; + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SaveCommand.java b/src/main/java/org/bukkit/command/defaults/SaveCommand.java new file mode 100644 index 0000000..8a44f9c --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SaveCommand.java @@ -0,0 +1,46 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import com.google.common.collect.ImmutableList; + +public class SaveCommand extends VanillaCommand { + public SaveCommand() { + super("save-all"); + this.description = "Saves the server to disk"; + this.usageMessage = "/save-all"; + this.setPermission("bukkit.command.save.perform"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Command.broadcastCommandMessage(sender, "Forcing save.."); + + Bukkit.savePlayers(); + + for (World world : Bukkit.getWorlds()) { + world.save(); + } + + Command.broadcastCommandMessage(sender, "Save complete."); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SaveOffCommand.java b/src/main/java/org/bukkit/command/defaults/SaveOffCommand.java new file mode 100644 index 0000000..1fbb3f0 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SaveOffCommand.java @@ -0,0 +1,41 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import com.google.common.collect.ImmutableList; + +public class SaveOffCommand extends VanillaCommand { + public SaveOffCommand() { + super("save-off"); + this.description = "Disables server autosaving"; + this.usageMessage = "/save-off"; + this.setPermission("bukkit.command.save.disable"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + for (World world : Bukkit.getWorlds()) { + world.setAutoSave(false); + } + + Command.broadcastCommandMessage(sender, "Disabled level saving.."); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SaveOnCommand.java b/src/main/java/org/bukkit/command/defaults/SaveOnCommand.java new file mode 100644 index 0000000..9774f67 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SaveOnCommand.java @@ -0,0 +1,41 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import com.google.common.collect.ImmutableList; + +public class SaveOnCommand extends VanillaCommand { + public SaveOnCommand() { + super("save-on"); + this.description = "Enables server autosaving"; + this.usageMessage = "/save-on"; + this.setPermission("bukkit.command.save.enable"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + for (World world : Bukkit.getWorlds()) { + world.setAutoSave(true); + } + + Command.broadcastCommandMessage(sender, "Enabled level saving.."); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SayCommand.java b/src/main/java/org/bukkit/command/defaults/SayCommand.java new file mode 100644 index 0000000..658fe21 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SayCommand.java @@ -0,0 +1,62 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class SayCommand extends VanillaCommand { + public SayCommand() { + super("say"); + this.description = "Broadcasts the given message as the sender"; + this.usageMessage = "/say "; + this.setPermission("bukkit.command.say"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + StringBuilder message = new StringBuilder(); + message.append(ChatColor.LIGHT_PURPLE).append("["); + if (sender instanceof ConsoleCommandSender) { + message.append("Server"); + } else if (sender instanceof Player) { + message.append(((Player) sender).getDisplayName()); + } else { + message.append(sender.getName()); + } + message.append(ChatColor.LIGHT_PURPLE).append("] "); + + if (args.length > 0) { + message.append(args[0]); + for (int i = 1; i < args.length; i++) { + message.append(" ").append(args[i]); + } + } + + Bukkit.broadcastMessage(message.toString()); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + + if (args.length >= 1) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java b/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java new file mode 100644 index 0000000..f0490cf --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java @@ -0,0 +1,617 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +public class ScoreboardCommand extends VanillaCommand { + + private static final List MAIN_CHOICES = ImmutableList.of("objectives", "players", "teams"); + private static final List OBJECTIVES_CHOICES = ImmutableList.of("list", "add", "remove", "setdisplay"); + private static final List OBJECTIVES_CRITERIA = ImmutableList.of("health", "playerKillCount", "totalKillCount", "deathCount", "dummy"); + private static final List PLAYERS_CHOICES = ImmutableList.of("set", "add", "remove", "reset", "list"); + private static final List TEAMS_CHOICES = ImmutableList.of("add", "remove", "join", "leave", "empty", "list", "option"); + private static final List TEAMS_OPTION_CHOICES = ImmutableList.of("color", "friendlyfire", "seeFriendlyInvisibles"); + private static final Map OBJECTIVES_DISPLAYSLOT = ImmutableMap.of("belowName", DisplaySlot.BELOW_NAME, "list", DisplaySlot.PLAYER_LIST, "sidebar", DisplaySlot.SIDEBAR); + private static final Map TEAMS_OPTION_COLOR = ImmutableMap.builder() + .put("aqua", ChatColor.AQUA) + .put("black", ChatColor.BLACK) + .put("blue", ChatColor.BLUE) + .put("bold", ChatColor.BOLD) + .put("dark_aqua", ChatColor.DARK_AQUA) + .put("dark_blue", ChatColor.DARK_BLUE) + .put("dark_gray", ChatColor.DARK_GRAY) + .put("dark_green", ChatColor.DARK_GREEN) + .put("dark_purple", ChatColor.DARK_PURPLE) + .put("dark_red", ChatColor.DARK_RED) + .put("gold", ChatColor.GOLD) + .put("gray", ChatColor.GRAY) + .put("green", ChatColor.GREEN) + .put("italic", ChatColor.ITALIC) + .put("light_purple", ChatColor.LIGHT_PURPLE) + .put("obfuscated", ChatColor.MAGIC) // This is the important line + .put("red", ChatColor.RED) + .put("reset", ChatColor.RESET) + .put("strikethrough", ChatColor.STRIKETHROUGH) + .put("underline", ChatColor.UNDERLINE) + .put("white", ChatColor.WHITE) + .put("yellow", ChatColor.YELLOW) + .build(); + private static final List BOOLEAN = ImmutableList.of("true", "false"); + + public ScoreboardCommand() { + super("scoreboard"); + this.description = "Scoreboard control"; + this.usageMessage = "/scoreboard"; + this.setPermission("bukkit.command.scoreboard"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) + return true; + if (args.length < 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: /scoreboard "); + return false; + } + + final Scoreboard mainScoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); + + if (args[0].equalsIgnoreCase("objectives")) { + if (args.length == 1) { + sender.sendMessage(ChatColor.RED + "Usage: /scoreboard objectives "); + return false; + } + if (args[1].equalsIgnoreCase("list")) { + Set objectives = mainScoreboard.getObjectives(); + if (objectives.isEmpty()) { + sender.sendMessage(ChatColor.RED + "There are no objectives on the scoreboard"); + return false; + } + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + objectives.size() + " objective(s) on scoreboard"); + for (Objective objective : objectives) { + sender.sendMessage("- " + objective.getName() + ": displays as '" + objective.getDisplayName() + "' and is type '" + objective.getCriteria() + "'"); + } + } else if (args[1].equalsIgnoreCase("add")) { + if (args.length < 4) { + sender.sendMessage(ChatColor.RED + "/scoreboard objectives add [display name ...]"); + return false; + } + String name = args[2]; + String criteria = args[3]; + + if (criteria == null) { + sender.sendMessage(ChatColor.RED + "Invalid objective criteria type. Valid types are: " + stringCollectionToString(OBJECTIVES_CRITERIA)); + } else if (name.length() > 16) { + sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for an objective, it can be at most 16 characters long"); + } else if (mainScoreboard.getObjective(name) != null) { + sender.sendMessage(ChatColor.RED + "An objective with the name '" + name + "' already exists"); + } else { + String displayName = null; + if (args.length > 4) { + displayName = StringUtils.join(ArrayUtils.subarray(args, 4, args.length), ' '); + if (displayName.length() > 32) { + sender.sendMessage(ChatColor.RED + "The name '" + displayName + "' is too long for an objective, it can be at most 32 characters long"); + return false; + } + } + Objective objective = mainScoreboard.registerNewObjective(name, criteria); + if (displayName != null && displayName.length() > 0) { + objective.setDisplayName(displayName); + } + sender.sendMessage("Added new objective '" + name + "' successfully"); + } + } else if (args[1].equalsIgnoreCase("remove")) { + if (args.length != 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard objectives remove "); + return false; + } + String name = args[2]; + Objective objective = mainScoreboard.getObjective(name); + if (objective == null) { + sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + name + "'"); + } else { + objective.unregister(); + sender.sendMessage("Removed objective '" + name + "' successfully"); + } + } else if (args[1].equalsIgnoreCase("setdisplay")) { + if (args.length != 3 && args.length != 4) { + sender.sendMessage(ChatColor.RED + "/scoreboard objectives setdisplay [objective]"); + return false; + } + String slotName = args[2]; + DisplaySlot slot = OBJECTIVES_DISPLAYSLOT.get(slotName); + if (slot == null) { + sender.sendMessage(ChatColor.RED + "No such display slot '" + slotName + "'"); + } else { + if (args.length == 4) { + String objectiveName = args[3]; + Objective objective = mainScoreboard.getObjective(objectiveName); + if (objective == null) { + sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'"); + return false; + } + + objective.setDisplaySlot(slot); + sender.sendMessage("Set the display objective in slot '" + slotName + "' to '" + objective.getName() + "'"); + } else { + Objective objective = mainScoreboard.getObjective(slot); + if (objective != null) { + objective.setDisplaySlot(null); + } + sender.sendMessage("Cleared objective display slot '" + slotName + "'"); + } + } + } + } else if (args[0].equalsIgnoreCase("players")) { + if (args.length == 1) { + sender.sendMessage(ChatColor.RED + "/scoreboard players "); + return false; + } + if (args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) { + if (args.length != 5) { + if (args[1].equalsIgnoreCase("set")) { + sender.sendMessage(ChatColor.RED + "/scoreboard players set "); + } else if (args[1].equalsIgnoreCase("add")) { + sender.sendMessage(ChatColor.RED + "/scoreboard players add "); + } else { + sender.sendMessage(ChatColor.RED + "/scoreboard players remove "); + } + return false; + } + String objectiveName = args[3]; + Objective objective = mainScoreboard.getObjective(objectiveName); + if (objective == null) { + sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'"); + return false; + } else if (!objective.isModifiable()) { + sender.sendMessage(ChatColor.RED + "The objective '" + objectiveName + "' is read-only and cannot be set"); + return false; + } + + String valueString = args[4]; + int value; + try { + value = Integer.parseInt(valueString); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "'" + valueString + "' is not a valid number"); + return false; + } + if (value < 1 && !args[1].equalsIgnoreCase("set")) { + sender.sendMessage(ChatColor.RED + "The number you have entered (" + value + ") is too small, it must be at least 1"); + return false; + } + + String playerName = args[2]; + if (playerName.length() > 16) { + sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name"); + return false; + } + Score score = objective.getScore(playerName); + int newScore; + if (args[1].equalsIgnoreCase("set")) { + newScore = value; + } else if (args[1].equalsIgnoreCase("add")) { + newScore = score.getScore() + value; + } else { + newScore = score.getScore() - value; + } + score.setScore(newScore); + sender.sendMessage("Set score of " + objectiveName + " for player " + playerName + " to " + newScore); + } else if (args[1].equalsIgnoreCase("reset")) { + if (args.length != 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard players reset "); + return false; + } + String playerName = args[2]; + if (playerName.length() > 16) { + sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name"); + return false; + } + mainScoreboard.resetScores(playerName); + sender.sendMessage("Reset all scores of player " + playerName); + } else if (args[1].equalsIgnoreCase("list")) { + if (args.length > 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard players list "); + return false; + } + if (args.length == 2) { + Set entries = mainScoreboard.getEntries(); + if (entries.isEmpty()) { + sender.sendMessage(ChatColor.RED + "There are no tracked players on the scoreboard"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + entries.size() + " tracked players on the scoreboard"); + sender.sendMessage(stringCollectionToString(entries)); + } + } else { + String playerName = args[2]; + if (playerName.length() > 16) { + sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name"); + return false; + } + Set scores = mainScoreboard.getScores(playerName); + if (scores.isEmpty()) { + sender.sendMessage(ChatColor.RED + "Player " + playerName + " has no scores recorded"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + scores.size() + " tracked objective(s) for " + playerName); + for (Score score : scores) { + sender.sendMessage("- " + score.getObjective().getDisplayName() + ": " + score.getScore() + " (" + score.getObjective().getName() + ")"); + } + } + } + } + } else if (args[0].equalsIgnoreCase("teams")) { + if (args.length == 1) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams "); + return false; + } + if (args[1].equalsIgnoreCase("list")) { + if (args.length == 2) { + Set teams = mainScoreboard.getTeams(); + if (teams.isEmpty()) { + sender.sendMessage(ChatColor.RED + "There are no teams registered on the scoreboard"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + teams.size() + " teams on the scoreboard"); + for (Team team : teams) { + sender.sendMessage("- " + team.getName() + ": '" + team.getDisplayName() + "' has " + team.getSize() + " players"); + } + } + } else if (args.length == 3) { + String teamName = args[2]; + Team team = mainScoreboard.getTeam(teamName); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'"); + } else { + Set players = team.getPlayers(); + if (players.isEmpty()) { + sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " has no players"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + players.size() + " player(s) in team " + team.getName()); + sender.sendMessage(offlinePlayerSetToString(players)); + } + } + } else { + sender.sendMessage(ChatColor.RED + "/scoreboard teams list [name]"); + return false; + } + } else if (args[1].equalsIgnoreCase("add")) { + if (args.length < 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams add [display name ...]"); + return false; + } + String name = args[2]; + if (name.length() > 16) { + sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for a team, it can be at most 16 characters long"); + } else if (mainScoreboard.getTeam(name) != null) { + sender.sendMessage(ChatColor.RED + "A team with the name '" + name + "' already exists"); + } else { + String displayName = null; + if (args.length > 3) { + displayName = StringUtils.join(ArrayUtils.subarray(args, 3, args.length), ' '); + if (displayName.length() > 32) { + sender.sendMessage(ChatColor.RED + "The display name '" + displayName + "' is too long for a team, it can be at most 32 characters long"); + return false; + } + } + Team team = mainScoreboard.registerNewTeam(name); + if (displayName != null && displayName.length() > 0) { + team.setDisplayName(displayName); + } + sender.sendMessage("Added new team '" + team.getName() + "' successfully"); + } + } else if (args[1].equalsIgnoreCase("remove")) { + if (args.length != 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams remove "); + return false; + } + String name = args[2]; + Team team = mainScoreboard.getTeam(name); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'"); + } else { + team.unregister(); + sender.sendMessage("Removed team " + name); + } + } else if (args[1].equalsIgnoreCase("empty")) { + if (args.length != 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams clear "); + return false; + } + String name = args[2]; + Team team = mainScoreboard.getTeam(name); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'"); + } else { + Set players = team.getPlayers(); + if (players.isEmpty()) { + sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " is already empty, cannot remove nonexistant players"); + } else { + for (OfflinePlayer player : players) { + team.removePlayer(player); + } + sender.sendMessage("Removed all " + players.size() + " player(s) from team " + team.getName()); + } + } + } else if (args[1].equalsIgnoreCase("join")) { + if ((sender instanceof Player) ? args.length < 3 : args.length < 4) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams join [player...]"); + return false; + } + String teamName = args[2]; + Team team = mainScoreboard.getTeam(teamName); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'"); + } else { + Set addedPlayers = new HashSet(); + if ((sender instanceof Player) && args.length == 3) { + team.addPlayer((Player) sender); + addedPlayers.add(sender.getName()); + } else { + for (int i = 3; i < args.length; i++) { + String playerName = args[i]; + OfflinePlayer offlinePlayer; + Player player = Bukkit.getPlayerExact(playerName); + if (player != null) { + offlinePlayer = player; + } else { + offlinePlayer = Bukkit.getOfflinePlayer(playerName); + } + team.addPlayer(offlinePlayer); + addedPlayers.add(offlinePlayer.getName()); + } + } + sender.sendMessage("Added " + addedPlayers.size() + " player(s) to team " + team.getName() + ": " + stringCollectionToString(addedPlayers)); + } + } else if (args[1].equalsIgnoreCase("leave")) { + if (!(sender instanceof Player) && args.length < 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams leave [player...]"); + return false; + } + Set left = new HashSet(); + Set noTeam = new HashSet(); + if ((sender instanceof Player) && args.length == 2) { + Team team = mainScoreboard.getPlayerTeam((Player) sender); + if (team != null) { + team.removePlayer((Player) sender); + left.add(sender.getName()); + } else { + noTeam.add(sender.getName()); + } + } else { + for (int i = 2; i < args.length; i++) { + String playerName = args[i]; + OfflinePlayer offlinePlayer; + Player player = Bukkit.getPlayerExact(playerName); + if (player != null) { + offlinePlayer = player; + } else { + offlinePlayer = Bukkit.getOfflinePlayer(playerName); + } + Team team = mainScoreboard.getPlayerTeam(offlinePlayer); + if (team != null) { + team.removePlayer(offlinePlayer); + left.add(offlinePlayer.getName()); + } else { + noTeam.add(offlinePlayer.getName()); + } + } + } + if (!left.isEmpty()) { + sender.sendMessage("Removed " + left.size() + " player(s) from their teams: " + stringCollectionToString(left)); + } + if (!noTeam.isEmpty()) { + sender.sendMessage("Could not remove " + noTeam.size() + " player(s) from their teams: " + stringCollectionToString(noTeam)); + } + } else if (args[1].equalsIgnoreCase("option")) { + if (args.length != 4 && args.length != 5) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams option "); + return false; + } + String teamName = args[2]; + Team team = mainScoreboard.getTeam(teamName); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'"); + return false; + } + String option = args[3].toLowerCase(); + if (!option.equals("friendlyfire") && !option.equals("color") && !option.equals("seefriendlyinvisibles")) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams option "); + return false; + } + if (args.length == 4) { + if (option.equals("color")) { + sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet())); + } else { + sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false"); + } + } else { + String value = args[4].toLowerCase(); + if (option.equals("color")) { + ChatColor color = TEAMS_OPTION_COLOR.get(value); + if (color == null) { + sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet())); + return false; + } + team.setPrefix(color.toString()); + team.setSuffix(ChatColor.RESET.toString()); + } else { + if (!value.equals("true") && !value.equals("false")) { + sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false"); + return false; + } + if (option.equals("friendlyfire")) { + team.setAllowFriendlyFire(value.equals("true")); + } else { + team.setCanSeeFriendlyInvisibles(value.equals("true")); + } + } + sender.sendMessage("Set option " + option + " for team " + team.getName() + " to " + value); + } + } + } else { + sender.sendMessage(ChatColor.RED + "Usage: /scoreboard "); + return false; + } + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], MAIN_CHOICES, new ArrayList()); + } + if (args.length > 1) { + if (args[0].equalsIgnoreCase("objectives")) { + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], OBJECTIVES_CHOICES, new ArrayList()); + } + if (args[1].equalsIgnoreCase("add")) { + if (args.length == 4) { + return StringUtil.copyPartialMatches(args[3], OBJECTIVES_CRITERIA, new ArrayList()); + } + } else if (args[1].equalsIgnoreCase("remove")) { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentObjectives(), new ArrayList()); + } + } else if (args[1].equalsIgnoreCase("setdisplay")) { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], OBJECTIVES_DISPLAYSLOT.keySet(), new ArrayList()); + } + if (args.length == 4) { + return StringUtil.copyPartialMatches(args[3], this.getCurrentObjectives(), new ArrayList()); + } + } + } else if (args[0].equalsIgnoreCase("players")) { + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], PLAYERS_CHOICES, new ArrayList()); + } + if (args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) { + if (args.length == 3) { + return super.tabComplete(sender, alias, args); + } + if (args.length == 4) { + return StringUtil.copyPartialMatches(args[3], this.getCurrentObjectives(), new ArrayList()); + } + } else { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentEntries(), new ArrayList()); + } + } + } else if (args[0].equalsIgnoreCase("teams")) { + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], TEAMS_CHOICES, new ArrayList()); + } + if (args[1].equalsIgnoreCase("join")) { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList()); + } + if (args.length >= 4) { + return super.tabComplete(sender, alias, args); + } + } else if (args[1].equalsIgnoreCase("leave")) { + return super.tabComplete(sender, alias, args); + } else if (args[1].equalsIgnoreCase("option")) { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList()); + } + if (args.length == 4) { + return StringUtil.copyPartialMatches(args[3], TEAMS_OPTION_CHOICES, new ArrayList()); + } + if (args.length == 5) { + if (args[3].equalsIgnoreCase("color")) { + return StringUtil.copyPartialMatches(args[4], TEAMS_OPTION_COLOR.keySet(), new ArrayList()); + } else { + return StringUtil.copyPartialMatches(args[4], BOOLEAN, new ArrayList()); + } + } + } else { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList()); + } + } + } + } + + return ImmutableList.of(); + } + + private static String offlinePlayerSetToString(Set set) { + StringBuilder string = new StringBuilder(); + String lastValue = null; + for (OfflinePlayer value : set) { + string.append(lastValue = value.getName()).append(", "); + } + string.delete(string.length() - 2, Integer.MAX_VALUE); + if (string.length() != lastValue.length()) { + string.insert(string.length() - lastValue.length(), "and "); + } + return string.toString(); + + } + + private static String stringCollectionToString(Collection set) { + StringBuilder string = new StringBuilder(); + String lastValue = null; + for (String value : set) { + string.append(lastValue = value).append(", "); + } + string.delete(string.length() - 2, Integer.MAX_VALUE); + if (string.length() != lastValue.length()) { + string.insert(string.length() - lastValue.length(), "and "); + } + return string.toString(); + } + + private List getCurrentObjectives() { + List list = new ArrayList(); + for (Objective objective : Bukkit.getScoreboardManager().getMainScoreboard().getObjectives()) { + list.add(objective.getName()); + } + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + return list; + } + + private List getCurrentEntries() { + List list = new ArrayList(); + for (String entry : Bukkit.getScoreboardManager().getMainScoreboard().getEntries()) { + list.add(entry); + } + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + return list; + } + + private List getCurrentTeams() { + List list = new ArrayList(); + for (Team team : Bukkit.getScoreboardManager().getMainScoreboard().getTeams()) { + list.add(team.getName()); + } + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + return list; + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SeedCommand.java b/src/main/java/org/bukkit/command/defaults/SeedCommand.java new file mode 100644 index 0000000..b64fd40 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SeedCommand.java @@ -0,0 +1,41 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class SeedCommand extends VanillaCommand { + public SeedCommand() { + super("seed"); + this.description = "Shows the world seed"; + this.usageMessage = "/seed"; + this.setPermission("bukkit.command.seed"); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) return true; + long seed; + if (sender instanceof Player) { + seed = ((Player) sender).getWorld().getSeed(); + } else { + seed = Bukkit.getWorlds().get(0).getSeed(); + } + sender.sendMessage("Seed: " + seed); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SetIdleTimeoutCommand.java b/src/main/java/org/bukkit/command/defaults/SetIdleTimeoutCommand.java new file mode 100644 index 0000000..6b8bb2d --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SetIdleTimeoutCommand.java @@ -0,0 +1,53 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.List; + +public class SetIdleTimeoutCommand extends VanillaCommand { + + public SetIdleTimeoutCommand() { + super("setidletimeout"); + this.description = "Sets the server's idle timeout"; + this.usageMessage = "/setidletimeout "; + this.setPermission("bukkit.command.setidletimeout"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length == 1) { + int minutes; + + try { + minutes = getInteger(sender, args[0], 0, Integer.MAX_VALUE, true); + } catch (NumberFormatException ex) { + sender.sendMessage(ex.getMessage()); + return true; + } + + Bukkit.getServer().setIdleTimeout(minutes); + + Command.broadcastCommandMessage(sender, "Successfully set the idle timeout to " + minutes + " minutes."); + return true; + } + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SetWorldSpawnCommand.java b/src/main/java/org/bukkit/command/defaults/SetWorldSpawnCommand.java new file mode 100644 index 0000000..59c5059 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SetWorldSpawnCommand.java @@ -0,0 +1,79 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +public class SetWorldSpawnCommand extends VanillaCommand { + + public SetWorldSpawnCommand() { + super("setworldspawn"); + this.description = "Sets a worlds's spawn point. If no coordinates are specified, the player's coordinates will be used."; + this.usageMessage = "/setworldspawn OR /setworldspawn "; + this.setPermission("bukkit.command.setworldspawn"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Player player = null; + World world; + if (sender instanceof Player) { + player = (Player) sender; + world = player.getWorld(); + } else { + world = Bukkit.getWorlds().get(0); + } + + final int x, y, z; + + if (args.length == 0) { + if (player == null) { + sender.sendMessage("You can only perform this command as a player"); + return true; + } + + Location location = player.getLocation(); + + x = location.getBlockX(); + y = location.getBlockY(); + z = location.getBlockZ(); + } else if (args.length == 3) { + try { + x = getInteger(sender, args[0], MIN_COORD, MAX_COORD, true); + y = getInteger(sender, args[1], 0, world.getMaxHeight(), true); + z = getInteger(sender, args[2], MIN_COORD, MAX_COORD, true); + } catch (NumberFormatException ex) { + sender.sendMessage(ex.getMessage()); + return true; + } + } else { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + world.setSpawnLocation(x, y, z); + + Command.broadcastCommandMessage(sender, "Set world " + world.getName() + "'s spawnpoint to (" + x + ", " + y + ", " + z + ")"); + return true; + + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SpawnpointCommand.java b/src/main/java/org/bukkit/command/defaults/SpawnpointCommand.java new file mode 100644 index 0000000..4214bee --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SpawnpointCommand.java @@ -0,0 +1,87 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +public class SpawnpointCommand extends VanillaCommand { + + public SpawnpointCommand() { + super("spawnpoint"); + this.description = "Sets a player's spawn point"; + this.usageMessage = "/spawnpoint OR /spawnpoint OR /spawnpoint "; + this.setPermission("bukkit.command.spawnpoint"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Player player; + + if (args.length == 0) { + if (sender instanceof Player) { + player = (Player) sender; + } else { + sender.sendMessage("Please provide a player!"); + return true; + } + } else { + player = Bukkit.getPlayerExact(args[0]); + if (player == null) { + sender.sendMessage("Can't find player " + args[0]); + return true; + } + } + + World world = player.getWorld(); + + if (args.length == 4) { + if (world != null) { + int pos = 1; + final int x, y, z; + try { + x = getInteger(sender, args[pos++], MIN_COORD, MAX_COORD, true); + y = getInteger(sender, args[pos++], 0, world.getMaxHeight()); + z = getInteger(sender, args[pos], MIN_COORD, MAX_COORD, true); + } catch(NumberFormatException ex) { + sender.sendMessage(ex.getMessage()); + return true; + } + + player.setBedSpawnLocation(new Location(world, x, y, z), true); + Command.broadcastCommandMessage(sender, "Set " + player.getDisplayName() + "'s spawnpoint to " + x + ", " + y + ", " + z); + } + } else if (args.length <= 1) { + Location location = player.getLocation(); + player.setBedSpawnLocation(location, true); + Command.broadcastCommandMessage(sender, "Set " + player.getDisplayName() + "'s spawnpoint to " + location.getX() + ", " + location.getY() + ", " + location.getZ()); + } else { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/SpreadPlayersCommand.java b/src/main/java/org/bukkit/command/defaults/SpreadPlayersCommand.java new file mode 100644 index 0000000..5297cf7 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/SpreadPlayersCommand.java @@ -0,0 +1,265 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Team; + +public class SpreadPlayersCommand extends VanillaCommand { + private static final Random random = new Random(); + + public SpreadPlayersCommand() { + super("spreadplayers"); + this.description = "Spreads players around a point"; + this.usageMessage = "/spreadplayers "; + this.setPermission("bukkit.command.spreadplayers"); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) { + return true; + } + + if (args.length < 6) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + final double x = getDouble(sender, args[0], -30000000, 30000000); + final double z = getDouble(sender, args[1], -30000000, 30000000); + final double distance = getDouble(sender, args[2]); + final double range = getDouble(sender, args[3]); + + if (distance < 0.0D) { + sender.sendMessage(ChatColor.RED + "Distance is too small."); + return false; + } + + if (range < distance + 1.0D) { + sender.sendMessage(ChatColor.RED + "Max range is too small."); + return false; + } + + final String respectTeams = args[4]; + boolean teams = false; + + if (respectTeams.equalsIgnoreCase("true")) { + teams = true; + } else if (!respectTeams.equalsIgnoreCase("false")) { + sender.sendMessage(String.format(ChatColor.RED + "'%s' is not true or false", args[4])); + return false; + } + + List players = Lists.newArrayList(); + World world = null; + + for (int i = 5; i < args.length; i++) { + Player player = Bukkit.getPlayerExact(args[i]); + if (player == null) { + continue; + } + + if (world == null) { + world = player.getWorld(); + } + players.add(player); + } + + if (world == null) { + return true; + } + + final double xRangeMin = x - range; + final double zRangeMin = z - range; + final double xRangeMax = x + range; + final double zRangeMax = z + range; + + final int spreadSize = teams ? getTeams(players) : players.size(); + + final Location[] locations = getSpreadLocations(world, spreadSize, xRangeMin, zRangeMin, xRangeMax, zRangeMax); + final int rangeSpread = range(world, distance, xRangeMin, zRangeMin, xRangeMax, zRangeMax, locations); + + if (rangeSpread == -1) { + sender.sendMessage(String.format("Could not spread %d %s around %s,%s (too many players for space - try using spread of at most %s)", spreadSize, teams ? "teams" : "players", x, z)); + return false; + } + + final double distanceSpread = spread(world, players, locations, teams); + + sender.sendMessage(String.format("Succesfully spread %d %s around %s,%s", locations.length, teams ? "teams" : "players", x, z)); + if (locations.length > 1) { + sender.sendMessage(String.format("(Average distance between %s is %s blocks apart after %s iterations)", teams ? "teams" : "players", String.format("%.2f", distanceSpread), rangeSpread)); + } + return true; + } + + private int range(World world, double distance, double xRangeMin, double zRangeMin, double xRangeMax, double zRangeMax, Location[] locations) { + boolean flag = true; + double max; + + int i; + + for (i = 0; i < 10000 && flag; ++i) { + flag = false; + max = Float.MAX_VALUE; + + Location loc1; + int j; + + for (int k = 0; k < locations.length; ++k) { + Location loc2 = locations[k]; + + j = 0; + loc1 = new Location(world, 0, 0, 0); + + for (int l = 0; l < locations.length; ++l) { + if (k != l) { + Location loc3 = locations[l]; + double dis = loc2.distanceSquared(loc3); + + max = Math.min(dis, max); + if (dis < distance) { + ++j; + loc1.add(loc3.getX() - loc2.getX(), 0, 0); + loc1.add(loc3.getZ() - loc2.getZ(), 0, 0); + } + } + } + + if (j > 0) { + loc2.setX(loc2.getX() / j); + loc2.setZ(loc2.getZ() / j); + double d7 = Math.sqrt(loc1.getX() * loc1.getX() + loc1.getZ() * loc1.getZ()); + + if (d7 > 0.0D) { + loc1.setX(loc1.getX() / d7); + loc2.add(-loc1.getX(), 0, -loc1.getZ()); + } else { + double x = xRangeMin >= xRangeMax ? xRangeMin : random.nextDouble() * (xRangeMax - xRangeMin) + xRangeMin; + double z = zRangeMin >= zRangeMax ? zRangeMin : random.nextDouble() * (zRangeMax - zRangeMin) + zRangeMin; + loc2.setX(x); + loc2.setZ(z); + } + + flag = true; + } + + boolean swap = false; + + if (loc2.getX() < xRangeMin) { + loc2.setX(xRangeMin); + swap = true; + } else if (loc2.getX() > xRangeMax) { + loc2.setX(xRangeMax); + swap = true; + } + + if (loc2.getZ() < zRangeMin) { + loc2.setZ(zRangeMin); + swap = true; + } else if (loc2.getZ() > zRangeMax) { + loc2.setZ(zRangeMax); + swap = true; + } + if (swap) { + flag = true; + } + } + + if (!flag) { + Location[] locs = locations; + int i1 = locations.length; + + for (j = 0; j < i1; ++j) { + loc1 = locs[j]; + if (world.getHighestBlockYAt(loc1) == 0) { + double x = xRangeMin >= xRangeMax ? xRangeMin : random.nextDouble() * (xRangeMax - xRangeMin) + xRangeMin; + double z = zRangeMin >= zRangeMax ? zRangeMin : random.nextDouble() * (zRangeMax - zRangeMin) + zRangeMin; + locations[i] = (new Location(world, x, 0, z)); + loc1.setX(x); + loc1.setZ(z); + flag = true; + } + } + } + } + + if (i >= 10000) { + return -1; + } else { + return i; + } + } + + private double spread(World world, List list, Location[] locations, boolean teams) { + double distance = 0.0D; + int i = 0; + Map hashmap = Maps.newHashMap(); + + for (int j = 0; j < list.size(); ++j) { + Player player = list.get(j); + Location location; + + if (teams) { + Team team = player.getScoreboard().getPlayerTeam(player); + + if (!hashmap.containsKey(team)) { + hashmap.put(team, locations[i++]); + } + + location = hashmap.get(team); + } else { + location = locations[i++]; + } + + player.teleport(new Location(world, Math.floor(location.getX()) + 0.5D, world.getHighestBlockYAt((int) location.getX(), (int) location.getZ()), Math.floor(location.getZ()) + 0.5D)); + double value = Double.MAX_VALUE; + + for (int k = 0; k < locations.length; ++k) { + if (location != locations[k]) { + double d = location.distanceSquared(locations[k]); + value = Math.min(d, value); + } + } + + distance += value; + } + + distance /= list.size(); + return distance; + } + + private int getTeams(List players) { + Set teams = Sets.newHashSet(); + + for (Player player : players) { + teams.add(player.getScoreboard().getPlayerTeam(player)); + } + + return teams.size(); + } + + private Location[] getSpreadLocations(World world, int size, double xRangeMin, double zRangeMin, double xRangeMax, double zRangeMax) { + Location[] locations = new Location[size]; + + for (int i = 0; i < size; ++i) { + double x = xRangeMin >= xRangeMax ? xRangeMin : random.nextDouble() * (xRangeMax - xRangeMin) + xRangeMin; + double z = zRangeMin >= zRangeMax ? zRangeMin : random.nextDouble() * (zRangeMax - zRangeMin) + zRangeMin; + locations[i] = (new Location(world, x, 0, z)); + } + + return locations; + } +} diff --git a/src/main/java/org/bukkit/command/defaults/StopCommand.java b/src/main/java/org/bukkit/command/defaults/StopCommand.java new file mode 100644 index 0000000..be70e63 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/StopCommand.java @@ -0,0 +1,48 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; + +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class StopCommand extends VanillaCommand { + public StopCommand() { + super("stop"); + this.description = "Stops the server with optional reason"; + this.usageMessage = "/stop [reason]"; + this.setPermission("bukkit.command.stop"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Command.broadcastCommandMessage(sender, "Stopping the server.."); + Bukkit.shutdown(); + + String reason = this.createString(args, 0); + if (StringUtils.isNotEmpty(reason)) { + for (Player player : Bukkit.getOnlinePlayers()) { + player.kickPlayer(reason); + } + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/TeleportCommand.java b/src/main/java/org/bukkit/command/defaults/TeleportCommand.java new file mode 100644 index 0000000..fd1b9bd --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/TeleportCommand.java @@ -0,0 +1,124 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + +import com.google.common.collect.ImmutableList; + +public class TeleportCommand extends VanillaCommand { + + public TeleportCommand() { + super("tp"); + this.description = "Teleports the given player (or yourself) to another player or coordinates"; + this.usageMessage = "/tp [player] and/or "; + this.setPermission("bukkit.command.teleport"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1 || args.length > 4) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Player player; + + if (args.length == 1 || args.length == 3) { + if (sender instanceof Player) { + player = (Player) sender; + } else { + sender.sendMessage("Please provide a player!"); + return true; + } + } else { + player = Bukkit.getPlayerExact(args[0]); + } + + if (player == null) { + sender.sendMessage("Player not found: " + args[0]); + return true; + } + + if (args.length < 3) { + Player target = Bukkit.getPlayerExact(args[args.length - 1]); + if (target == null) { + sender.sendMessage("Can't find player " + args[args.length - 1] + ". No tp."); + return true; + } + player.teleport(target, TeleportCause.COMMAND); + Command.broadcastCommandMessage(sender, "Teleported " + player.getDisplayName() + " to " + target.getDisplayName()); + } else if (player.getWorld() != null) { + Location playerLocation = player.getLocation(); + double x = getCoordinate(sender, playerLocation.getX(), args[args.length - 3]); + double y = getCoordinate(sender, playerLocation.getY(), args[args.length - 2], 0, 0); + double z = getCoordinate(sender, playerLocation.getZ(), args[args.length - 1]); + + if (x == MIN_COORD_MINUS_ONE || y == MIN_COORD_MINUS_ONE || z == MIN_COORD_MINUS_ONE) { + sender.sendMessage("Please provide a valid location!"); + return true; + } + + playerLocation.setX(x); + playerLocation.setY(y); + playerLocation.setZ(z); + + player.teleport(playerLocation, TeleportCause.COMMAND); + Command.broadcastCommandMessage(sender, String.format("Teleported %s to %.2f, %.2f, %.2f", player.getDisplayName(), x, y, z)); + } + return true; + } + + private double getCoordinate(CommandSender sender, double current, String input) { + return getCoordinate(sender, current, input, MIN_COORD, MAX_COORD); + } + + private double getCoordinate(CommandSender sender, double current, String input, int min, int max) { + boolean relative = input.startsWith("~"); + double result = relative ? current : 0; + + if (!relative || input.length() > 1) { + boolean exact = input.contains("."); + if (relative) input = input.substring(1); + + double testResult = getDouble(sender, input); + if (testResult == MIN_COORD_MINUS_ONE) { + return MIN_COORD_MINUS_ONE; + } + result += testResult; + + if (!exact && !relative) result += 0.5f; + } + if (min != 0 || max != 0) { + if (result < min) { + result = MIN_COORD_MINUS_ONE; + } + + if (result > max) { + result = MIN_COORD_MINUS_ONE; + } + } + + return result; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1 || args.length == 2) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/TellCommand.java b/src/main/java/org/bukkit/command/defaults/TellCommand.java new file mode 100644 index 0000000..287f49f --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/TellCommand.java @@ -0,0 +1,48 @@ +package org.bukkit.command.defaults; + +import java.util.Arrays; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class TellCommand extends VanillaCommand { + public TellCommand() { + super("tell"); + this.description = "Sends a private message to the given player"; + this.usageMessage = "/tell "; + this.setAliases(Arrays.asList(new String[] { "w", "msg" })); + this.setPermission("bukkit.command.tell"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Player player = Bukkit.getPlayerExact(args[0]); + + // If a player is hidden from the sender pretend they are offline + if (player == null || (sender instanceof Player && !((Player) sender).canSee(player))) { + sender.sendMessage("There's no player by that name online."); + } else { + StringBuilder message = new StringBuilder(); + + for (int i = 1; i < args.length; i++) { + if (i > 1) message.append(" "); + message.append(args[i]); + } + + String result = ChatColor.GRAY + sender.getName() + " whispers " + message; + + sender.sendMessage("[" + sender.getName() + "->" + player.getName() + "] " + message); + player.sendMessage(result); + } + + return true; + } +} diff --git a/src/main/java/org/bukkit/command/defaults/TestForCommand.java b/src/main/java/org/bukkit/command/defaults/TestForCommand.java new file mode 100644 index 0000000..c9ac1ce --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/TestForCommand.java @@ -0,0 +1,26 @@ +package org.bukkit.command.defaults; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +public class TestForCommand extends VanillaCommand { + public TestForCommand() { + super("testfor"); + this.description = "Tests whether a specifed player is online"; + this.usageMessage = "/testfor "; + this.setPermission("bukkit.command.testfor"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + sender.sendMessage(ChatColor.RED + "/testfor is only usable by commandblocks with analog output."); + return true; + } +} diff --git a/src/main/java/org/bukkit/command/defaults/TimeCommand.java b/src/main/java/org/bukkit/command/defaults/TimeCommand.java new file mode 100644 index 0000000..86083b4 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/TimeCommand.java @@ -0,0 +1,88 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class TimeCommand extends VanillaCommand { + private static final List TABCOMPLETE_ADD_SET = ImmutableList.of("add", "set"); + private static final List TABCOMPLETE_DAY_NIGHT = ImmutableList.of("day", "night"); + + public TimeCommand() { + super("time"); + this.description = "Changes the time on each world"; + this.usageMessage = "/time set \n/time add "; + this.setPermission("bukkit.command.time.add;bukkit.command.time.set"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Incorrect usage. Correct usage:\n" + usageMessage); + return false; + } + + int value; + + if (args[0].equals("set")) { + if (!sender.hasPermission("bukkit.command.time.set")) { + sender.sendMessage(ChatColor.RED + "You don't have permission to set the time"); + return true; + } + + if (args[1].equals("day")) { + value = 0; + } else if (args[1].equals("night")) { + value = 12500; + } else { + value = getInteger(sender, args[1], 0); + } + + for (World world : Bukkit.getWorlds()) { + world.setTime(value); + } + + Command.broadcastCommandMessage(sender, "Set time to " + value); + } else if (args[0].equals("add")) { + if (!sender.hasPermission("bukkit.command.time.add")) { + sender.sendMessage(ChatColor.RED + "You don't have permission to set the time"); + return true; + } + + value = getInteger(sender, args[1], 0); + + for (World world : Bukkit.getWorlds()) { + world.setFullTime(world.getFullTime() + value); + } + + Command.broadcastCommandMessage(sender, "Added " + value + " to time"); + } else { + sender.sendMessage("Unknown method. Usage: " + usageMessage); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], TABCOMPLETE_ADD_SET, new ArrayList(TABCOMPLETE_ADD_SET.size())); + } else if (args.length == 2 && args[0].equalsIgnoreCase("set")) { + return StringUtil.copyPartialMatches(args[1], TABCOMPLETE_DAY_NIGHT, new ArrayList(TABCOMPLETE_DAY_NIGHT.size())); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/TimingsCommand.java b/src/main/java/org/bukkit/command/defaults/TimingsCommand.java new file mode 100644 index 0000000..05cfcb0 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/TimingsCommand.java @@ -0,0 +1,121 @@ +package org.bukkit.command.defaults; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredListener; +import org.bukkit.plugin.TimedRegisteredListener; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class TimingsCommand extends BukkitCommand { + private static final List TIMINGS_SUBCOMMANDS = ImmutableList.of("merged", "reset", "separate"); + + public TimingsCommand(String name) { + super(name); + this.description = "Records timings for all plugin events"; + this.usageMessage = "/timings "; + this.setPermission("bukkit.command.timings"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + if (!sender.getServer().getPluginManager().useTimings()) { + sender.sendMessage("Please enable timings by setting \"settings.plugin-profiling\" to true in bukkit.yml"); + return true; + } + + boolean separate = "separate".equals(args[0]); + if ("reset".equals(args[0])) { + for (HandlerList handlerList : HandlerList.getHandlerLists()) { + for (RegisteredListener listener : handlerList.getRegisteredListeners()) { + if (listener instanceof TimedRegisteredListener) { + ((TimedRegisteredListener)listener).reset(); + } + } + } + sender.sendMessage("Timings reset"); + } else if ("merged".equals(args[0]) || separate) { + + int index = 0; + int pluginIdx = 0; + File timingFolder = new File("timings"); + timingFolder.mkdirs(); + File timings = new File(timingFolder, "timings.txt"); + File names = null; + while (timings.exists()) timings = new File(timingFolder, "timings" + (++index) + ".txt"); + PrintStream fileTimings = null; + PrintStream fileNames = null; + try { + fileTimings = new PrintStream(timings); + if (separate) { + names = new File(timingFolder, "names" + index + ".txt"); + fileNames = new PrintStream(names); + } + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + pluginIdx++; + long totalTime = 0; + if (separate) { + fileNames.println(pluginIdx + " " + plugin.getDescription().getFullName()); + fileTimings.println("Plugin " + pluginIdx); + } + else fileTimings.println(plugin.getDescription().getFullName()); + for (RegisteredListener listener : HandlerList.getRegisteredListeners(plugin)) { + if (listener instanceof TimedRegisteredListener) { + TimedRegisteredListener trl = (TimedRegisteredListener) listener; + long time = trl.getTotalTime(); + int count = trl.getCount(); + if (count == 0) continue; + long avg = time / count; + totalTime += time; + Class eventClass = trl.getEventClass(); + if (count > 0 && eventClass != null) { + fileTimings.println(" " + eventClass.getSimpleName() + (trl.hasMultiple() ? " (and sub-classes)" : "") + " Time: " + time + " Count: " + count + " Avg: " + avg); + } + } + } + fileTimings.println(" Total time " + totalTime + " (" + totalTime / 1000000000 + "s)"); + } + sender.sendMessage("Timings written to " + timings.getPath()); + if (separate) sender.sendMessage("Names written to " + names.getPath()); + } catch (IOException e) { + } finally { + if (fileTimings != null) { + fileTimings.close(); + } + if (fileNames != null) { + fileNames.close(); + } + } + } + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], TIMINGS_SUBCOMMANDS, new ArrayList(TIMINGS_SUBCOMMANDS.size())); + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/ToggleDownfallCommand.java b/src/main/java/org/bukkit/command/defaults/ToggleDownfallCommand.java new file mode 100644 index 0000000..ac78bfb --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/ToggleDownfallCommand.java @@ -0,0 +1,56 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.google.common.collect.ImmutableList; + +public class ToggleDownfallCommand extends VanillaCommand { + public ToggleDownfallCommand() { + super("toggledownfall"); + this.description = "Toggles rain on/off on a given world"; + this.usageMessage = "/toggledownfall"; + this.setPermission("bukkit.command.toggledownfall"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + World world = null; + + if (args.length == 1) { + world = Bukkit.getWorld(args[0]); + + if (world == null) { + sender.sendMessage(ChatColor.RED + "No world exists with the name '" + args[0] + "'"); + return true; + } + } else if (sender instanceof Player) { + world = ((Player) sender).getWorld(); + } else { + world = Bukkit.getWorlds().get(0); + } + + Command.broadcastCommandMessage(sender, "Toggling downfall " + (world.hasStorm() ? "off" : "on") + " for world '" + world.getName() + "'"); + world.setStorm(!world.hasStorm()); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/VanillaCommand.java b/src/main/java/org/bukkit/command/defaults/VanillaCommand.java new file mode 100644 index 0000000..9b13ac6 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/VanillaCommand.java @@ -0,0 +1,110 @@ +package org.bukkit.command.defaults; + +import java.util.List; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public abstract class VanillaCommand extends Command { + static final int MAX_COORD = 30000000; + static final int MIN_COORD_MINUS_ONE = -30000001; + static final int MIN_COORD = -30000000; + + protected VanillaCommand(String name) { + super(name); + } + + protected VanillaCommand(String name, String description, String usageMessage, List aliases) { + super(name, description, usageMessage, aliases); + } + + public boolean matches(String input) { + return input.equalsIgnoreCase(this.getName()); + } + + protected int getInteger(CommandSender sender, String value, int min) { + return getInteger(sender, value, min, Integer.MAX_VALUE); + } + + int getInteger(CommandSender sender, String value, int min, int max) { + return getInteger(sender, value, min, max, false); + } + + int getInteger(CommandSender sender, String value, int min, int max, boolean Throws) { + int i = min; + + try { + i = Integer.valueOf(value); + } catch (NumberFormatException ex) { + if (Throws) { + throw new NumberFormatException(String.format("%s is not a valid number", value)); + } + } + + if (i < min) { + i = min; + } else if (i > max) { + i = max; + } + + return i; + } + + Integer getInteger(String value) { + try { + return Integer.valueOf(value); + } catch (NumberFormatException ex) { + return null; + } + } + + public static double getRelativeDouble(double original, CommandSender sender, String input) { + if (input.startsWith("~")) { + double value = getDouble(sender, input.substring(1)); + if (value == MIN_COORD_MINUS_ONE) { + return MIN_COORD_MINUS_ONE; + } + return original + value; + } else { + return getDouble(sender, input); + } + } + + public static double getDouble(CommandSender sender, String input) { + try { + return Double.parseDouble(input); + } catch (NumberFormatException ex) { + return MIN_COORD_MINUS_ONE; + } + } + + public static double getDouble(CommandSender sender, String input, double min, double max) { + double result = getDouble(sender, input); + + // TODO: This should throw an exception instead. + if (result < min) { + result = min; + } else if (result > max) { + result = max; + } + + return result; + } + + String createString(String[] args, int start) { + return createString(args, start, " "); + } + + String createString(String[] args, int start, String glue) { + StringBuilder string = new StringBuilder(); + + for (int x = start; x < args.length; x++) { + string.append(args[x]); + if (x != args.length - 1) { + string.append(glue); + } + } + + return string.toString(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/VersionCommand.java b/src/main/java/org/bukkit/command/defaults/VersionCommand.java new file mode 100644 index 0000000..902f9d1 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/VersionCommand.java @@ -0,0 +1,129 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class VersionCommand extends BukkitCommand { + public VersionCommand(String name) { + super(name); + + this.description = "Gets the version of this server including any plugins in use"; + this.usageMessage = "/version [plugin name]"; + this.setPermission("bukkit.command.version"); + this.setAliases(Arrays.asList("ver", "about")); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length == 0) { + sender.sendMessage("This server is running " + Bukkit.getName() + " version " + Bukkit.getVersion() + " (Implementing API version " + Bukkit.getBukkitVersion() + ")"); + } else { + StringBuilder name = new StringBuilder(); + + for (String arg : args) { + if (name.length() > 0) { + name.append(' '); + } + + name.append(arg); + } + + String pluginName = name.toString(); + Plugin exactPlugin = Bukkit.getPluginManager().getPlugin(pluginName); + if (exactPlugin != null) { + describeToSender(exactPlugin, sender); + return true; + } + + boolean found = false; + pluginName = pluginName.toLowerCase(); + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + if (plugin.getName().toLowerCase().contains(pluginName)) { + describeToSender(plugin, sender); + found = true; + } + } + + if (!found) { + sender.sendMessage("This server is not running any plugin by that name."); + sender.sendMessage("Use /plugins to get a list of plugins."); + } + } + return true; + } + + private void describeToSender(Plugin plugin, CommandSender sender) { + PluginDescriptionFile desc = plugin.getDescription(); + sender.sendMessage(ChatColor.GREEN + desc.getName() + ChatColor.WHITE + " version " + ChatColor.GREEN + desc.getVersion()); + + if (desc.getDescription() != null) { + sender.sendMessage(desc.getDescription()); + } + + if (desc.getWebsite() != null) { + sender.sendMessage("Website: " + ChatColor.GREEN + desc.getWebsite()); + } + + if (!desc.getAuthors().isEmpty()) { + if (desc.getAuthors().size() == 1) { + sender.sendMessage("Author: " + getAuthors(desc)); + } else { + sender.sendMessage("Authors: " + getAuthors(desc)); + } + } + } + + private String getAuthors(final PluginDescriptionFile desc) { + StringBuilder result = new StringBuilder(); + List authors = desc.getAuthors(); + + for (int i = 0; i < authors.size(); i++) { + if (result.length() > 0) { + result.append(ChatColor.WHITE); + + if (i < authors.size() - 1) { + result.append(", "); + } else { + result.append(" and "); + } + } + + result.append(ChatColor.GREEN); + result.append(authors.get(i)); + } + + return result.toString(); + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + List completions = new ArrayList(); + String toComplete = args[0].toLowerCase(); + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + if (StringUtil.startsWithIgnoreCase(plugin.getName(), toComplete)) { + completions.add(plugin.getName()); + } + } + return completions; + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/WeatherCommand.java b/src/main/java/org/bukkit/command/defaults/WeatherCommand.java new file mode 100644 index 0000000..a39c1b0 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/WeatherCommand.java @@ -0,0 +1,73 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class WeatherCommand extends VanillaCommand { + private static final List WEATHER_TYPES = ImmutableList.of("clear", "rain", "thunder"); + + public WeatherCommand() { + super("weather"); + this.description = "Changes the weather"; + this.usageMessage = "/weather [duration in seconds]"; + this.setPermission("bukkit.command.weather"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + int duration = (300 + new Random().nextInt(600)) * 20; + if (args.length >= 2) { + duration = getInteger(sender, args[1], 1, 1000000) * 20; + } + + World world = Bukkit.getWorlds().get(0); + + world.setWeatherDuration(duration); + world.setThunderDuration(duration); + + if ("clear".equalsIgnoreCase(args[0])) { + world.setStorm(false); + world.setThundering(false); + Command.broadcastCommandMessage(sender, "Changed weather to clear for " + (duration / 20) + " seconds."); + } else if ("rain".equalsIgnoreCase(args[0])) { + world.setStorm(true); + world.setThundering(false); + Command.broadcastCommandMessage(sender, "Changed weather to rainy for " + (duration / 20) + " seconds."); + } else if ("thunder".equalsIgnoreCase(args[0])) { + world.setStorm(true); + world.setThundering(true); + Command.broadcastCommandMessage(sender, "Changed weather to thundering " + (duration / 20) + " seconds."); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], WEATHER_TYPES, new ArrayList(WEATHER_TYPES.size())); + } + + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/command/defaults/WhitelistCommand.java b/src/main/java/org/bukkit/command/defaults/WhitelistCommand.java new file mode 100644 index 0000000..b3fa4f8 --- /dev/null +++ b/src/main/java/org/bukkit/command/defaults/WhitelistCommand.java @@ -0,0 +1,127 @@ +package org.bukkit.command.defaults; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import com.google.common.collect.ImmutableList; + +public class WhitelistCommand extends VanillaCommand { + private static final List WHITELIST_SUBCOMMANDS = ImmutableList.of("add", "remove", "on", "off", "list", "reload"); + + public WhitelistCommand() { + super("whitelist"); + this.description = "Manages the list of players allowed to use this server"; + this.usageMessage = "/whitelist (add|remove) \n/whitelist (on|off|list|reload)"; + this.setPermission("bukkit.command.whitelist.reload;bukkit.command.whitelist.enable;bukkit.command.whitelist.disable;bukkit.command.whitelist.list;bukkit.command.whitelist.add;bukkit.command.whitelist.remove"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length == 1) { + if (args[0].equalsIgnoreCase("reload")) { + if (badPerm(sender, "reload")) return true; + + Bukkit.reloadWhitelist(); + Command.broadcastCommandMessage(sender, "Reloaded white-list from file"); + return true; + } else if (args[0].equalsIgnoreCase("on")) { + if (badPerm(sender, "enable")) return true; + + Bukkit.setWhitelist(true); + Command.broadcastCommandMessage(sender, "Turned on white-listing"); + return true; + } else if (args[0].equalsIgnoreCase("off")) { + if (badPerm(sender, "disable")) return true; + + Bukkit.setWhitelist(false); + Command.broadcastCommandMessage(sender, "Turned off white-listing"); + return true; + } else if (args[0].equalsIgnoreCase("list")) { + if (badPerm(sender, "list")) return true; + + StringBuilder result = new StringBuilder(); + + for (OfflinePlayer player : Bukkit.getWhitelistedPlayers()) { + if (result.length() > 0) { + result.append(", "); + } + + result.append(player.getName()); + } + + sender.sendMessage("White-listed players: " + result.toString()); + return true; + } + } else if (args.length == 2) { + if (args[0].equalsIgnoreCase("add")) { + if (badPerm(sender, "add")) return true; + + Bukkit.getOfflinePlayer(args[1]).setWhitelisted(true); + + Command.broadcastCommandMessage(sender, "Added " + args[1] + " to white-list"); + return true; + } else if (args[0].equalsIgnoreCase("remove")) { + if (badPerm(sender, "remove")) return true; + + Bukkit.getOfflinePlayer(args[1]).setWhitelisted(false); + + Command.broadcastCommandMessage(sender, "Removed " + args[1] + " from white-list"); + return true; + } + } + + sender.sendMessage(ChatColor.RED + "Correct command usage:\n" + usageMessage); + return false; + } + + private boolean badPerm(CommandSender sender, String perm) { + if (!sender.hasPermission("bukkit.command.whitelist." + perm)) { + sender.sendMessage(ChatColor.RED + "You do not have permission to perform this action."); + return true; + } + + return false; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], WHITELIST_SUBCOMMANDS, new ArrayList(WHITELIST_SUBCOMMANDS.size())); + } else if (args.length == 2) { + if (args[0].equalsIgnoreCase("add")) { + List completions = new ArrayList(); + for (OfflinePlayer player : Bukkit.getOfflinePlayers()) { + String name = player.getName(); + if (StringUtil.startsWithIgnoreCase(name, args[1]) && !player.isWhitelisted()) { + completions.add(name); + } + } + return completions; + } else if (args[0].equalsIgnoreCase("remove")) { + List completions = new ArrayList(); + for (OfflinePlayer player : Bukkit.getWhitelistedPlayers()) { + String name = player.getName(); + if (StringUtil.startsWithIgnoreCase(name, args[1])) { + completions.add(name); + } + } + return completions; + } + } + return ImmutableList.of(); + } +} diff --git a/src/main/java/org/bukkit/configuration/Configuration.java b/src/main/java/org/bukkit/configuration/Configuration.java new file mode 100644 index 0000000..9289c21 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/Configuration.java @@ -0,0 +1,84 @@ +package org.bukkit.configuration; + +import java.util.Map; + +/** + * Represents a source of configurable options and settings + */ +public interface Configuration extends ConfigurationSection { + /** + * Sets the default value of the given path as provided. + *

          + * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

          + * If value is null, the value will be removed from the default + * Configuration source. + * + * @param path Path of the value to set. + * @param value Value to set the default to. + * @throws IllegalArgumentException Thrown if path is null. + */ + public void addDefault(String path, Object value); + + /** + * Sets the default values of the given paths as provided. + *

          + * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default values. + * + * @param defaults A map of Path->Values to add to defaults. + * @throws IllegalArgumentException Thrown if defaults is null. + */ + public void addDefaults(Map defaults); + + /** + * Sets the default values of the given paths as provided. + *

          + * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

          + * This method will not hold a reference to the specified Configuration, + * nor will it automatically update if that Configuration ever changes. If + * you require this, you should set the default source with {@link + * #setDefaults(org.bukkit.configuration.Configuration)}. + * + * @param defaults A configuration holding a list of defaults to copy. + * @throws IllegalArgumentException Thrown if defaults is null or this. + */ + public void addDefaults(Configuration defaults); + + /** + * Sets the source of all default values for this {@link Configuration}. + *

          + * If a previous source was set, or previous default values were defined, + * then they will not be copied to the new source. + * + * @param defaults New source of default values for this configuration. + * @throws IllegalArgumentException Thrown if defaults is null or this. + */ + public void setDefaults(Configuration defaults); + + /** + * Gets the source {@link Configuration} for this configuration. + *

          + * If no configuration source was set, but default values were added, then + * a {@link MemoryConfiguration} will be returned. If no source was set + * and no defaults were set, then this method will return null. + * + * @return Configuration source for default values, or null if none exist. + */ + public Configuration getDefaults(); + + /** + * Gets the {@link ConfigurationOptions} for this {@link Configuration}. + *

          + * All setters through this method are chainable. + * + * @return Options for this configuration + */ + public ConfigurationOptions options(); +} diff --git a/src/main/java/org/bukkit/configuration/ConfigurationOptions.java b/src/main/java/org/bukkit/configuration/ConfigurationOptions.java new file mode 100644 index 0000000..2f59382 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/ConfigurationOptions.java @@ -0,0 +1,90 @@ +package org.bukkit.configuration; + +/** + * Various settings for controlling the input and output of a {@link + * Configuration} + */ +public class ConfigurationOptions { + private char pathSeparator = '.'; + private boolean copyDefaults = false; + private final Configuration configuration; + + protected ConfigurationOptions(Configuration configuration) { + this.configuration = configuration; + } + + /** + * Returns the {@link Configuration} that this object is responsible for. + * + * @return Parent configuration + */ + public Configuration configuration() { + return configuration; + } + + /** + * Gets the char that will be used to separate {@link + * ConfigurationSection}s + *

          + * This value does not affect how the {@link Configuration} is stored, + * only in how you access the data. The default value is '.'. + * + * @return Path separator + */ + public char pathSeparator() { + return pathSeparator; + } + + /** + * Sets the char that will be used to separate {@link + * ConfigurationSection}s + *

          + * This value does not affect how the {@link Configuration} is stored, + * only in how you access the data. The default value is '.'. + * + * @param value Path separator + * @return This object, for chaining + */ + public ConfigurationOptions pathSeparator(char value) { + this.pathSeparator = value; + return this; + } + + /** + * Checks if the {@link Configuration} should copy values from its default + * {@link Configuration} directly. + *

          + * If this is true, all values in the default Configuration will be + * directly copied, making it impossible to distinguish between values + * that were set and values that are provided by default. As a result, + * {@link ConfigurationSection#contains(java.lang.String)} will always + * return the same value as {@link + * ConfigurationSection#isSet(java.lang.String)}. The default value is + * false. + * + * @return Whether or not defaults are directly copied + */ + public boolean copyDefaults() { + return copyDefaults; + } + + /** + * Sets if the {@link Configuration} should copy values from its default + * {@link Configuration} directly. + *

          + * If this is true, all values in the default Configuration will be + * directly copied, making it impossible to distinguish between values + * that were set and values that are provided by default. As a result, + * {@link ConfigurationSection#contains(java.lang.String)} will always + * return the same value as {@link + * ConfigurationSection#isSet(java.lang.String)}. The default value is + * false. + * + * @param value Whether or not defaults are directly copied + * @return This object, for chaining + */ + public ConfigurationOptions copyDefaults(boolean value) { + this.copyDefaults = value; + return this; + } +} diff --git a/src/main/java/org/bukkit/configuration/ConfigurationSection.java b/src/main/java/org/bukkit/configuration/ConfigurationSection.java new file mode 100644 index 0000000..1bd7fb5 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/ConfigurationSection.java @@ -0,0 +1,809 @@ +package org.bukkit.configuration; + +import java.util.Map; +import java.util.Set; +import java.util.List; + +import org.bukkit.Color; +import org.bukkit.OfflinePlayer; +import org.bukkit.util.Vector; +import org.bukkit.inventory.ItemStack; + +/** + * Represents a section of a {@link Configuration} + */ +public interface ConfigurationSection { + /** + * Gets a set containing all keys in this section. + *

          + * If deep is set to true, then this will contain all the keys within any + * child {@link ConfigurationSection}s (and their children, etc). These + * will be in a valid path notation for you to use. + *

          + * If deep is set to false, then this will contain only the keys of any + * direct children, and not their own children. + * + * @param deep Whether or not to get a deep list, as opposed to a shallow + * list. + * @return Set of keys contained within this ConfigurationSection. + */ + public Set getKeys(boolean deep); + + /** + * Gets a Map containing all keys and their values for this section. + *

          + * If deep is set to true, then this will contain all the keys and values + * within any child {@link ConfigurationSection}s (and their children, + * etc). These keys will be in a valid path notation for you to use. + *

          + * If deep is set to false, then this will contain only the keys and + * values of any direct children, and not their own children. + * + * @param deep Whether or not to get a deep list, as opposed to a shallow + * list. + * @return Map of keys and values of this section. + */ + public Map getValues(boolean deep); + + /** + * Checks if this {@link ConfigurationSection} contains the given path. + *

          + * If the value for the requested path does not exist but a default value + * has been specified, this will return true. + * + * @param path Path to check for existence. + * @return True if this section contains the requested path, either via + * default or being set. + * @throws IllegalArgumentException Thrown when path is null. + */ + public boolean contains(String path); + + /** + * Checks if this {@link ConfigurationSection} has a value set for the + * given path. + *

          + * If the value for the requested path does not exist but a default value + * has been specified, this will still return false. + * + * @param path Path to check for existence. + * @return True if this section contains the requested path, regardless of + * having a default. + * @throws IllegalArgumentException Thrown when path is null. + */ + public boolean isSet(String path); + + /** + * Gets the path of this {@link ConfigurationSection} from its root {@link + * Configuration} + *

          + * For any {@link Configuration} themselves, this will return an empty + * string. + *

          + * If the section is no longer contained within its root for any reason, + * such as being replaced with a different value, this may return null. + *

          + * To retrieve the single name of this section, that is, the final part of + * the path returned by this method, you may use {@link #getName()}. + * + * @return Path of this section relative to its root + */ + public String getCurrentPath(); + + /** + * Gets the name of this individual {@link ConfigurationSection}, in the + * path. + *

          + * This will always be the final part of {@link #getCurrentPath()}, unless + * the section is orphaned. + * + * @return Name of this section + */ + public String getName(); + + /** + * Gets the root {@link Configuration} that contains this {@link + * ConfigurationSection} + *

          + * For any {@link Configuration} themselves, this will return its own + * object. + *

          + * If the section is no longer contained within its root for any reason, + * such as being replaced with a different value, this may return null. + * + * @return Root configuration containing this section. + */ + public Configuration getRoot(); + + /** + * Gets the parent {@link ConfigurationSection} that directly contains + * this {@link ConfigurationSection}. + *

          + * For any {@link Configuration} themselves, this will return null. + *

          + * If the section is no longer contained within its parent for any reason, + * such as being replaced with a different value, this may return null. + * + * @return Parent section containing this section. + */ + public ConfigurationSection getParent(); + + /** + * Gets the requested Object by path. + *

          + * If the Object does not exist but a default value has been specified, + * this will return the default value. If the Object does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the Object to get. + * @return Requested Object. + */ + public Object get(String path); + + /** + * Gets the requested Object by path, returning a default value if not + * found. + *

          + * If the Object does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the Object to get. + * @param def The default value to return if the path is not found. + * @return Requested Object. + */ + public Object get(String path, Object def); + + /** + * Sets the specified path to the given value. + *

          + * If value is null, the entry will be removed. Any existing entry will be + * replaced, regardless of what the new value is. + *

          + * Some implementations may have limitations on what you may store. See + * their individual javadocs for details. No implementations should allow + * you to store {@link Configuration}s or {@link ConfigurationSection}s, + * please use {@link #createSection(java.lang.String)} for that. + * + * @param path Path of the object to set. + * @param value New value to set the path to. + */ + public void set(String path, Object value); + + /** + * Creates an empty {@link ConfigurationSection} at the specified path. + *

          + * Any value that was previously set at this path will be overwritten. If + * the previous value was itself a {@link ConfigurationSection}, it will + * be orphaned. + * + * @param path Path to create the section at. + * @return Newly created section + */ + public ConfigurationSection createSection(String path); + + /** + * Creates a {@link ConfigurationSection} at the specified path, with + * specified values. + *

          + * Any value that was previously set at this path will be overwritten. If + * the previous value was itself a {@link ConfigurationSection}, it will + * be orphaned. + * + * @param path Path to create the section at. + * @param map The values to used. + * @return Newly created section + */ + public ConfigurationSection createSection(String path, Map map); + + // Primitives + /** + * Gets the requested String by path. + *

          + * If the String does not exist but a default value has been specified, + * this will return the default value. If the String does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the String to get. + * @return Requested String. + */ + public String getString(String path); + + /** + * Gets the requested String by path, returning a default value if not + * found. + *

          + * If the String does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the String to get. + * @param def The default value to return if the path is not found or is + * not a String. + * @return Requested String. + */ + public String getString(String path, String def); + + /** + * Checks if the specified path is a String. + *

          + * If the path exists but is not a String, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a String and return appropriately. + * + * @param path Path of the String to check. + * @return Whether or not the specified path is a String. + */ + public boolean isString(String path); + + /** + * Gets the requested int by path. + *

          + * If the int does not exist but a default value has been specified, this + * will return the default value. If the int does not exist and no default + * value was specified, this will return 0. + * + * @param path Path of the int to get. + * @return Requested int. + */ + public int getInt(String path); + + /** + * Gets the requested int by path, returning a default value if not found. + *

          + * If the int does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the int to get. + * @param def The default value to return if the path is not found or is + * not an int. + * @return Requested int. + */ + public int getInt(String path, int def); + + /** + * Checks if the specified path is an int. + *

          + * If the path exists but is not a int, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a int and return appropriately. + * + * @param path Path of the int to check. + * @return Whether or not the specified path is an int. + */ + public boolean isInt(String path); + + /** + * Gets the requested boolean by path. + *

          + * If the boolean does not exist but a default value has been specified, + * this will return the default value. If the boolean does not exist and + * no default value was specified, this will return false. + * + * @param path Path of the boolean to get. + * @return Requested boolean. + */ + public boolean getBoolean(String path); + + /** + * Gets the requested boolean by path, returning a default value if not + * found. + *

          + * If the boolean does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the boolean to get. + * @param def The default value to return if the path is not found or is + * not a boolean. + * @return Requested boolean. + */ + public boolean getBoolean(String path, boolean def); + + /** + * Checks if the specified path is a boolean. + *

          + * If the path exists but is not a boolean, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a boolean and return appropriately. + * + * @param path Path of the boolean to check. + * @return Whether or not the specified path is a boolean. + */ + public boolean isBoolean(String path); + + /** + * Gets the requested double by path. + *

          + * If the double does not exist but a default value has been specified, + * this will return the default value. If the double does not exist and no + * default value was specified, this will return 0. + * + * @param path Path of the double to get. + * @return Requested double. + */ + public double getDouble(String path); + + /** + * Gets the requested double by path, returning a default value if not + * found. + *

          + * If the double does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the double to get. + * @param def The default value to return if the path is not found or is + * not a double. + * @return Requested double. + */ + public double getDouble(String path, double def); + + /** + * Checks if the specified path is a double. + *

          + * If the path exists but is not a double, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a double and return appropriately. + * + * @param path Path of the double to check. + * @return Whether or not the specified path is a double. + */ + public boolean isDouble(String path); + + /** + * Gets the requested long by path. + *

          + * If the long does not exist but a default value has been specified, this + * will return the default value. If the long does not exist and no + * default value was specified, this will return 0. + * + * @param path Path of the long to get. + * @return Requested long. + */ + public long getLong(String path); + + /** + * Gets the requested long by path, returning a default value if not + * found. + *

          + * If the long does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the long to get. + * @param def The default value to return if the path is not found or is + * not a long. + * @return Requested long. + */ + public long getLong(String path, long def); + + /** + * Checks if the specified path is a long. + *

          + * If the path exists but is not a long, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a long and return appropriately. + * + * @param path Path of the long to check. + * @return Whether or not the specified path is a long. + */ + public boolean isLong(String path); + + // Java + /** + * Gets the requested List by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the List to get. + * @return Requested List. + */ + public List getList(String path); + + /** + * Gets the requested List by path, returning a default value if not + * found. + *

          + * If the List does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the List to get. + * @param def The default value to return if the path is not found or is + * not a List. + * @return Requested List. + */ + public List getList(String path, List def); + + /** + * Checks if the specified path is a List. + *

          + * If the path exists but is not a List, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a List and return appropriately. + * + * @param path Path of the List to check. + * @return Whether or not the specified path is a List. + */ + public boolean isList(String path); + + /** + * Gets the requested List of String by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a String if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of String. + */ + public List getStringList(String path); + + /** + * Gets the requested List of Integer by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Integer if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Integer. + */ + public List getIntegerList(String path); + + /** + * Gets the requested List of Boolean by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Boolean if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Boolean. + */ + public List getBooleanList(String path); + + /** + * Gets the requested List of Double by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Double if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Double. + */ + public List getDoubleList(String path); + + /** + * Gets the requested List of Float by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Float if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Float. + */ + public List getFloatList(String path); + + /** + * Gets the requested List of Long by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Long if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Long. + */ + public List getLongList(String path); + + /** + * Gets the requested List of Byte by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Byte if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Byte. + */ + public List getByteList(String path); + + /** + * Gets the requested List of Character by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Character if + * possible, but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Character. + */ + public List getCharacterList(String path); + + /** + * Gets the requested List of Short by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Short if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Short. + */ + public List getShortList(String path); + + /** + * Gets the requested List of Maps by path. + *

          + * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

          + * This method will attempt to cast any values into a Map if possible, but + * may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Maps. + */ + public List> getMapList(String path); + + // Bukkit + /** + * Gets the requested Vector by path. + *

          + * If the Vector does not exist but a default value has been specified, + * this will return the default value. If the Vector does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the Vector to get. + * @return Requested Vector. + */ + public Vector getVector(String path); + + /** + * Gets the requested {@link Vector} by path, returning a default value if + * not found. + *

          + * If the Vector does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the Vector to get. + * @param def The default value to return if the path is not found or is + * not a Vector. + * @return Requested Vector. + */ + public Vector getVector(String path, Vector def); + + /** + * Checks if the specified path is a Vector. + *

          + * If the path exists but is not a Vector, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a Vector and return appropriately. + * + * @param path Path of the Vector to check. + * @return Whether or not the specified path is a Vector. + */ + public boolean isVector(String path); + + /** + * Gets the requested OfflinePlayer by path. + *

          + * If the OfflinePlayer does not exist but a default value has been + * specified, this will return the default value. If the OfflinePlayer + * does not exist and no default value was specified, this will return + * null. + * + * @param path Path of the OfflinePlayer to get. + * @return Requested OfflinePlayer. + */ + public OfflinePlayer getOfflinePlayer(String path); + + /** + * Gets the requested {@link OfflinePlayer} by path, returning a default + * value if not found. + *

          + * If the OfflinePlayer does not exist then the specified default value + * will returned regardless of if a default has been identified in the + * root {@link Configuration}. + * + * @param path Path of the OfflinePlayer to get. + * @param def The default value to return if the path is not found or is + * not an OfflinePlayer. + * @return Requested OfflinePlayer. + */ + public OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def); + + /** + * Checks if the specified path is an OfflinePlayer. + *

          + * If the path exists but is not a OfflinePlayer, this will return false. + * If the path does not exist, this will return false. If the path does + * not exist but a default value has been specified, this will check if + * that default value is a OfflinePlayer and return appropriately. + * + * @param path Path of the OfflinePlayer to check. + * @return Whether or not the specified path is an OfflinePlayer. + */ + public boolean isOfflinePlayer(String path); + + /** + * Gets the requested ItemStack by path. + *

          + * If the ItemStack does not exist but a default value has been specified, + * this will return the default value. If the ItemStack does not exist and + * no default value was specified, this will return null. + * + * @param path Path of the ItemStack to get. + * @return Requested ItemStack. + */ + public ItemStack getItemStack(String path); + + /** + * Gets the requested {@link ItemStack} by path, returning a default value + * if not found. + *

          + * If the ItemStack does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the ItemStack to get. + * @param def The default value to return if the path is not found or is + * not an ItemStack. + * @return Requested ItemStack. + */ + public ItemStack getItemStack(String path, ItemStack def); + + /** + * Checks if the specified path is an ItemStack. + *

          + * If the path exists but is not a ItemStack, this will return false. If + * the path does not exist, this will return false. If the path does not + * exist but a default value has been specified, this will check if that + * default value is a ItemStack and return appropriately. + * + * @param path Path of the ItemStack to check. + * @return Whether or not the specified path is an ItemStack. + */ + public boolean isItemStack(String path); + + /** + * Gets the requested Color by path. + *

          + * If the Color does not exist but a default value has been specified, + * this will return the default value. If the Color does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the Color to get. + * @return Requested Color. + */ + public Color getColor(String path); + + /** + * Gets the requested {@link Color} by path, returning a default value if + * not found. + *

          + * If the Color does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the Color to get. + * @param def The default value to return if the path is not found or is + * not a Color. + * @return Requested Color. + */ + public Color getColor(String path, Color def); + + /** + * Checks if the specified path is a Color. + *

          + * If the path exists but is not a Color, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a Color and return appropriately. + * + * @param path Path of the Color to check. + * @return Whether or not the specified path is a Color. + */ + public boolean isColor(String path); + + /** + * Gets the requested ConfigurationSection by path. + *

          + * If the ConfigurationSection does not exist but a default value has been + * specified, this will return the default value. If the + * ConfigurationSection does not exist and no default value was specified, + * this will return null. + * + * @param path Path of the ConfigurationSection to get. + * @return Requested ConfigurationSection. + */ + public ConfigurationSection getConfigurationSection(String path); + + /** + * Checks if the specified path is a ConfigurationSection. + *

          + * If the path exists but is not a ConfigurationSection, this will return + * false. If the path does not exist, this will return false. If the path + * does not exist but a default value has been specified, this will check + * if that default value is a ConfigurationSection and return + * appropriately. + * + * @param path Path of the ConfigurationSection to check. + * @return Whether or not the specified path is a ConfigurationSection. + */ + public boolean isConfigurationSection(String path); + + /** + * Gets the equivalent {@link ConfigurationSection} from the default + * {@link Configuration} defined in {@link #getRoot()}. + *

          + * If the root contains no defaults, or the defaults doesn't contain a + * value for this path, or the value at this path is not a {@link + * ConfigurationSection} then this will return null. + * + * @return Equivalent section in root configuration + */ + public ConfigurationSection getDefaultSection(); + + /** + * Sets the default value in the root at the given path as provided. + *

          + * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

          + * If value is null, the value will be removed from the default + * Configuration source. + *

          + * If the value as returned by {@link #getDefaultSection()} is null, then + * this will create a new section at the path, replacing anything that may + * have existed there previously. + * + * @param path Path of the value to set. + * @param value Value to set the default to. + * @throws IllegalArgumentException Thrown if path is null. + */ + public void addDefault(String path, Object value); +} diff --git a/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java b/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java new file mode 100644 index 0000000..d23480e --- /dev/null +++ b/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java @@ -0,0 +1,45 @@ +package org.bukkit.configuration; + +/** + * Exception thrown when attempting to load an invalid {@link Configuration} + */ +@SuppressWarnings("serial") +public class InvalidConfigurationException extends Exception { + + /** + * Creates a new instance of InvalidConfigurationException without a + * message or cause. + */ + public InvalidConfigurationException() {} + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified message. + * + * @param msg The details of the exception. + */ + public InvalidConfigurationException(String msg) { + super(msg); + } + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified cause. + * + * @param cause The cause of the exception. + */ + public InvalidConfigurationException(Throwable cause) { + super(cause); + } + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified message and cause. + * + * @param cause The cause of the exception. + * @param msg The details of the exception. + */ + public InvalidConfigurationException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/src/main/java/org/bukkit/configuration/MemoryConfiguration.java b/src/main/java/org/bukkit/configuration/MemoryConfiguration.java new file mode 100644 index 0000000..19c27a1 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/MemoryConfiguration.java @@ -0,0 +1,79 @@ +package org.bukkit.configuration; + +import java.util.Map; + +import org.apache.commons.lang.Validate; + +/** + * This is a {@link Configuration} implementation that does not save or load + * from any source, and stores all values in memory only. + * This is useful for temporary Configurations for providing defaults. + */ +public class MemoryConfiguration extends MemorySection implements Configuration { + protected Configuration defaults; + protected MemoryConfigurationOptions options; + + /** + * Creates an empty {@link MemoryConfiguration} with no default values. + */ + public MemoryConfiguration() {} + + /** + * Creates an empty {@link MemoryConfiguration} using the specified {@link + * Configuration} as a source for all default values. + * + * @param defaults Default value provider + * @throws IllegalArgumentException Thrown if defaults is null + */ + public MemoryConfiguration(Configuration defaults) { + this.defaults = defaults; + } + + @Override + public void addDefault(String path, Object value) { + Validate.notNull(path, "Path may not be null"); + + if (defaults == null) { + defaults = new MemoryConfiguration(); + } + + defaults.set(path, value); + } + + public void addDefaults(Map defaults) { + Validate.notNull(defaults, "Defaults may not be null"); + + for (Map.Entry entry : defaults.entrySet()) { + addDefault(entry.getKey(), entry.getValue()); + } + } + + public void addDefaults(Configuration defaults) { + Validate.notNull(defaults, "Defaults may not be null"); + + addDefaults(defaults.getValues(true)); + } + + public void setDefaults(Configuration defaults) { + Validate.notNull(defaults, "Defaults may not be null"); + + this.defaults = defaults; + } + + public Configuration getDefaults() { + return defaults; + } + + @Override + public ConfigurationSection getParent() { + return null; + } + + public MemoryConfigurationOptions options() { + if (options == null) { + options = new MemoryConfigurationOptions(this); + } + + return options; + } +} diff --git a/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java b/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java new file mode 100644 index 0000000..44c046c --- /dev/null +++ b/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java @@ -0,0 +1,28 @@ +package org.bukkit.configuration; + +/** + * Various settings for controlling the input and output of a {@link + * MemoryConfiguration} + */ +public class MemoryConfigurationOptions extends ConfigurationOptions { + protected MemoryConfigurationOptions(MemoryConfiguration configuration) { + super(configuration); + } + + @Override + public MemoryConfiguration configuration() { + return (MemoryConfiguration) super.configuration(); + } + + @Override + public MemoryConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public MemoryConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } +} diff --git a/src/main/java/org/bukkit/configuration/MemorySection.java b/src/main/java/org/bukkit/configuration/MemorySection.java new file mode 100644 index 0000000..f180bf5 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/MemorySection.java @@ -0,0 +1,820 @@ +package org.bukkit.configuration; + +import static org.bukkit.util.NumberConversions.*; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.Validate; +import org.bukkit.Color; +import org.bukkit.OfflinePlayer; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +/** + * A type of {@link ConfigurationSection} that is stored in memory. + */ +public class MemorySection implements ConfigurationSection { + protected final Map map = new LinkedHashMap(); + private final Configuration root; + private final ConfigurationSection parent; + private final String path; + private final String fullPath; + + /** + * Creates an empty MemorySection for use as a root {@link Configuration} + * section. + *

          + * Note that calling this without being yourself a {@link Configuration} + * will throw an exception! + * + * @throws IllegalStateException Thrown if this is not a {@link + * Configuration} root. + */ + protected MemorySection() { + if (!(this instanceof Configuration)) { + throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); + } + + this.path = ""; + this.fullPath = ""; + this.parent = null; + this.root = (Configuration) this; + } + + /** + * Creates an empty MemorySection with the specified parent and path. + * + * @param parent Parent section that contains this own section. + * @param path Path that you may access this section from via the root + * {@link Configuration}. + * @throws IllegalArgumentException Thrown is parent or path is null, or + * if parent contains no root Configuration. + */ + protected MemorySection(ConfigurationSection parent, String path) { + Validate.notNull(parent, "Parent cannot be null"); + Validate.notNull(path, "Path cannot be null"); + + this.path = path; + this.parent = parent; + this.root = parent.getRoot(); + + Validate.notNull(root, "Path cannot be orphaned"); + + this.fullPath = createPath(parent, path); + } + + public Set getKeys(boolean deep) { + Set result = new LinkedHashSet(); + + Configuration root = getRoot(); + if (root != null && root.options().copyDefaults()) { + ConfigurationSection defaults = getDefaultSection(); + + if (defaults != null) { + result.addAll(defaults.getKeys(deep)); + } + } + + mapChildrenKeys(result, this, deep); + + return result; + } + + public Map getValues(boolean deep) { + Map result = new LinkedHashMap(); + + Configuration root = getRoot(); + if (root != null && root.options().copyDefaults()) { + ConfigurationSection defaults = getDefaultSection(); + + if (defaults != null) { + result.putAll(defaults.getValues(deep)); + } + } + + mapChildrenValues(result, this, deep); + + return result; + } + + public boolean contains(String path) { + return get(path) != null; + } + + public boolean isSet(String path) { + Configuration root = getRoot(); + if (root == null) { + return false; + } + if (root.options().copyDefaults()) { + return contains(path); + } + return get(path, null) != null; + } + + public String getCurrentPath() { + return fullPath; + } + + public String getName() { + return path; + } + + public Configuration getRoot() { + return root; + } + + public ConfigurationSection getParent() { + return parent; + } + + public void addDefault(String path, Object value) { + Validate.notNull(path, "Path cannot be null"); + + Configuration root = getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot add default without root"); + } + if (root == this) { + throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation"); + } + root.addDefault(createPath(this, path), value); + } + + public ConfigurationSection getDefaultSection() { + Configuration root = getRoot(); + Configuration defaults = root == null ? null : root.getDefaults(); + + if (defaults != null) { + if (defaults.isConfigurationSection(getCurrentPath())) { + return defaults.getConfigurationSection(getCurrentPath()); + } + } + + return null; + } + + public void set(String path, Object value) { + Validate.notEmpty(path, "Cannot set to an empty path"); + + Configuration root = getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot use section without a root"); + } + + final char separator = root.options().pathSeparator(); + // i1 is the leading (higher) index + // i2 is the trailing (lower) index + int i1 = -1, i2; + ConfigurationSection section = this; + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { + String node = path.substring(i2, i1); + ConfigurationSection subSection = section.getConfigurationSection(node); + if (subSection == null) { + section = section.createSection(node); + } else { + section = subSection; + } + } + + String key = path.substring(i2); + if (section == this) { + if (value == null) { + map.remove(key); + } else { + map.put(key, value); + } + } else { + section.set(key, value); + } + } + + public Object get(String path) { + return get(path, getDefault(path)); + } + + public Object get(String path, Object def) { + Validate.notNull(path, "Path cannot be null"); + + if (path.length() == 0) { + return this; + } + + Configuration root = getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot access section without a root"); + } + + final char separator = root.options().pathSeparator(); + // i1 is the leading (higher) index + // i2 is the trailing (lower) index + int i1 = -1, i2; + ConfigurationSection section = this; + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { + section = section.getConfigurationSection(path.substring(i2, i1)); + if (section == null) { + return def; + } + } + + String key = path.substring(i2); + if (section == this) { + Object result = map.get(key); + return (result == null) ? def : result; + } + return section.get(key, def); + } + + public ConfigurationSection createSection(String path) { + Validate.notEmpty(path, "Cannot create section at empty path"); + Configuration root = getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot create section without a root"); + } + + final char separator = root.options().pathSeparator(); + // i1 is the leading (higher) index + // i2 is the trailing (lower) index + int i1 = -1, i2; + ConfigurationSection section = this; + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { + String node = path.substring(i2, i1); + ConfigurationSection subSection = section.getConfigurationSection(node); + if (subSection == null) { + section = section.createSection(node); + } else { + section = subSection; + } + } + + String key = path.substring(i2); + if (section == this) { + ConfigurationSection result = new MemorySection(this, key); + map.put(key, result); + return result; + } + return section.createSection(key); + } + + public ConfigurationSection createSection(String path, Map map) { + ConfigurationSection section = createSection(path); + + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() instanceof Map) { + section.createSection(entry.getKey().toString(), (Map) entry.getValue()); + } else { + section.set(entry.getKey().toString(), entry.getValue()); + } + } + + return section; + } + + // Primitives + public String getString(String path) { + Object def = getDefault(path); + return getString(path, def != null ? def.toString() : null); + } + + public String getString(String path, String def) { + Object val = get(path, def); + return (val != null) ? val.toString() : def; + } + + public boolean isString(String path) { + Object val = get(path); + return val instanceof String; + } + + public int getInt(String path) { + Object def = getDefault(path); + return getInt(path, (def instanceof Number) ? toInt(def) : 0); + } + + public int getInt(String path, int def) { + Object val = get(path, def); + return (val instanceof Number) ? toInt(val) : def; + } + + public boolean isInt(String path) { + Object val = get(path); + return val instanceof Integer; + } + + public boolean getBoolean(String path) { + Object def = getDefault(path); + return getBoolean(path, (def instanceof Boolean) ? (Boolean) def : false); + } + + public boolean getBoolean(String path, boolean def) { + Object val = get(path, def); + return (val instanceof Boolean) ? (Boolean) val : def; + } + + public boolean isBoolean(String path) { + Object val = get(path); + return val instanceof Boolean; + } + + public double getDouble(String path) { + Object def = getDefault(path); + return getDouble(path, (def instanceof Number) ? toDouble(def) : 0); + } + + public double getDouble(String path, double def) { + Object val = get(path, def); + return (val instanceof Number) ? toDouble(val) : def; + } + + public boolean isDouble(String path) { + Object val = get(path); + return val instanceof Double; + } + + public long getLong(String path) { + Object def = getDefault(path); + return getLong(path, (def instanceof Number) ? toLong(def) : 0); + } + + public long getLong(String path, long def) { + Object val = get(path, def); + return (val instanceof Number) ? toLong(val) : def; + } + + public boolean isLong(String path) { + Object val = get(path); + return val instanceof Long; + } + + // Java + public List getList(String path) { + Object def = getDefault(path); + return getList(path, (def instanceof List) ? (List) def : null); + } + + public List getList(String path, List def) { + Object val = get(path, def); + return (List) ((val instanceof List) ? val : def); + } + + public boolean isList(String path) { + Object val = get(path); + return val instanceof List; + } + + public List getStringList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if ((object instanceof String) || (isPrimitiveWrapper(object))) { + result.add(String.valueOf(object)); + } + } + + return result; + } + + public List getIntegerList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Integer) { + result.add((Integer) object); + } else if (object instanceof String) { + try { + result.add(Integer.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((int) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).intValue()); + } + } + + return result; + } + + public List getBooleanList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Boolean) { + result.add((Boolean) object); + } else if (object instanceof String) { + if (Boolean.TRUE.toString().equals(object)) { + result.add(true); + } else if (Boolean.FALSE.toString().equals(object)) { + result.add(false); + } + } + } + + return result; + } + + public List getDoubleList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Double) { + result.add((Double) object); + } else if (object instanceof String) { + try { + result.add(Double.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((double) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).doubleValue()); + } + } + + return result; + } + + public List getFloatList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Float) { + result.add((Float) object); + } else if (object instanceof String) { + try { + result.add(Float.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((float) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).floatValue()); + } + } + + return result; + } + + public List getLongList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Long) { + result.add((Long) object); + } else if (object instanceof String) { + try { + result.add(Long.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((long) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).longValue()); + } + } + + return result; + } + + public List getByteList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Byte) { + result.add((Byte) object); + } else if (object instanceof String) { + try { + result.add(Byte.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((byte) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).byteValue()); + } + } + + return result; + } + + public List getCharacterList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Character) { + result.add((Character) object); + } else if (object instanceof String) { + String str = (String) object; + + if (str.length() == 1) { + result.add(str.charAt(0)); + } + } else if (object instanceof Number) { + result.add((char) ((Number) object).intValue()); + } + } + + return result; + } + + public List getShortList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Short) { + result.add((Short) object); + } else if (object instanceof String) { + try { + result.add(Short.valueOf((String) object)); + } catch (Exception ex) { + } + } else if (object instanceof Character) { + result.add((short) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).shortValue()); + } + } + + return result; + } + + public List> getMapList(String path) { + List list = getList(path); + List> result = new ArrayList>(); + + if (list == null) { + return result; + } + + for (Object object : list) { + if (object instanceof Map) { + result.add((Map) object); + } + } + + return result; + } + + // Bukkit + public Vector getVector(String path) { + Object def = getDefault(path); + return getVector(path, (def instanceof Vector) ? (Vector) def : null); + } + + public Vector getVector(String path, Vector def) { + Object val = get(path, def); + return (val instanceof Vector) ? (Vector) val : def; + } + + public boolean isVector(String path) { + Object val = get(path); + return val instanceof Vector; + } + + public OfflinePlayer getOfflinePlayer(String path) { + Object def = getDefault(path); + return getOfflinePlayer(path, (def instanceof OfflinePlayer) ? (OfflinePlayer) def : null); + } + + public OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def) { + Object val = get(path, def); + return (val instanceof OfflinePlayer) ? (OfflinePlayer) val : def; + } + + public boolean isOfflinePlayer(String path) { + Object val = get(path); + return val instanceof OfflinePlayer; + } + + public ItemStack getItemStack(String path) { + Object def = getDefault(path); + return getItemStack(path, (def instanceof ItemStack) ? (ItemStack) def : null); + } + + public ItemStack getItemStack(String path, ItemStack def) { + Object val = get(path, def); + return (val instanceof ItemStack) ? (ItemStack) val : def; + } + + public boolean isItemStack(String path) { + Object val = get(path); + return val instanceof ItemStack; + } + + public Color getColor(String path) { + Object def = getDefault(path); + return getColor(path, (def instanceof Color) ? (Color) def : null); + } + + public Color getColor(String path, Color def) { + Object val = get(path, def); + return (val instanceof Color) ? (Color) val : def; + } + + public boolean isColor(String path) { + Object val = get(path); + return val instanceof Color; + } + + public ConfigurationSection getConfigurationSection(String path) { + Object val = get(path, null); + if (val != null) { + return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; + } + + val = get(path, getDefault(path)); + return (val instanceof ConfigurationSection) ? createSection(path) : null; + } + + public boolean isConfigurationSection(String path) { + Object val = get(path); + return val instanceof ConfigurationSection; + } + + protected boolean isPrimitiveWrapper(Object input) { + return input instanceof Integer || input instanceof Boolean || + input instanceof Character || input instanceof Byte || + input instanceof Short || input instanceof Double || + input instanceof Long || input instanceof Float; + } + + protected Object getDefault(String path) { + Validate.notNull(path, "Path cannot be null"); + + Configuration root = getRoot(); + Configuration defaults = root == null ? null : root.getDefaults(); + return (defaults == null) ? null : defaults.get(createPath(this, path)); + } + + protected void mapChildrenKeys(Set output, ConfigurationSection section, boolean deep) { + if (section instanceof MemorySection) { + MemorySection sec = (MemorySection) section; + + for (Map.Entry entry : sec.map.entrySet()) { + output.add(createPath(section, entry.getKey(), this)); + + if ((deep) && (entry.getValue() instanceof ConfigurationSection)) { + ConfigurationSection subsection = (ConfigurationSection) entry.getValue(); + mapChildrenKeys(output, subsection, deep); + } + } + } else { + Set keys = section.getKeys(deep); + + for (String key : keys) { + output.add(createPath(section, key, this)); + } + } + } + + protected void mapChildrenValues(Map output, ConfigurationSection section, boolean deep) { + if (section instanceof MemorySection) { + MemorySection sec = (MemorySection) section; + + for (Map.Entry entry : sec.map.entrySet()) { + output.put(createPath(section, entry.getKey(), this), entry.getValue()); + + if (entry.getValue() instanceof ConfigurationSection) { + if (deep) { + mapChildrenValues(output, (ConfigurationSection) entry.getValue(), deep); + } + } + } + } else { + Map values = section.getValues(deep); + + for (Map.Entry entry : values.entrySet()) { + output.put(createPath(section, entry.getKey(), this), entry.getValue()); + } + } + } + + /** + * Creates a full path to the given {@link ConfigurationSection} from its + * root {@link Configuration}. + *

          + * You may use this method for any given {@link ConfigurationSection}, not + * only {@link MemorySection}. + * + * @param section Section to create a path for. + * @param key Name of the specified section. + * @return Full path of the section from its root. + */ + public static String createPath(ConfigurationSection section, String key) { + return createPath(section, key, (section == null) ? null : section.getRoot()); + } + + /** + * Creates a relative path to the given {@link ConfigurationSection} from + * the given relative section. + *

          + * You may use this method for any given {@link ConfigurationSection}, not + * only {@link MemorySection}. + * + * @param section Section to create a path for. + * @param key Name of the specified section. + * @param relativeTo Section to create the path relative to. + * @return Full path of the section from its root. + */ + public static String createPath(ConfigurationSection section, String key, ConfigurationSection relativeTo) { + Validate.notNull(section, "Cannot create path without a section"); + Configuration root = section.getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot create path without a root"); + } + char separator = root.options().pathSeparator(); + + StringBuilder builder = new StringBuilder(); + if (section != null) { + for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) { + if (builder.length() > 0) { + builder.insert(0, separator); + } + + builder.insert(0, parent.getName()); + } + } + + if ((key != null) && (key.length() > 0)) { + if (builder.length() > 0) { + builder.append(separator); + } + + builder.append(key); + } + + return builder.toString(); + } + + @Override + public String toString() { + Configuration root = getRoot(); + return new StringBuilder() + .append(getClass().getSimpleName()) + .append("[path='") + .append(getCurrentPath()) + .append("', root='") + .append(root == null ? null : root.getClass().getSimpleName()) + .append("']") + .toString(); + } +} diff --git a/src/main/java/org/bukkit/configuration/file/FileConfiguration.java b/src/main/java/org/bukkit/configuration/file/FileConfiguration.java new file mode 100644 index 0000000..9d6d1c6 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/file/FileConfiguration.java @@ -0,0 +1,290 @@ +package org.bukkit.configuration.file; + +import com.google.common.base.Charsets; +import com.google.common.io.Files; + +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.InvalidConfigurationException; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.nio.charset.Charset; + +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.MemoryConfiguration; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +/** + * This is a base class for all File based implementations of {@link + * Configuration} + */ +public abstract class FileConfiguration extends MemoryConfiguration { + /** + * This value specified that the system default encoding should be + * completely ignored, as it cannot handle the ASCII character set, or it + * is a strict-subset of UTF8 already (plain ASCII). + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean UTF8_OVERRIDE; + /** + * This value specifies if the system default encoding is unicode, but + * cannot parse standard ASCII. + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean UTF_BIG; + /** + * This value specifies if the system supports unicode. + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean SYSTEM_UTF; + static { + final byte[] testBytes = Base64Coder.decode("ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX4NCg=="); + final String testString = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\r\n"; + final Charset defaultCharset = Charset.defaultCharset(); + final String resultString = new String(testBytes, defaultCharset); + final boolean trueUTF = defaultCharset.name().contains("UTF"); + UTF8_OVERRIDE = !testString.equals(resultString) || defaultCharset.equals(Charset.forName("US-ASCII")); + SYSTEM_UTF = trueUTF || UTF8_OVERRIDE; + UTF_BIG = trueUTF && UTF8_OVERRIDE; + } + + /** + * Creates an empty {@link FileConfiguration} with no default values. + */ + public FileConfiguration() { + super(); + } + + /** + * Creates an empty {@link FileConfiguration} using the specified {@link + * Configuration} as a source for all default values. + * + * @param defaults Default value provider + */ + public FileConfiguration(Configuration defaults) { + super(defaults); + } + + /** + * Saves this {@link FileConfiguration} to the specified location. + *

          + * If the file does not exist, it will be created. If already exists, it + * will be overwritten. If it cannot be overwritten or created, an + * exception will be thrown. + *

          + * This method will save using the system default encoding, or possibly + * using UTF8. + * + * @param file File to save to. + * @throws IOException Thrown when the given file cannot be written to for + * any reason. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void save(File file) throws IOException { + Validate.notNull(file, "File cannot be null"); + + Files.createParentDirs(file); + + String data = saveToString(); + + Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? Charsets.UTF_8 : Charset.defaultCharset()); + + try { + writer.write(data); + } finally { + writer.close(); + } + } + + /** + * Saves this {@link FileConfiguration} to the specified location. + *

          + * If the file does not exist, it will be created. If already exists, it + * will be overwritten. If it cannot be overwritten or created, an + * exception will be thrown. + *

          + * This method will save using the system default encoding, or possibly + * using UTF8. + * + * @param file File to save to. + * @throws IOException Thrown when the given file cannot be written to for + * any reason. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void save(String file) throws IOException { + Validate.notNull(file, "File cannot be null"); + + save(new File(file)); + } + + /** + * Saves this {@link FileConfiguration} to a string, and returns it. + * + * @return String containing this configuration. + */ + public abstract String saveToString(); + + /** + * Loads this {@link FileConfiguration} from the specified location. + *

          + * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given file. + *

          + * If the file cannot be loaded for any reason, an exception will be + * thrown. + *

          + * This will attempt to use the {@link Charset#defaultCharset()} for + * files, unless {@link #UTF8_OVERRIDE} but not {@link #UTF_BIG} is + * specified. + * + * @param file File to load from. + * @throws FileNotFoundException Thrown when the given file cannot be + * opened. + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException { + Validate.notNull(file, "File cannot be null"); + + final FileInputStream stream = new FileInputStream(file); + + load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? Charsets.UTF_8 : Charset.defaultCharset())); + } + + /** + * Loads this {@link FileConfiguration} from the specified stream. + *

          + * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given stream. + *

          + * This will attempt to use the {@link Charset#defaultCharset()}, unless + * {@link #UTF8_OVERRIDE} or {@link #UTF_BIG} is specified. + * + * @param stream Stream to load from + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when stream is null. + * @deprecated This does not consider encoding + * @see #load(Reader) + */ + @Deprecated + public void load(InputStream stream) throws IOException, InvalidConfigurationException { + Validate.notNull(stream, "Stream cannot be null"); + + load(new InputStreamReader(stream, UTF8_OVERRIDE ? Charsets.UTF_8 : Charset.defaultCharset())); + } + + /** + * Loads this {@link FileConfiguration} from the specified reader. + *

          + * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given stream. + * + * @param reader the reader to load from + * @throws IOException thrown when underlying reader throws an IOException + * @throws InvalidConfigurationException thrown when the reader does not + * represent a valid Configuration + * @throws IllegalArgumentException thrown when reader is null + */ + public void load(Reader reader) throws IOException, InvalidConfigurationException { + BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + + StringBuilder builder = new StringBuilder(); + + try { + String line; + + while ((line = input.readLine()) != null) { + builder.append(line); + builder.append('\n'); + } + } finally { + input.close(); + } + + loadFromString(builder.toString()); + } + + /** + * Loads this {@link FileConfiguration} from the specified location. + *

          + * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given file. + *

          + * If the file cannot be loaded for any reason, an exception will be + * thrown. + * + * @param file File to load from. + * @throws FileNotFoundException Thrown when the given file cannot be + * opened. + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void load(String file) throws FileNotFoundException, IOException, InvalidConfigurationException { + Validate.notNull(file, "File cannot be null"); + + load(new File(file)); + } + + /** + * Loads this {@link FileConfiguration} from the specified string, as + * opposed to from file. + *

          + * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given string. + *

          + * If the string is invalid in any way, an exception will be thrown. + * + * @param contents Contents of a Configuration to load. + * @throws InvalidConfigurationException Thrown if the specified string is + * invalid. + * @throws IllegalArgumentException Thrown if contents is null. + */ + public abstract void loadFromString(String contents) throws InvalidConfigurationException; + + /** + * Compiles the header for this {@link FileConfiguration} and returns the + * result. + *

          + * This will use the header from {@link #options()} -> {@link + * FileConfigurationOptions#header()}, respecting the rules of {@link + * FileConfigurationOptions#copyHeader()} if set. + * + * @return Compiled header + */ + protected abstract String buildHeader(); + + @Override + public FileConfigurationOptions options() { + if (options == null) { + options = new FileConfigurationOptions(this); + } + + return (FileConfigurationOptions) options; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java b/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java new file mode 100644 index 0000000..ccf81e0 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java @@ -0,0 +1,118 @@ +package org.bukkit.configuration.file; + +import org.bukkit.configuration.*; + +/** + * Various settings for controlling the input and output of a {@link + * FileConfiguration} + */ +public class FileConfigurationOptions extends MemoryConfigurationOptions { + private String header = null; + private boolean copyHeader = true; + + protected FileConfigurationOptions(MemoryConfiguration configuration) { + super(configuration); + } + + @Override + public FileConfiguration configuration() { + return (FileConfiguration) super.configuration(); + } + + @Override + public FileConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public FileConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } + + /** + * Gets the header that will be applied to the top of the saved output. + *

          + * This header will be commented out and applied directly at the top of + * the generated output of the {@link FileConfiguration}. It is not + * required to include a newline at the end of the header as it will + * automatically be applied, but you may include one if you wish for extra + * spacing. + *

          + * Null is a valid value which will indicate that no header is to be + * applied. The default value is null. + * + * @return Header + */ + public String header() { + return header; + } + + /** + * Sets the header that will be applied to the top of the saved output. + *

          + * This header will be commented out and applied directly at the top of + * the generated output of the {@link FileConfiguration}. It is not + * required to include a newline at the end of the header as it will + * automatically be applied, but you may include one if you wish for extra + * spacing. + *

          + * Null is a valid value which will indicate that no header is to be + * applied. + * + * @param value New header + * @return This object, for chaining + */ + public FileConfigurationOptions header(String value) { + this.header = value; + return this; + } + + /** + * Gets whether or not the header should be copied from a default source. + *

          + * If this is true, if a default {@link FileConfiguration} is passed to + * {@link + * FileConfiguration#setDefaults(org.bukkit.configuration.Configuration)} + * then upon saving it will use the header from that config, instead of + * the one provided here. + *

          + * If no default is set on the configuration, or the default is not of + * type FileConfiguration, or that config has no header ({@link #header()} + * returns null) then the header specified in this configuration will be + * used. + *

          + * Defaults to true. + * + * @return Whether or not to copy the header + */ + public boolean copyHeader() { + return copyHeader; + } + + /** + * Sets whether or not the header should be copied from a default source. + *

          + * If this is true, if a default {@link FileConfiguration} is passed to + * {@link + * FileConfiguration#setDefaults(org.bukkit.configuration.Configuration)} + * then upon saving it will use the header from that config, instead of + * the one provided here. + *

          + * If no default is set on the configuration, or the default is not of + * type FileConfiguration, or that config has no header ({@link #header()} + * returns null) then the header specified in this configuration will be + * used. + *

          + * Defaults to true. + * + * @param value Whether or not to copy the header + * @return This object, for chaining + */ + public FileConfigurationOptions copyHeader(boolean value) { + copyHeader = value; + + return this; + } +} diff --git a/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java b/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java new file mode 100644 index 0000000..ea4c2b3 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java @@ -0,0 +1,249 @@ +package org.bukkit.configuration.file; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Map; +import java.util.logging.Level; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.representer.Representer; + +/** + * An implementation of {@link Configuration} which saves all files in Yaml. + * Note that this implementation is not synchronized. + */ +public class YamlConfiguration extends FileConfiguration { + protected static final String COMMENT_PREFIX = "# "; + protected static final String BLANK_CONFIG = "{}\n"; + private final DumperOptions yamlOptions = new DumperOptions(); + private final Representer yamlRepresenter = new YamlRepresenter(); + private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); + + @Override + public String saveToString() { + yamlOptions.setIndent(options().indent()); + yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + yamlOptions.setAllowUnicode(SYSTEM_UTF); + yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + String header = buildHeader(); + String dump = yaml.dump(getValues(false)); + + if (dump.equals(BLANK_CONFIG)) { + dump = ""; + } + + return header + dump; + } + + @Override + public void loadFromString(String contents) throws InvalidConfigurationException { + Validate.notNull(contents, "Contents cannot be null"); + + Map input; + try { + input = (Map) yaml.load(contents); + } catch (YAMLException e) { + throw new InvalidConfigurationException(e); + } catch (ClassCastException e) { + throw new InvalidConfigurationException("Top level is not a Map."); + } + + String header = parseHeader(contents); + if (header.length() > 0) { + options().header(header); + } + + if (input != null) { + convertMapsToSections(input, this); + } + } + + protected void convertMapsToSections(Map input, ConfigurationSection section) { + for (Map.Entry entry : input.entrySet()) { + String key = entry.getKey().toString(); + Object value = entry.getValue(); + + if (value instanceof Map) { + convertMapsToSections((Map) value, section.createSection(key)); + } else { + section.set(key, value); + } + } + } + + protected String parseHeader(String input) { + String[] lines = input.split("\r?\n", -1); + StringBuilder result = new StringBuilder(); + boolean readingHeader = true; + boolean foundHeader = false; + + for (int i = 0; (i < lines.length) && (readingHeader); i++) { + String line = lines[i]; + + if (line.startsWith(COMMENT_PREFIX)) { + if (i > 0) { + result.append("\n"); + } + + if (line.length() > COMMENT_PREFIX.length()) { + result.append(line.substring(COMMENT_PREFIX.length())); + } + + foundHeader = true; + } else if ((foundHeader) && (line.length() == 0)) { + result.append("\n"); + } else if (foundHeader) { + readingHeader = false; + } + } + + return result.toString(); + } + + @Override + protected String buildHeader() { + String header = options().header(); + + if (options().copyHeader()) { + Configuration def = getDefaults(); + + if ((def != null) && (def instanceof FileConfiguration)) { + FileConfiguration filedefaults = (FileConfiguration) def; + String defaultsHeader = filedefaults.buildHeader(); + + if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { + return defaultsHeader; + } + } + } + + if (header == null) { + return ""; + } + + StringBuilder builder = new StringBuilder(); + String[] lines = header.split("\r?\n", -1); + boolean startedHeader = false; + + for (int i = lines.length - 1; i >= 0; i--) { + builder.insert(0, "\n"); + + if ((startedHeader) || (lines[i].length() != 0)) { + builder.insert(0, lines[i]); + builder.insert(0, COMMENT_PREFIX); + startedHeader = true; + } + } + + return builder.toString(); + } + + @Override + public YamlConfigurationOptions options() { + if (options == null) { + options = new YamlConfigurationOptions(this); + } + + return (YamlConfigurationOptions) options; + } + + /** + * Creates a new {@link YamlConfiguration}, loading from the given file. + *

          + * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + *

          + * The encoding used may follow the system dependent default. + * + * @param file Input file + * @return Resulting configuration + * @throws IllegalArgumentException Thrown if file is null + */ + public static YamlConfiguration loadConfiguration(File file) { + Validate.notNull(file, "File cannot be null"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(file); + } catch (FileNotFoundException ex) { + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); + } catch (InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file , ex); + } + + return config; + } + + /** + * Creates a new {@link YamlConfiguration}, loading from the given stream. + *

          + * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + * + * @param stream Input stream + * @return Resulting configuration + * @throws IllegalArgumentException Thrown if stream is null + * @deprecated does not properly consider encoding + * @see #load(InputStream) + * @see #loadConfiguration(Reader) + */ + @Deprecated + public static YamlConfiguration loadConfiguration(InputStream stream) { + Validate.notNull(stream, "Stream cannot be null"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(stream); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); + } catch (InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); + } + + return config; + } + + + /** + * Creates a new {@link YamlConfiguration}, loading from the given reader. + *

          + * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + * + * @param reader input + * @return resulting configuration + * @throws IllegalArgumentException Thrown if stream is null + */ + public static YamlConfiguration loadConfiguration(Reader reader) { + Validate.notNull(reader, "Stream cannot be null"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(reader); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); + } catch (InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); + } + + return config; + } +} diff --git a/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java b/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java new file mode 100644 index 0000000..57894e3 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java @@ -0,0 +1,71 @@ +package org.bukkit.configuration.file; + +import org.apache.commons.lang.Validate; + +/** + * Various settings for controlling the input and output of a {@link + * YamlConfiguration} + */ +public class YamlConfigurationOptions extends FileConfigurationOptions { + private int indent = 2; + + protected YamlConfigurationOptions(YamlConfiguration configuration) { + super(configuration); + } + + @Override + public YamlConfiguration configuration() { + return (YamlConfiguration) super.configuration(); + } + + @Override + public YamlConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public YamlConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } + + @Override + public YamlConfigurationOptions header(String value) { + super.header(value); + return this; + } + + @Override + public YamlConfigurationOptions copyHeader(boolean value) { + super.copyHeader(value); + return this; + } + + /** + * Gets how much spaces should be used to indent each line. + *

          + * The minimum value this may be is 2, and the maximum is 9. + * + * @return How much to indent by + */ + public int indent() { + return indent; + } + + /** + * Sets how much spaces should be used to indent each line. + *

          + * The minimum value this may be is 2, and the maximum is 9. + * + * @param value New indent + * @return This object, for chaining + */ + public YamlConfigurationOptions indent(int value) { + Validate.isTrue(value >= 2, "Indent must be at least 2 characters"); + Validate.isTrue(value <= 9, "Indent cannot be greater than 9 characters"); + + this.indent = value; + return this; + } +} diff --git a/src/main/java/org/bukkit/configuration/file/YamlConstructor.java b/src/main/java/org/bukkit/configuration/file/YamlConstructor.java new file mode 100644 index 0000000..73ad722 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/file/YamlConstructor.java @@ -0,0 +1,49 @@ +package org.bukkit.configuration.file; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.nodes.Tag; + +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +public class YamlConstructor extends SafeConstructor { + + public YamlConstructor() { + this.yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); + } + + private class ConstructCustomObject extends ConstructYamlMap { + @Override + public Object construct(Node node) { + if (node.isTwoStepsConstruction()) { + throw new YAMLException("Unexpected referential mapping structure. Node: " + node); + } + + Map raw = (Map) super.construct(node); + + if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { + Map typed = new LinkedHashMap(raw.size()); + for (Map.Entry entry : raw.entrySet()) { + typed.put(entry.getKey().toString(), entry.getValue()); + } + + try { + return ConfigurationSerialization.deserializeObject(typed); + } catch (IllegalArgumentException ex) { + throw new YAMLException("Could not deserialize object", ex); + } + } + + return raw; + } + + @Override + public void construct2ndStep(Node node, Object object) { + throw new YAMLException("Unexpected referential mapping structure. Node: " + node); + } + } +} diff --git a/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java b/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java new file mode 100644 index 0000000..bc9c098 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java @@ -0,0 +1,38 @@ +package org.bukkit.configuration.file; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.representer.Representer; + +public class YamlRepresenter extends Representer { + + public YamlRepresenter() { + this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection()); + this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); + } + + private class RepresentConfigurationSection extends RepresentMap { + @Override + public Node representData(Object data) { + return super.representData(((ConfigurationSection) data).getValues(false)); + } + } + + private class RepresentConfigurationSerializable extends RepresentMap { + @Override + public Node representData(Object data) { + ConfigurationSerializable serializable = (ConfigurationSerializable) data; + Map values = new LinkedHashMap(); + values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass())); + values.putAll(serializable.serialize()); + + return super.representData(values); + } + } +} diff --git a/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java b/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java new file mode 100644 index 0000000..ba3c8c4 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java @@ -0,0 +1,35 @@ +package org.bukkit.configuration.serialization; + +import java.util.Map; + +/** + * Represents an object that may be serialized. + *

          + * These objects MUST implement one of the following, in addition to the + * methods as defined by this interface: + *

            + *
          • A static method "deserialize" that accepts a single {@link Map}< + * {@link String}, {@link Object}> and returns the class.
          • + *
          • A static method "valueOf" that accepts a single {@link Map}<{@link + * String}, {@link Object}> and returns the class.
          • + *
          • A constructor that accepts a single {@link Map}<{@link String}, + * {@link Object}>.
          • + *
          + * In addition to implementing this interface, you must register the class + * with {@link ConfigurationSerialization#registerClass(Class)}. + * + * @see DelegateDeserialization + * @see SerializableAs + */ +public interface ConfigurationSerializable { + + /** + * Creates a Map representation of this class. + *

          + * This class must provide a method to restore this class, as defined in + * the {@link ConfigurationSerializable} interface javadocs. + * + * @return Map containing the current state of this class + */ + public Map serialize(); +} diff --git a/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java b/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java new file mode 100644 index 0000000..96a806f --- /dev/null +++ b/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java @@ -0,0 +1,281 @@ +package org.bukkit.configuration.serialization; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.commons.lang.Validate; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.configuration.Configuration; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.util.BlockVector; +import org.bukkit.util.Vector; + +/** + * Utility class for storing and retrieving classes for {@link Configuration}. + */ +public class ConfigurationSerialization { + public static final String SERIALIZED_TYPE_KEY = "=="; + private final Class clazz; + private static Map> aliases = new HashMap>(); + + static { + registerClass(Vector.class); + registerClass(BlockVector.class); + registerClass(ItemStack.class); + registerClass(Color.class); + registerClass(PotionEffect.class); + registerClass(FireworkEffect.class); + } + + protected ConfigurationSerialization(Class clazz) { + this.clazz = clazz; + } + + protected Method getMethod(String name, boolean isStatic) { + try { + Method method = clazz.getDeclaredMethod(name, Map.class); + + if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) { + return null; + } + if (Modifier.isStatic(method.getModifiers()) != isStatic) { + return null; + } + + return method; + } catch (NoSuchMethodException ex) { + return null; + } catch (SecurityException ex) { + return null; + } + } + + protected Constructor getConstructor() { + try { + return clazz.getConstructor(Map.class); + } catch (NoSuchMethodException ex) { + return null; + } catch (SecurityException ex) { + return null; + } + } + + protected ConfigurationSerializable deserializeViaMethod(Method method, Map args) { + try { + ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args); + + if (result == null) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null"); + } else { + return result; + } + } catch (Throwable ex) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log( + Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); + } + + return null; + } + + protected ConfigurationSerializable deserializeViaCtor(Constructor ctor, Map args) { + try { + return ctor.newInstance(args); + } catch (Throwable ex) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log( + Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); + } + + return null; + } + + public ConfigurationSerializable deserialize(Map args) { + Validate.notNull(args, "Args must not be null"); + + ConfigurationSerializable result = null; + Method method = null; + + if (result == null) { + method = getMethod("deserialize", true); + + if (method != null) { + result = deserializeViaMethod(method, args); + } + } + + if (result == null) { + method = getMethod("valueOf", true); + + if (method != null) { + result = deserializeViaMethod(method, args); + } + } + + if (result == null) { + Constructor constructor = getConstructor(); + + if (constructor != null) { + result = deserializeViaCtor(constructor, args); + } + } + + return result; + } + + /** + * Attempts to deserialize the given arguments into a new instance of the + * given class. + *

          + * The class must implement {@link ConfigurationSerializable}, including + * the extra methods as specified in the javadoc of + * ConfigurationSerializable. + *

          + * If a new instance could not be made, an example being the class not + * fully implementing the interface, null will be returned. + * + * @param args Arguments for deserialization + * @param clazz Class to deserialize into + * @return New instance of the specified class + */ + public static ConfigurationSerializable deserializeObject(Map args, Class clazz) { + return new ConfigurationSerialization(clazz).deserialize(args); + } + + /** + * Attempts to deserialize the given arguments into a new instance of the + * given class. + *

          + * The class must implement {@link ConfigurationSerializable}, including + * the extra methods as specified in the javadoc of + * ConfigurationSerializable. + *

          + * If a new instance could not be made, an example being the class not + * fully implementing the interface, null will be returned. + * + * @param args Arguments for deserialization + * @return New instance of the specified class + */ + public static ConfigurationSerializable deserializeObject(Map args) { + Class clazz = null; + + if (args.containsKey(SERIALIZED_TYPE_KEY)) { + try { + String alias = (String) args.get(SERIALIZED_TYPE_KEY); + + if (alias == null) { + throw new IllegalArgumentException("Cannot have null alias"); + } + clazz = getClassByAlias(alias); + if (clazz == null) { + throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); + } + } catch (ClassCastException ex) { + ex.fillInStackTrace(); + throw ex; + } + } else { + throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); + } + + return new ConfigurationSerialization(clazz).deserialize(args); + } + + /** + * Registers the given {@link ConfigurationSerializable} class by its + * alias + * + * @param clazz Class to register + */ + public static void registerClass(Class clazz) { + DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); + + if (delegate == null) { + registerClass(clazz, getAlias(clazz)); + registerClass(clazz, clazz.getName()); + } + } + + /** + * Registers the given alias to the specified {@link + * ConfigurationSerializable} class + * + * @param clazz Class to register + * @param alias Alias to register as + * @see SerializableAs + */ + public static void registerClass(Class clazz, String alias) { + aliases.put(alias, clazz); + } + + /** + * Unregisters the specified alias to a {@link ConfigurationSerializable} + * + * @param alias Alias to unregister + */ + public static void unregisterClass(String alias) { + aliases.remove(alias); + } + + /** + * Unregisters any aliases for the specified {@link + * ConfigurationSerializable} class + * + * @param clazz Class to unregister + */ + public static void unregisterClass(Class clazz) { + while (aliases.values().remove(clazz)) { + ; + } + } + + /** + * Attempts to get a registered {@link ConfigurationSerializable} class by + * its alias + * + * @param alias Alias of the serializable + * @return Registered class, or null if not found + */ + public static Class getClassByAlias(String alias) { + return aliases.get(alias); + } + + /** + * Gets the correct alias for the given {@link ConfigurationSerializable} + * class + * + * @param clazz Class to get alias for + * @return Alias to use for the class + */ + public static String getAlias(Class clazz) { + DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); + + if (delegate != null) { + if ((delegate.value() == null) || (delegate.value() == clazz)) { + delegate = null; + } else { + return getAlias(delegate.value()); + } + } + + if (delegate == null) { + SerializableAs alias = clazz.getAnnotation(SerializableAs.class); + + if ((alias != null) && (alias.value() != null)) { + return alias.value(); + } + } + + return clazz.getName(); + } +} diff --git a/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java b/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java new file mode 100644 index 0000000..1cfae94 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java @@ -0,0 +1,22 @@ +package org.bukkit.configuration.serialization; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Applies to a {@link ConfigurationSerializable} that will delegate all + * deserialization to another {@link ConfigurationSerializable}. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface DelegateDeserialization { + /** + * Which class should be used as a delegate for this classes + * deserialization + * + * @return Delegate class + */ + public Class value(); +} diff --git a/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java b/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java new file mode 100644 index 0000000..c5ee998 --- /dev/null +++ b/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java @@ -0,0 +1,34 @@ +package org.bukkit.configuration.serialization; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Represents an "alias" that a {@link ConfigurationSerializable} may be + * stored as. + * If this is not present on a {@link ConfigurationSerializable} class, it + * will use the fully qualified name of the class. + *

          + * This value will be stored in the configuration so that the configuration + * deserialization can determine what type it is. + *

          + * Using this annotation on any other class than a {@link + * ConfigurationSerializable} will have no effect. + * + * @see ConfigurationSerialization#registerClass(Class, String) + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SerializableAs { + /** + * This is the name your class will be stored and retrieved as. + *

          + * This name MUST be unique. We recommend using names such as + * "MyPluginThing" instead of "Thing". + * + * @return Name to serialize the class as. + */ + public String value(); +} diff --git a/src/main/java/org/bukkit/conversations/BooleanPrompt.java b/src/main/java/org/bukkit/conversations/BooleanPrompt.java new file mode 100644 index 0000000..3f2c97f --- /dev/null +++ b/src/main/java/org/bukkit/conversations/BooleanPrompt.java @@ -0,0 +1,36 @@ +package org.bukkit.conversations; + +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.BooleanUtils; + +/** + * BooleanPrompt is the base class for any prompt that requires a boolean + * response from the user. + */ +public abstract class BooleanPrompt extends ValidatingPrompt{ + + public BooleanPrompt() { + super(); + } + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + String[] accepted = {"true", "false", "on", "off", "yes", "no"}; + return ArrayUtils.contains(accepted, input.toLowerCase()); + } + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, String input) { + return acceptValidatedInput(context, BooleanUtils.toBoolean(input)); + } + + /** + * Override this method to perform some action with the user's boolean + * response. + * + * @param context Context information about the conversation. + * @param input The user's boolean response. + * @return The next {@link Prompt} in the prompt graph. + */ + protected abstract Prompt acceptValidatedInput(ConversationContext context, boolean input); +} diff --git a/src/main/java/org/bukkit/conversations/Conversable.java b/src/main/java/org/bukkit/conversations/Conversable.java new file mode 100644 index 0000000..55674b5 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/Conversable.java @@ -0,0 +1,57 @@ +package org.bukkit.conversations; + +import org.bukkit.command.CommandSender; + +/** + * The Conversable interface is used to indicate objects that can have + * conversations. + */ +public interface Conversable { + + /** + * Tests to see of a Conversable object is actively engaged in a + * conversation. + * + * @return True if a conversation is in progress + */ + public boolean isConversing(); + + /** + * Accepts input into the active conversation. If no conversation is in + * progress, this method does nothing. + * + * @param input The input message into the conversation + */ + public void acceptConversationInput(String input); + + /** + * Enters into a dialog with a Conversation object. + * + * @param conversation The conversation to begin + * @return True if the conversation should proceed, false if it has been + * enqueued + */ + public boolean beginConversation(Conversation conversation); + + /** + * Abandons an active conversation. + * + * @param conversation The conversation to abandon + */ + public void abandonConversation(Conversation conversation); + + /** + * Abandons an active conversation. + * + * @param conversation The conversation to abandon + * @param details Details about why the conversation was abandoned + */ + public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details); + + /** + * Sends this sender a message raw + * + * @param message Message to be displayed + */ + public void sendRawMessage(String message); +} diff --git a/src/main/java/org/bukkit/conversations/Conversation.java b/src/main/java/org/bukkit/conversations/Conversation.java new file mode 100644 index 0000000..d4c1f6d --- /dev/null +++ b/src/main/java/org/bukkit/conversations/Conversation.java @@ -0,0 +1,297 @@ +package org.bukkit.conversations; + +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The Conversation class is responsible for tracking the current state of a + * conversation, displaying prompts to the user, and dispatching the user's + * response to the appropriate place. Conversation objects are not typically + * instantiated directly. Instead a {@link ConversationFactory} is used to + * construct identical conversations on demand. + *

          + * Conversation flow consists of a directed graph of {@link Prompt} objects. + * Each time a prompt gets input from the user, it must return the next prompt + * in the graph. Since each Prompt chooses the next Prompt, complex + * conversation trees can be implemented where the nature of the player's + * response directs the flow of the conversation. + *

          + * Each conversation has a {@link ConversationPrefix} that prepends all output + * from the conversation to the player. The ConversationPrefix can be used to + * display the plugin name or conversation status as the conversation evolves. + *

          + * Each conversation has a timeout measured in the number of inactive seconds + * to wait before abandoning the conversation. If the inactivity timeout is + * reached, the conversation is abandoned and the user's incoming and outgoing + * chat is returned to normal. + *

          + * You should not construct a conversation manually. Instead, use the {@link + * ConversationFactory} for access to all available options. + */ +public class Conversation { + + private Prompt firstPrompt; + private boolean abandoned; + protected Prompt currentPrompt; + protected ConversationContext context; + protected boolean modal; + protected boolean localEchoEnabled; + protected ConversationPrefix prefix; + protected List cancellers; + protected List abandonedListeners; + + /** + * Initializes a new Conversation. + * + * @param plugin The plugin that owns this conversation. + * @param forWhom The entity for whom this conversation is mediating. + * @param firstPrompt The first prompt in the conversation graph. + */ + public Conversation(Plugin plugin, Conversable forWhom, Prompt firstPrompt) { + this(plugin, forWhom, firstPrompt, new HashMap()); + } + + /** + * Initializes a new Conversation. + * + * @param plugin The plugin that owns this conversation. + * @param forWhom The entity for whom this conversation is mediating. + * @param firstPrompt The first prompt in the conversation graph. + * @param initialSessionData Any initial values to put in the conversation + * context sessionData map. + */ + public Conversation(Plugin plugin, Conversable forWhom, Prompt firstPrompt, Map initialSessionData) { + this.firstPrompt = firstPrompt; + this.context = new ConversationContext(plugin, forWhom, initialSessionData); + this.modal = true; + this.localEchoEnabled = true; + this.prefix = new NullConversationPrefix(); + this.cancellers = new ArrayList(); + this.abandonedListeners = new ArrayList(); + } + + /** + * Gets the entity for whom this conversation is mediating. + * + * @return The entity. + */ + public Conversable getForWhom() { + return context.getForWhom(); + } + + /** + * Gets the modality of this conversation. If a conversation is modal, all + * messages directed to the player are suppressed for the duration of the + * conversation. + * + * @return The conversation modality. + */ + public boolean isModal() { + return modal; + } + + /** + * Sets the modality of this conversation. If a conversation is modal, + * all messages directed to the player are suppressed for the duration of + * the conversation. + * + * @param modal The new conversation modality. + */ + void setModal(boolean modal) { + this.modal = modal; + } + + /** + * Gets the status of local echo for this conversation. If local echo is + * enabled, any text submitted to a conversation gets echoed back into the + * submitter's chat window. + * + * @return The status of local echo. + */ + public boolean isLocalEchoEnabled() { + return localEchoEnabled; + } + + /** + * Sets the status of local echo for this conversation. If local echo is + * enabled, any text submitted to a conversation gets echoed back into the + * submitter's chat window. + * + * @param localEchoEnabled The status of local echo. + */ + public void setLocalEchoEnabled(boolean localEchoEnabled) { + this.localEchoEnabled = localEchoEnabled; + } + + /** + * Gets the {@link ConversationPrefix} that prepends all output from this + * conversation. + * + * @return The ConversationPrefix in use. + */ + public ConversationPrefix getPrefix() { + return prefix; + } + + /** + * Sets the {@link ConversationPrefix} that prepends all output from this + * conversation. + * + * @param prefix The ConversationPrefix to use. + */ + void setPrefix(ConversationPrefix prefix) { + this.prefix = prefix; + } + + /** + * Adds a {@link ConversationCanceller} to the cancellers collection. + * + * @param canceller The {@link ConversationCanceller} to add. + */ + void addConversationCanceller(ConversationCanceller canceller) { + canceller.setConversation(this); + this.cancellers.add(canceller); + } + + /** + * Gets the list of {@link ConversationCanceller}s + * + * @return The list. + */ + public List getCancellers() { + return cancellers; + } + + /** + * Returns the Conversation's {@link ConversationContext}. + * + * @return The ConversationContext. + */ + public ConversationContext getContext() { + return context; + } + + /** + * Displays the first prompt of this conversation and begins redirecting + * the user's chat responses. + */ + public void begin() { + if (currentPrompt == null) { + abandoned = false; + currentPrompt = firstPrompt; + context.getForWhom().beginConversation(this); + } + } + + /** + * Returns Returns the current state of the conversation. + * + * @return The current state of the conversation. + */ + public ConversationState getState() { + if (currentPrompt != null) { + return ConversationState.STARTED; + } else if (abandoned) { + return ConversationState.ABANDONED; + } else { + return ConversationState.UNSTARTED; + } + } + + /** + * Passes player input into the current prompt. The next prompt (as + * determined by the current prompt) is then displayed to the user. + * + * @param input The user's chat text. + */ + public void acceptInput(String input) { + if (currentPrompt != null) { + + // Echo the user's input + if (localEchoEnabled) { + context.getForWhom().sendRawMessage(prefix.getPrefix(context) + input); + } + + // Test for conversation abandonment based on input + for(ConversationCanceller canceller : cancellers) { + if (canceller.cancelBasedOnInput(context, input)) { + abandon(new ConversationAbandonedEvent(this, canceller)); + return; + } + } + + // Not abandoned, output the next prompt + currentPrompt = currentPrompt.acceptInput(context, input); + outputNextPrompt(); + } + } + + /** + * Adds a {@link ConversationAbandonedListener}. + * + * @param listener The listener to add. + */ + public synchronized void addConversationAbandonedListener(ConversationAbandonedListener listener) { + abandonedListeners.add(listener); + } + + /** + * Removes a {@link ConversationAbandonedListener}. + * + * @param listener The listener to remove. + */ + public synchronized void removeConversationAbandonedListener(ConversationAbandonedListener listener) { + abandonedListeners.remove(listener); + } + + /** + * Abandons and resets the current conversation. Restores the user's + * normal chat behavior. + */ + public void abandon() { + abandon(new ConversationAbandonedEvent(this, new ManuallyAbandonedConversationCanceller())); + } + + /** + * Abandons and resets the current conversation. Restores the user's + * normal chat behavior. + * + * @param details Details about why the conversation was abandoned + */ + public synchronized void abandon(ConversationAbandonedEvent details) { + if (!abandoned) { + abandoned = true; + currentPrompt = null; + context.getForWhom().abandonConversation(this); + for (ConversationAbandonedListener listener : abandonedListeners) { + listener.conversationAbandoned(details); + } + } + } + + /** + * Displays the next user prompt and abandons the conversation if the next + * prompt is null. + */ + public void outputNextPrompt() { + if (currentPrompt == null) { + abandon(new ConversationAbandonedEvent(this)); + } else { + context.getForWhom().sendRawMessage(prefix.getPrefix(context) + currentPrompt.getPromptText(context)); + if (!currentPrompt.blocksForInput(context)) { + currentPrompt = currentPrompt.acceptInput(context, null); + outputNextPrompt(); + } + } + } + + public enum ConversationState { + UNSTARTED, + STARTED, + ABANDONED + } +} diff --git a/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java b/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java new file mode 100644 index 0000000..63c4a2a --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java @@ -0,0 +1,53 @@ +package org.bukkit.conversations; + +import java.util.EventObject; + +/** + * ConversationAbandonedEvent contains information about an abandoned + * conversation. + */ +public class ConversationAbandonedEvent extends EventObject { + + private ConversationContext context; + private ConversationCanceller canceller; + + public ConversationAbandonedEvent(Conversation conversation) { + this(conversation, null); + } + + public ConversationAbandonedEvent(Conversation conversation, ConversationCanceller canceller) { + super(conversation); + this.context = conversation.getContext(); + this.canceller = canceller; + } + + /** + * Gets the object that caused the conversation to be abandoned. + * + * @return The object that abandoned the conversation. + */ + public ConversationCanceller getCanceller() { + return canceller; + } + + /** + * Gets the abandoned conversation's conversation context. + * + * @return The abandoned conversation's conversation context. + */ + public ConversationContext getContext() { + return context; + } + + /** + * Indicates how the conversation was abandoned - naturally as part of the + * prompt chain or prematurely via a {@link ConversationCanceller}. + * + * @return True if the conversation is abandoned gracefully by a {@link + * Prompt} returning null or the next prompt. False of the + * conversations is abandoned prematurely by a ConversationCanceller. + */ + public boolean gracefulExit() { + return canceller == null; + } +} diff --git a/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java b/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java new file mode 100644 index 0000000..dc046b1 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java @@ -0,0 +1,15 @@ +package org.bukkit.conversations; + +import java.util.EventListener; + +/** + */ +public interface ConversationAbandonedListener extends EventListener { + /** + * Called whenever a {@link Conversation} is abandoned. + * + * @param abandonedEvent Contains details about the abandoned + * conversation. + */ + public void conversationAbandoned(ConversationAbandonedEvent abandonedEvent); +} diff --git a/src/main/java/org/bukkit/conversations/ConversationCanceller.java b/src/main/java/org/bukkit/conversations/ConversationCanceller.java new file mode 100644 index 0000000..db43bb1 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ConversationCanceller.java @@ -0,0 +1,34 @@ +package org.bukkit.conversations; + +/** + * A ConversationCanceller is a class that cancels an active {@link + * Conversation}. A Conversation can have more than one ConversationCanceller. + */ +public interface ConversationCanceller extends Cloneable { + + /** + * Sets the conversation this ConversationCanceller can optionally cancel. + * + * @param conversation A conversation. + */ + public void setConversation(Conversation conversation); + + /** + * Cancels a conversation based on user input. + * + * @param context Context information about the conversation. + * @param input The input text from the user. + * @return True to cancel the conversation, False otherwise. + */ + public boolean cancelBasedOnInput(ConversationContext context, String input); + + /** + * Allows the {@link ConversationFactory} to duplicate this + * ConversationCanceller when creating a new {@link Conversation}. + *

          + * Implementing this method should reset any internal object state. + * + * @return A clone. + */ + public ConversationCanceller clone(); +} diff --git a/src/main/java/org/bukkit/conversations/ConversationContext.java b/src/main/java/org/bukkit/conversations/ConversationContext.java new file mode 100644 index 0000000..4f33ff4 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ConversationContext.java @@ -0,0 +1,71 @@ +package org.bukkit.conversations; + +import org.bukkit.plugin.Plugin; + +import java.util.Map; + +/** + * A ConversationContext provides continuity between nodes in the prompt graph + * by giving the developer access to the subject of the conversation and a + * generic map for storing values that are shared between all {@link Prompt} + * invocations. + */ +public class ConversationContext { + private Conversable forWhom; + private Map sessionData; + private Plugin plugin; + + /** + * @param plugin The owning plugin. + * @param forWhom The subject of the conversation. + * @param initialSessionData Any initial values to put in the sessionData + * map. + */ + public ConversationContext(Plugin plugin, Conversable forWhom, Map initialSessionData) { + this.plugin = plugin; + this.forWhom = forWhom; + this.sessionData = initialSessionData; + } + + /** + * Gets the plugin that owns this conversation. + * + * @return The owning plugin. + */ + public Plugin getPlugin() { + return plugin; + } + + /** + * Gets the subject of the conversation. + * + * @return The subject of the conversation. + */ + public Conversable getForWhom() { + return forWhom; + } + + /** + * Gets session data shared between all {@link Prompt} invocations. Use + * this as a way to pass data through each Prompt as the conversation + * develops. + * + * @param key The session data key. + * @return The requested session data. + */ + public Object getSessionData(Object key) { + return sessionData.get(key); + } + + /** + * Sets session data shared between all {@link Prompt} invocations. Use + * this as a way to pass data through each prompt as the conversation + * develops. + * + * @param key The session data key. + * @param value The session data value. + */ + public void setSessionData(Object key, Object value) { + sessionData.put(key, value); + } +} diff --git a/src/main/java/org/bukkit/conversations/ConversationFactory.java b/src/main/java/org/bukkit/conversations/ConversationFactory.java new file mode 100644 index 0000000..e7cbd52 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ConversationFactory.java @@ -0,0 +1,228 @@ +package org.bukkit.conversations; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * A ConversationFactory is responsible for creating a {@link Conversation} + * from a predefined template. A ConversationFactory is typically created when + * a plugin is instantiated and builds a Conversation each time a user + * initiates a conversation with the plugin. Each Conversation maintains its + * own state and calls back as needed into the plugin. + *

          + * The ConversationFactory implements a fluid API, allowing parameters to be + * set as an extension to the constructor. + */ +public class ConversationFactory { + + protected Plugin plugin; + protected boolean isModal; + protected boolean localEchoEnabled; + protected ConversationPrefix prefix; + protected Prompt firstPrompt; + protected Map initialSessionData; + protected String playerOnlyMessage; + protected List cancellers; + protected List abandonedListeners; + + /** + * Constructs a ConversationFactory. + * + * @param plugin The plugin that owns the factory. + */ + public ConversationFactory(Plugin plugin) + { + this.plugin = plugin; + isModal = true; + localEchoEnabled = true; + prefix = new NullConversationPrefix(); + firstPrompt = Prompt.END_OF_CONVERSATION; + initialSessionData = new HashMap(); + playerOnlyMessage = null; + cancellers = new ArrayList(); + abandonedListeners = new ArrayList(); + } + + /** + * Sets the modality of all {@link Conversation}s created by this factory. + * If a conversation is modal, all messages directed to the player are + * suppressed for the duration of the conversation. + *

          + * The default is True. + * + * @param modal The modality of all conversations to be created. + * @return This object. + */ + public ConversationFactory withModality(boolean modal) + { + isModal = modal; + return this; + } + + /** + * Sets the local echo status for all {@link Conversation}s created by + * this factory. If local echo is enabled, any text submitted to a + * conversation gets echoed back into the submitter's chat window. + * + * @param localEchoEnabled The status of local echo. + * @return This object. + */ + public ConversationFactory withLocalEcho(boolean localEchoEnabled) { + this.localEchoEnabled = localEchoEnabled; + return this; + } + + /** + * Sets the {@link ConversationPrefix} that prepends all output from all + * generated conversations. + *

          + * The default is a {@link NullConversationPrefix}; + * + * @param prefix The ConversationPrefix to use. + * @return This object. + */ + public ConversationFactory withPrefix(ConversationPrefix prefix) { + this.prefix = prefix; + return this; + } + + /** + * Sets the number of inactive seconds to wait before automatically + * abandoning all generated conversations. + *

          + * The default is 600 seconds (5 minutes). + * + * @param timeoutSeconds The number of seconds to wait. + * @return This object. + */ + public ConversationFactory withTimeout(int timeoutSeconds) { + return withConversationCanceller(new InactivityConversationCanceller(plugin, timeoutSeconds)); + } + + /** + * Sets the first prompt to use in all generated conversations. + *

          + * The default is Prompt.END_OF_CONVERSATION. + * + * @param firstPrompt The first prompt. + * @return This object. + */ + public ConversationFactory withFirstPrompt(Prompt firstPrompt) { + this.firstPrompt = firstPrompt; + return this; + } + + /** + * Sets any initial data with which to populate the conversation context + * sessionData map. + * + * @param initialSessionData The conversation context's initial + * sessionData. + * @return This object. + */ + public ConversationFactory withInitialSessionData(Map initialSessionData) { + this.initialSessionData = initialSessionData; + return this; + } + + /** + * Sets the player input that, when received, will immediately terminate + * the conversation. + * + * @param escapeSequence Input to terminate the conversation. + * @return This object. + */ + public ConversationFactory withEscapeSequence(String escapeSequence) { + return withConversationCanceller(new ExactMatchConversationCanceller(escapeSequence)); + } + + + /** + * Adds a {@link ConversationCanceller} to constructed conversations. + * + * @param canceller The {@link ConversationCanceller} to add. + * @return This object. + */ + public ConversationFactory withConversationCanceller(ConversationCanceller canceller) { + cancellers.add(canceller); + return this; + } + + /** + * Prevents this factory from creating a conversation for non-player + * {@link Conversable} objects. + * + * @param playerOnlyMessage The message to return to a non-play in lieu of + * starting a conversation. + * @return This object. + */ + public ConversationFactory thatExcludesNonPlayersWithMessage(String playerOnlyMessage) { + this.playerOnlyMessage = playerOnlyMessage; + return this; + } + + /** + * Adds a {@link ConversationAbandonedListener} to all conversations + * constructed by this factory. + * + * @param listener The listener to add. + * @return This object. + */ + public ConversationFactory addConversationAbandonedListener(ConversationAbandonedListener listener) { + abandonedListeners.add(listener); + return this; + } + + /** + * Constructs a {@link Conversation} in accordance with the defaults set + * for this factory. + * + * @param forWhom The entity for whom the new conversation is mediating. + * @return A new conversation. + */ + public Conversation buildConversation(Conversable forWhom) { + //Abort conversation construction if we aren't supposed to talk to non-players + if (playerOnlyMessage != null && !(forWhom instanceof Player)) { + return new Conversation(plugin, forWhom, new NotPlayerMessagePrompt()); + } + + //Clone any initial session data + Map copiedInitialSessionData = new HashMap(); + copiedInitialSessionData.putAll(initialSessionData); + + //Build and return a conversation + Conversation conversation = new Conversation(plugin, forWhom, firstPrompt, copiedInitialSessionData); + conversation.setModal(isModal); + conversation.setLocalEchoEnabled(localEchoEnabled); + conversation.setPrefix(prefix); + + //Clone the conversation cancellers + for (ConversationCanceller canceller : cancellers) { + conversation.addConversationCanceller(canceller.clone()); + } + + //Add the ConversationAbandonedListeners + for (ConversationAbandonedListener listener : abandonedListeners) { + conversation.addConversationAbandonedListener(listener); + } + + return conversation; + } + + private class NotPlayerMessagePrompt extends MessagePrompt { + + public String getPromptText(ConversationContext context) { + return playerOnlyMessage; + } + + @Override + protected Prompt getNextPrompt(ConversationContext context) { + return Prompt.END_OF_CONVERSATION; + } + } +} diff --git a/src/main/java/org/bukkit/conversations/ConversationPrefix.java b/src/main/java/org/bukkit/conversations/ConversationPrefix.java new file mode 100644 index 0000000..9889f17 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ConversationPrefix.java @@ -0,0 +1,19 @@ +package org.bukkit.conversations; + +import org.bukkit.command.CommandSender; + +/** + * A ConversationPrefix implementation prepends all output from the + * conversation to the player. The ConversationPrefix can be used to display + * the plugin name or conversation status as the conversation evolves. + */ +public interface ConversationPrefix { + + /** + * Gets the prefix to use before each message to the player. + * + * @param context Context information about the conversation. + * @return The prefix text. + */ + String getPrefix(ConversationContext context); +} diff --git a/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java b/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java new file mode 100644 index 0000000..327b9d9 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java @@ -0,0 +1,29 @@ +package org.bukkit.conversations; + +/** + * An ExactMatchConversationCanceller cancels a conversation if the user + * enters an exact input string + */ +public class ExactMatchConversationCanceller implements ConversationCanceller { + private String escapeSequence; + + /** + * Builds an ExactMatchConversationCanceller. + * + * @param escapeSequence The string that, if entered by the user, will + * cancel the conversation. + */ + public ExactMatchConversationCanceller(String escapeSequence) { + this.escapeSequence = escapeSequence; + } + + public void setConversation(Conversation conversation) {} + + public boolean cancelBasedOnInput(ConversationContext context, String input) { + return input.equals(escapeSequence); + } + + public ConversationCanceller clone() { + return new ExactMatchConversationCanceller(escapeSequence); + } +} diff --git a/src/main/java/org/bukkit/conversations/FixedSetPrompt.java b/src/main/java/org/bukkit/conversations/FixedSetPrompt.java new file mode 100644 index 0000000..b867c11 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/FixedSetPrompt.java @@ -0,0 +1,46 @@ +package org.bukkit.conversations; + +import org.apache.commons.lang.StringUtils; + +import java.util.Arrays; +import java.util.List; + +/** + * FixedSetPrompt is the base class for any prompt that requires a fixed set + * response from the user. + */ +public abstract class FixedSetPrompt extends ValidatingPrompt { + + protected List fixedSet; + + /** + * Creates a FixedSetPrompt from a set of strings. + *

          + * foo = new FixedSetPrompt("bar", "cheese", "panda"); + * + * @param fixedSet A fixed set of strings, one of which the user must + * type. + */ + public FixedSetPrompt(String... fixedSet) { + super(); + this.fixedSet = Arrays.asList(fixedSet); + } + + private FixedSetPrompt() {} + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + return fixedSet.contains(input); + } + + /** + * Utility function to create a formatted string containing all the + * options declared in the constructor. + * + * @return the options formatted like "[bar, cheese, panda]" if bar, + * cheese, and panda were the options used + */ + protected String formatFixedSet() { + return "[" + StringUtils.join(fixedSet, ", ") + "]"; + } +} diff --git a/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java b/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java new file mode 100644 index 0000000..760a518 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java @@ -0,0 +1,79 @@ +package org.bukkit.conversations; + +import org.bukkit.Server; +import org.bukkit.plugin.Plugin; + +/** + * An InactivityConversationCanceller will cancel a {@link Conversation} after + * a period of inactivity by the user. + */ +public class InactivityConversationCanceller implements ConversationCanceller { + protected Plugin plugin; + protected int timeoutSeconds; + protected Conversation conversation; + private int taskId = -1; + + /** + * Creates an InactivityConversationCanceller. + * + * @param plugin The owning plugin. + * @param timeoutSeconds The number of seconds of inactivity to wait. + */ + public InactivityConversationCanceller(Plugin plugin, int timeoutSeconds) { + this.plugin = plugin; + this.timeoutSeconds = timeoutSeconds; + } + + public void setConversation(Conversation conversation) { + this.conversation = conversation; + startTimer(); + } + + public boolean cancelBasedOnInput(ConversationContext context, String input) { + // Reset the inactivity timer + stopTimer(); + startTimer(); + return false; + } + + public ConversationCanceller clone() { + return new InactivityConversationCanceller(plugin, timeoutSeconds); + } + + /** + * Starts an inactivity timer. + */ + private void startTimer() { + taskId = plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + public void run() { + if (conversation.getState() == Conversation.ConversationState.UNSTARTED) { + startTimer(); + } else if (conversation.getState() == Conversation.ConversationState.STARTED) { + cancelling(conversation); + conversation.abandon(new ConversationAbandonedEvent(conversation, InactivityConversationCanceller.this)); + } + } + }, timeoutSeconds * 20); + } + + /** + * Stops the active inactivity timer. + */ + private void stopTimer() { + if (taskId != -1) { + plugin.getServer().getScheduler().cancelTask(taskId); + taskId = -1; + } + } + + /** + * Subclasses of InactivityConversationCanceller can override this method + * to take additional actions when the inactivity timer abandons the + * conversation. + * + * @param conversation The conversation being abandoned. + */ + protected void cancelling(Conversation conversation) { + + } +} diff --git a/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java b/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java new file mode 100644 index 0000000..3e80de1 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java @@ -0,0 +1,20 @@ +package org.bukkit.conversations; + +/** + * The ManuallyAbandonedConversationCanceller is only used as part of a {@link + * ConversationAbandonedEvent} to indicate that the conversation was manually + * abandoned by programmatically calling the abandon() method on it. + */ +public class ManuallyAbandonedConversationCanceller implements ConversationCanceller{ + public void setConversation(Conversation conversation) { + throw new UnsupportedOperationException(); + } + + public boolean cancelBasedOnInput(ConversationContext context, String input) { + throw new UnsupportedOperationException(); + } + + public ConversationCanceller clone() { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/org/bukkit/conversations/MessagePrompt.java b/src/main/java/org/bukkit/conversations/MessagePrompt.java new file mode 100644 index 0000000..fa1775a --- /dev/null +++ b/src/main/java/org/bukkit/conversations/MessagePrompt.java @@ -0,0 +1,42 @@ +package org.bukkit.conversations; + +/** + * MessagePrompt is the base class for any prompt that only displays a message + * to the user and requires no input. + */ +public abstract class MessagePrompt implements Prompt{ + + public MessagePrompt() { + super(); + } + + /** + * Message prompts never wait for user input before continuing. + * + * @param context Context information about the conversation. + * @return Always false. + */ + public boolean blocksForInput(ConversationContext context) { + return false; + } + + /** + * Accepts and ignores any user input, returning the next prompt in the + * prompt graph instead. + * + * @param context Context information about the conversation. + * @param input Ignored. + * @return The next prompt in the prompt graph. + */ + public Prompt acceptInput(ConversationContext context, String input) { + return getNextPrompt(context); + } + + /** + * Override this method to return the next prompt in the prompt graph. + * + * @param context Context information about the conversation. + * @return The next prompt in the prompt graph. + */ + protected abstract Prompt getNextPrompt(ConversationContext context); +} diff --git a/src/main/java/org/bukkit/conversations/NullConversationPrefix.java b/src/main/java/org/bukkit/conversations/NullConversationPrefix.java new file mode 100644 index 0000000..7d8a7d8 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/NullConversationPrefix.java @@ -0,0 +1,20 @@ +package org.bukkit.conversations; + +import org.bukkit.command.CommandSender; + +/** + * NullConversationPrefix is a {@link ConversationPrefix} implementation that + * displays nothing in front of conversation output. + */ +public class NullConversationPrefix implements ConversationPrefix{ + + /** + * Prepends each conversation message with an empty string. + * + * @param context Context information about the conversation. + * @return An empty string. + */ + public String getPrefix(ConversationContext context) { + return ""; + } +} diff --git a/src/main/java/org/bukkit/conversations/NumericPrompt.java b/src/main/java/org/bukkit/conversations/NumericPrompt.java new file mode 100644 index 0000000..f0fdea1 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/NumericPrompt.java @@ -0,0 +1,83 @@ +package org.bukkit.conversations; + +import org.apache.commons.lang.math.NumberUtils; + +/** + * NumericPrompt is the base class for any prompt that requires a {@link + * Number} response from the user. + */ +public abstract class NumericPrompt extends ValidatingPrompt{ + public NumericPrompt() { + super(); + } + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + return NumberUtils.isNumber(input) && isNumberValid(context, NumberUtils.createNumber(input)); + } + + /** + * Override this method to do further validation on the numeric player + * input after the input has been determined to actually be a number. + * + * @param context Context information about the conversation. + * @param input The number the player provided. + * @return The validity of the player's input. + */ + protected boolean isNumberValid(ConversationContext context, Number input) { + return true; + } + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, String input) { + try + { + return acceptValidatedInput(context, NumberUtils.createNumber(input)); + } catch (NumberFormatException e) { + return acceptValidatedInput(context, NumberUtils.INTEGER_ZERO); + } + } + + /** + * Override this method to perform some action with the user's integer + * response. + * + * @param context Context information about the conversation. + * @param input The user's response as a {@link Number}. + * @return The next {@link Prompt} in the prompt graph. + */ + protected abstract Prompt acceptValidatedInput(ConversationContext context, Number input); + + @Override + protected String getFailedValidationText(ConversationContext context, String invalidInput) { + if (NumberUtils.isNumber(invalidInput)) { + return getFailedValidationText(context, NumberUtils.createNumber(invalidInput)); + } else { + return getInputNotNumericText(context, invalidInput); + } + } + + /** + * Optionally override this method to display an additional message if the + * user enters an invalid number. + * + * @param context Context information about the conversation. + * @param invalidInput The invalid input provided by the user. + * @return A message explaining how to correct the input. + */ + protected String getInputNotNumericText(ConversationContext context, String invalidInput) { + return null; + } + + /** + * Optionally override this method to display an additional message if the + * user enters an invalid numeric input. + * + * @param context Context information about the conversation. + * @param invalidInput The invalid input provided by the user. + * @return A message explaining how to correct the input. + */ + protected String getFailedValidationText(ConversationContext context, Number invalidInput) { + return null; + } +} diff --git a/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java b/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java new file mode 100644 index 0000000..feeb715 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java @@ -0,0 +1,38 @@ +package org.bukkit.conversations; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +/** + * PlayerNamePrompt is the base class for any prompt that requires the player + * to enter another player's name. + */ +public abstract class PlayerNamePrompt extends ValidatingPrompt{ + private Plugin plugin; + + public PlayerNamePrompt(Plugin plugin) { + super(); + this.plugin = plugin; + } + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + return plugin.getServer().getPlayer(input) != null; + + } + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, String input) { + return acceptValidatedInput(context, plugin.getServer().getPlayer(input)); + } + + /** + * Override this method to perform some action with the user's player name + * response. + * + * @param context Context information about the conversation. + * @param input The user's player name response. + * @return The next {@link Prompt} in the prompt graph. + */ + protected abstract Prompt acceptValidatedInput(ConversationContext context, Player input); +} diff --git a/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java b/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java new file mode 100644 index 0000000..2290979 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java @@ -0,0 +1,40 @@ +package org.bukkit.conversations; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; + +/** + * PluginNameConversationPrefix is a {@link ConversationPrefix} implementation + * that displays the plugin name in front of conversation output. + */ +public class PluginNameConversationPrefix implements ConversationPrefix { + + protected String separator; + protected ChatColor prefixColor; + protected Plugin plugin; + + private String cachedPrefix; + + public PluginNameConversationPrefix(Plugin plugin) { + this(plugin, " > ", ChatColor.LIGHT_PURPLE); + } + + public PluginNameConversationPrefix(Plugin plugin, String separator, ChatColor prefixColor) { + this.separator = separator; + this.prefixColor = prefixColor; + this.plugin = plugin; + + cachedPrefix = prefixColor + plugin.getDescription().getName() + separator + ChatColor.WHITE; + } + + /** + * Prepends each conversation message with the plugin name. + * + * @param context Context information about the conversation. + * @return An empty string. + */ + public String getPrefix(ConversationContext context) { + return cachedPrefix; + } +} diff --git a/src/main/java/org/bukkit/conversations/Prompt.java b/src/main/java/org/bukkit/conversations/Prompt.java new file mode 100644 index 0000000..7519c84 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/Prompt.java @@ -0,0 +1,45 @@ +package org.bukkit.conversations; + +/** + * A Prompt is the main constituent of a {@link Conversation}. Each prompt + * displays text to the user and optionally waits for a user's response. + * Prompts are chained together into a directed graph that represents the + * conversation flow. To halt a conversation, END_OF_CONVERSATION is returned + * in liu of another Prompt object. + */ +public interface Prompt extends Cloneable { + + /** + * A convenience constant for indicating the end of a conversation. + */ + static final Prompt END_OF_CONVERSATION = null; + + /** + * Gets the text to display to the user when this prompt is first + * presented. + * + * @param context Context information about the conversation. + * @return The text to display. + */ + String getPromptText(ConversationContext context); + + /** + * Checks to see if this prompt implementation should wait for user input + * or immediately display the next prompt. + * + * @param context Context information about the conversation. + * @return If true, the {@link Conversation} will wait for input before + * continuing. + */ + boolean blocksForInput(ConversationContext context); + + /** + * Accepts and processes input from the user. Using the input, the next + * Prompt in the prompt graph is returned. + * + * @param context Context information about the conversation. + * @param input The input text from the user. + * @return The next Prompt in the prompt graph. + */ + Prompt acceptInput(ConversationContext context, String input); +} diff --git a/src/main/java/org/bukkit/conversations/RegexPrompt.java b/src/main/java/org/bukkit/conversations/RegexPrompt.java new file mode 100644 index 0000000..a3c7d1f --- /dev/null +++ b/src/main/java/org/bukkit/conversations/RegexPrompt.java @@ -0,0 +1,28 @@ +package org.bukkit.conversations; + +import java.util.regex.Pattern; + +/** + * RegexPrompt is the base class for any prompt that requires an input + * validated by a regular expression. + */ +public abstract class RegexPrompt extends ValidatingPrompt { + + private Pattern pattern; + + public RegexPrompt(String regex) { + this(Pattern.compile(regex)); + } + + public RegexPrompt(Pattern pattern) { + super(); + this.pattern = pattern; + } + + private RegexPrompt() {} + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + return pattern.matcher(input).matches(); + } +} diff --git a/src/main/java/org/bukkit/conversations/StringPrompt.java b/src/main/java/org/bukkit/conversations/StringPrompt.java new file mode 100644 index 0000000..2934459 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/StringPrompt.java @@ -0,0 +1,18 @@ +package org.bukkit.conversations; + +/** + * StringPrompt is the base class for any prompt that accepts an arbitrary + * string from the user. + */ +public abstract class StringPrompt implements Prompt{ + + /** + * Ensures that the prompt waits for the user to provide input. + * + * @param context Context information about the conversation. + * @return True. + */ + public boolean blocksForInput(ConversationContext context) { + return true; + } +} diff --git a/src/main/java/org/bukkit/conversations/ValidatingPrompt.java b/src/main/java/org/bukkit/conversations/ValidatingPrompt.java new file mode 100644 index 0000000..f41adb4 --- /dev/null +++ b/src/main/java/org/bukkit/conversations/ValidatingPrompt.java @@ -0,0 +1,78 @@ +package org.bukkit.conversations; + +import org.bukkit.ChatColor; + +/** + * ValidatingPrompt is the base class for any prompt that requires validation. + * ValidatingPrompt will keep replaying the prompt text until the user enters + * a valid response. + */ +public abstract class ValidatingPrompt implements Prompt { + public ValidatingPrompt() { + super(); + } + + /** + * Accepts and processes input from the user and validates it. If + * validation fails, this prompt is returned for re-execution, otherwise + * the next Prompt in the prompt graph is returned. + * + * @param context Context information about the conversation. + * @param input The input text from the user. + * @return This prompt or the next Prompt in the prompt graph. + */ + public Prompt acceptInput(ConversationContext context, String input) { + if (isInputValid(context, input)) { + return acceptValidatedInput(context, input); + } else { + String failPrompt = getFailedValidationText(context, input); + if (failPrompt != null) { + context.getForWhom().sendRawMessage(ChatColor.RED + failPrompt); + } + // Redisplay this prompt to the user to re-collect input + return this; + } + } + + /** + * Ensures that the prompt waits for the user to provide input. + * + * @param context Context information about the conversation. + * @return True. + */ + public boolean blocksForInput(ConversationContext context) { + return true; + } + + /** + * Override this method to check the validity of the player's input. + * + * @param context Context information about the conversation. + * @param input The player's raw console input. + * @return True or false depending on the validity of the input. + */ + protected abstract boolean isInputValid(ConversationContext context, String input); + + /** + * Override this method to accept and processes the validated input from + * the user. Using the input, the next Prompt in the prompt graph should + * be returned. + * + * @param context Context information about the conversation. + * @param input The validated input text from the user. + * @return The next Prompt in the prompt graph. + */ + protected abstract Prompt acceptValidatedInput(ConversationContext context, String input); + + /** + * Optionally override this method to display an additional message if the + * user enters an invalid input. + * + * @param context Context information about the conversation. + * @param invalidInput The invalid input provided by the user. + * @return A message explaining how to correct the input. + */ + protected String getFailedValidationText(ConversationContext context, String invalidInput) { + return null; + } +} diff --git a/src/main/java/org/bukkit/enchantments/Enchantment.java b/src/main/java/org/bukkit/enchantments/Enchantment.java new file mode 100644 index 0000000..e038412 --- /dev/null +++ b/src/main/java/org/bukkit/enchantments/Enchantment.java @@ -0,0 +1,292 @@ +package org.bukkit.enchantments; + +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.command.defaults.EnchantCommand; +import org.bukkit.inventory.ItemStack; + +/** + * The various type of enchantments that may be added to armour or weapons + */ +public abstract class Enchantment { + /** + * Provides protection against environmental damage + */ + public static final Enchantment PROTECTION_ENVIRONMENTAL = new EnchantmentWrapper(0); + + /** + * Provides protection against fire damage + */ + public static final Enchantment PROTECTION_FIRE = new EnchantmentWrapper(1); + + /** + * Provides protection against fall damage + */ + public static final Enchantment PROTECTION_FALL = new EnchantmentWrapper(2); + + /** + * Provides protection against explosive damage + */ + public static final Enchantment PROTECTION_EXPLOSIONS = new EnchantmentWrapper(3); + + /** + * Provides protection against projectile damage + */ + public static final Enchantment PROTECTION_PROJECTILE = new EnchantmentWrapper(4); + + /** + * Decreases the rate of air loss whilst underwater + */ + public static final Enchantment OXYGEN = new EnchantmentWrapper(5); + + /** + * Increases the speed at which a player may mine underwater + */ + public static final Enchantment WATER_WORKER = new EnchantmentWrapper(6); + + /** + * Damages the attacker + */ + public static final Enchantment THORNS = new EnchantmentWrapper(7); + + /** + * Increases damage against all targets + */ + public static final Enchantment DAMAGE_ALL = new EnchantmentWrapper(16); + + /** + * Increases damage against undead targets + */ + public static final Enchantment DAMAGE_UNDEAD = new EnchantmentWrapper(17); + + /** + * Increases damage against arthropod targets + */ + public static final Enchantment DAMAGE_ARTHROPODS = new EnchantmentWrapper(18); + + /** + * All damage to other targets will knock them back when hit + */ + public static final Enchantment KNOCKBACK = new EnchantmentWrapper(19); + + /** + * When attacking a target, has a chance to set them on fire + */ + public static final Enchantment FIRE_ASPECT = new EnchantmentWrapper(20); + + /** + * Provides a chance of gaining extra loot when killing monsters + */ + public static final Enchantment LOOT_BONUS_MOBS = new EnchantmentWrapper(21); + + /** + * Increases the rate at which you mine/dig + */ + public static final Enchantment DIG_SPEED = new EnchantmentWrapper(32); + + /** + * Allows blocks to drop themselves instead of fragments (for example, + * stone instead of cobblestone) + */ + public static final Enchantment SILK_TOUCH = new EnchantmentWrapper(33); + + /** + * Decreases the rate at which a tool looses durability + */ + public static final Enchantment DURABILITY = new EnchantmentWrapper(34); + + /** + * Provides a chance of gaining extra loot when destroying blocks + */ + public static final Enchantment LOOT_BONUS_BLOCKS = new EnchantmentWrapper(35); + + /** + * Provides extra damage when shooting arrows from bows + */ + public static final Enchantment ARROW_DAMAGE = new EnchantmentWrapper(48); + + /** + * Provides a knockback when an entity is hit by an arrow from a bow + */ + public static final Enchantment ARROW_KNOCKBACK = new EnchantmentWrapper(49); + + /** + * Sets entities on fire when hit by arrows shot from a bow + */ + public static final Enchantment ARROW_FIRE = new EnchantmentWrapper(50); + + /** + * Provides infinite arrows when shooting a bow + */ + public static final Enchantment ARROW_INFINITE = new EnchantmentWrapper(51); + + /** + * Decreases odds of catching worthless junk + */ + public static final Enchantment LUCK = new EnchantmentWrapper(61); + + /** + * Increases rate of fish biting your hook + */ + public static final Enchantment LURE = new EnchantmentWrapper(62); + + private static final Map byId = new HashMap(); + private static final Map byName = new HashMap(); + private static boolean acceptingNew = true; + private final int id; + + public Enchantment(int id) { + this.id = id; + } + + /** + * Gets the unique ID of this enchantment + * + * @return Unique ID + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets the unique name of this enchantment + * + * @return Unique name + */ + public abstract String getName(); + + /** + * Gets the maximum level that this Enchantment may become. + * + * @return Maximum level of the Enchantment + */ + public abstract int getMaxLevel(); + + /** + * Gets the level that this Enchantment should start at + * + * @return Starting level of the Enchantment + */ + public abstract int getStartLevel(); + + /** + * Gets the type of {@link ItemStack} that may fit this Enchantment. + * + * @return Target type of the Enchantment + */ + public abstract EnchantmentTarget getItemTarget(); + + /** + * Check if this enchantment conflicts with another enchantment. + * + * @param other The enchantment to check against + * @return True if there is a conflict. + */ + public abstract boolean conflictsWith(Enchantment other); + + /** + * Checks if this Enchantment may be applied to the given {@link + * ItemStack}. + *

          + * This does not check if it conflicts with any enchantments already + * applied to the item. + * + * @param item Item to test + * @return True if the enchantment may be applied, otherwise False + */ + public abstract boolean canEnchantItem(ItemStack item); + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof Enchantment)) { + return false; + } + final Enchantment other = (Enchantment) obj; + if (this.id != other.id) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return id; + } + + @Override + public String toString() { + return "Enchantment[" + id + ", " + getName() + "]"; + } + + /** + * Registers an enchantment with the given ID and object. + *

          + * Generally not to be used from within a plugin. + * + * @param enchantment Enchantment to register + */ + public static void registerEnchantment(Enchantment enchantment) { + if (byId.containsKey(enchantment.id) || byName.containsKey(enchantment.getName())) { + throw new IllegalArgumentException("Cannot set already-set enchantment"); + } else if (!isAcceptingRegistrations()) { + throw new IllegalStateException("No longer accepting new enchantments (can only be done by the server implementation)"); + } + + byId.put(enchantment.id, enchantment); + byName.put(enchantment.getName(), enchantment); + } + + /** + * Checks if this is accepting Enchantment registrations. + * + * @return True if the server Implementation may add enchantments + */ + public static boolean isAcceptingRegistrations() { + return acceptingNew; + } + + /** + * Stops accepting any enchantment registrations + */ + public static void stopAcceptingRegistrations() { + acceptingNew = false; + EnchantCommand.buildEnchantments(); + } + + /** + * Gets the Enchantment at the specified ID + * + * @param id ID to fetch + * @return Resulting Enchantment, or null if not found + * @deprecated Magic value + */ + @Deprecated + public static Enchantment getById(int id) { + return byId.get(id); + } + + /** + * Gets the Enchantment at the specified name + * + * @param name Name to fetch + * @return Resulting Enchantment, or null if not found + */ + public static Enchantment getByName(String name) { + return byName.get(name); + } + + /** + * Gets an array of all the registered {@link Enchantment}s + * + * @return Array of enchantments + */ + public static Enchantment[] values() { + return byId.values().toArray(new Enchantment[byId.size()]); + } +} diff --git a/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java b/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java new file mode 100644 index 0000000..d9b98ed --- /dev/null +++ b/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java @@ -0,0 +1,172 @@ +package org.bukkit.enchantments; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +/** + * Represents the applicable target for a {@link Enchantment} + */ +public enum EnchantmentTarget { + /** + * Allows the Enchantment to be placed on all items + */ + ALL { + @Override + public boolean includes(Material item) { + return true; + } + }, + + /** + * Allows the Enchantment to be placed on armor + */ + ARMOR { + @Override + public boolean includes(Material item) { + return ARMOR_FEET.includes(item) + || ARMOR_LEGS.includes(item) + || ARMOR_HEAD.includes(item) + || ARMOR_TORSO.includes(item); + } + }, + + /** + * Allows the Enchantment to be placed on feet slot armor + */ + ARMOR_FEET { + @Override + public boolean includes(Material item) { + return item.equals(Material.LEATHER_BOOTS) + || item.equals(Material.CHAINMAIL_BOOTS) + || item.equals(Material.IRON_BOOTS) + || item.equals(Material.DIAMOND_BOOTS) + || item.equals(Material.GOLD_BOOTS); + } + }, + + /** + * Allows the Enchantment to be placed on leg slot armor + */ + ARMOR_LEGS { + @Override + public boolean includes(Material item) { + return item.equals(Material.LEATHER_LEGGINGS) + || item.equals(Material.CHAINMAIL_LEGGINGS) + || item.equals(Material.IRON_LEGGINGS) + || item.equals(Material.DIAMOND_LEGGINGS) + || item.equals(Material.GOLD_LEGGINGS); + } + }, + + /** + * Allows the Enchantment to be placed on torso slot armor + */ + ARMOR_TORSO { + @Override + public boolean includes(Material item) { + return item.equals(Material.LEATHER_CHESTPLATE) + || item.equals(Material.CHAINMAIL_CHESTPLATE) + || item.equals(Material.IRON_CHESTPLATE) + || item.equals(Material.DIAMOND_CHESTPLATE) + || item.equals(Material.GOLD_CHESTPLATE); + } + }, + + /** + * Allows the Enchantment to be placed on head slot armor + */ + ARMOR_HEAD { + @Override + public boolean includes(Material item) { + return item.equals(Material.LEATHER_HELMET) + || item.equals(Material.CHAINMAIL_HELMET) + || item.equals(Material.DIAMOND_HELMET) + || item.equals(Material.IRON_HELMET) + || item.equals(Material.GOLD_HELMET); + } + }, + + /** + * Allows the Enchantment to be placed on weapons (swords) + */ + WEAPON { + @Override + public boolean includes(Material item) { + return item.equals(Material.WOOD_SWORD) + || item.equals(Material.STONE_SWORD) + || item.equals(Material.IRON_SWORD) + || item.equals(Material.DIAMOND_SWORD) + || item.equals(Material.GOLD_SWORD); + } + }, + + /** + * Allows the Enchantment to be placed on tools (spades, pickaxe, hoes, + * axes) + */ + TOOL { + @Override + public boolean includes(Material item) { + return item.equals(Material.WOOD_SPADE) + || item.equals(Material.STONE_SPADE) + || item.equals(Material.IRON_SPADE) + || item.equals(Material.DIAMOND_SPADE) + || item.equals(Material.GOLD_SPADE) + || item.equals(Material.WOOD_PICKAXE) + || item.equals(Material.STONE_PICKAXE) + || item.equals(Material.IRON_PICKAXE) + || item.equals(Material.DIAMOND_PICKAXE) + || item.equals(Material.GOLD_PICKAXE) + || item.equals(Material.WOOD_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.STONE_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.IRON_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.DIAMOND_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.GOLD_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.WOOD_AXE) + || item.equals(Material.STONE_AXE) + || item.equals(Material.IRON_AXE) + || item.equals(Material.DIAMOND_AXE) + || item.equals(Material.GOLD_AXE) + || item.equals(Material.SHEARS) // NOTE: No vanilla enchantments for this + || item.equals(Material.FLINT_AND_STEEL); // NOTE: No vanilla enchantments for this + } + }, + + /** + * Allows the Enchantment to be placed on bows. + */ + BOW { + @Override + public boolean includes(Material item) { + return item.equals(Material.BOW); + } + }, + + /** + * Allows the Enchantment to be placed on fishing rods. + */ + FISHING_ROD { + @Override + public boolean includes(Material item) { + return item.equals(Material.FISHING_ROD); + } + }; + + /** + * Check whether this target includes the specified item. + * + * @param item The item to check + * @return True if the target includes the item + */ + public abstract boolean includes(Material item); + + /** + * Check whether this target includes the specified item. + * + * @param item The item to check + * @return True if the target includes the item + */ + public boolean includes(ItemStack item) { + return includes(item.getType()); + } +} diff --git a/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java b/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java new file mode 100644 index 0000000..6a0aeb3 --- /dev/null +++ b/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java @@ -0,0 +1,51 @@ +package org.bukkit.enchantments; + +import org.bukkit.inventory.ItemStack; + +/** + * A simple wrapper for ease of selecting {@link Enchantment}s + */ +public class EnchantmentWrapper extends Enchantment { + public EnchantmentWrapper(int id) { + super(id); + } + + /** + * Gets the enchantment bound to this wrapper + * + * @return Enchantment + */ + public Enchantment getEnchantment() { + return Enchantment.getById(getId()); + } + + @Override + public int getMaxLevel() { + return getEnchantment().getMaxLevel(); + } + + @Override + public int getStartLevel() { + return getEnchantment().getStartLevel(); + } + + @Override + public EnchantmentTarget getItemTarget() { + return getEnchantment().getItemTarget(); + } + + @Override + public boolean canEnchantItem(ItemStack item) { + return getEnchantment().canEnchantItem(item); + } + + @Override + public String getName() { + return getEnchantment().getName(); + } + + @Override + public boolean conflictsWith(Enchantment other) { + return getEnchantment().conflictsWith(other); + } +} diff --git a/src/main/java/org/bukkit/entity/Ageable.java b/src/main/java/org/bukkit/entity/Ageable.java new file mode 100644 index 0000000..e9fccb2 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Ageable.java @@ -0,0 +1,67 @@ +package org.bukkit.entity; + +/** + * Represents an entity that can age and breed. + */ +public interface Ageable extends Creature { + /** + * Gets the age of this animal. + * + * @return Age + */ + public int getAge(); + + /** + * Sets the age of this animal. + * + * @param age New age + */ + public void setAge(int age); + + /** + * Lock the age of the animal, setting this will prevent the animal from + * maturing or getting ready for mating. + * + * @param lock new lock + */ + public void setAgeLock(boolean lock); + + /** + * Gets the current agelock. + * + * @return the current agelock + */ + public boolean getAgeLock(); + + /** + * Sets the age of the animal to a baby + */ + public void setBaby(); + + /** + * Sets the age of the animal to an adult + */ + public void setAdult(); + + /** + * Returns true if the animal is an adult. + * + * @return return true if the animal is an adult + */ + public boolean isAdult(); + + /** + * Return the ability to breed of the animal. + * + * @return the ability to breed of the animal + */ + public boolean canBreed(); + + /** + * Set breedability of the animal, if the animal is a baby and set to + * breed it will instantly grow up. + * + * @param breed breedability of the animal + */ + public void setBreed(boolean breed); +} diff --git a/src/main/java/org/bukkit/entity/Ambient.java b/src/main/java/org/bukkit/entity/Ambient.java new file mode 100644 index 0000000..779e389 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Ambient.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents an ambient mob + */ +public interface Ambient extends LivingEntity {} diff --git a/src/main/java/org/bukkit/entity/AnimalTamer.java b/src/main/java/org/bukkit/entity/AnimalTamer.java new file mode 100644 index 0000000..5f74f0d --- /dev/null +++ b/src/main/java/org/bukkit/entity/AnimalTamer.java @@ -0,0 +1,20 @@ +package org.bukkit.entity; + +import java.util.UUID; + +public interface AnimalTamer { + + /** + * This is the name of the specified AnimalTamer. + * + * @return The name to reference on tamed animals or null if a name cannot be obtained + */ + public String getName(); + + /** + * This is the UUID of the specified AnimalTamer. + * + * @return The UUID to reference on tamed animals + */ + public UUID getUniqueId(); +} diff --git a/src/main/java/org/bukkit/entity/Animals.java b/src/main/java/org/bukkit/entity/Animals.java new file mode 100644 index 0000000..f0dc157 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Animals.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents an Animal. + */ +public interface Animals extends Ageable {} diff --git a/src/main/java/org/bukkit/entity/Arrow.java b/src/main/java/org/bukkit/entity/Arrow.java new file mode 100644 index 0000000..e49eef0 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Arrow.java @@ -0,0 +1,42 @@ +package org.bukkit.entity; + +/** + * Represents an arrow. + */ +public interface Arrow extends Projectile { + + /** + * Gets the knockback strength for an arrow, which is the + * {@link org.bukkit.enchantments.Enchantment#KNOCKBACK KnockBack} level + * of the bow that shot it. + * + * @return the knockback strength value + */ + public int getKnockbackStrength(); + + /** + * Sets the knockback strength for an arrow. + * + * @param knockbackStrength the knockback strength value + */ + public void setKnockbackStrength(int knockbackStrength); + + /** + * Gets whether this arrow is critical. + *

          + * Critical arrows have increased damage and cause particle effects. + *

          + * Critical arrows generally occur when a player fully draws a bow before + * firing. + * + * @return true if it is critical + */ + public boolean isCritical(); + + /** + * Sets whether or not this arrow should be critical. + * + * @param critical whether or not it should be critical + */ + public void setCritical(boolean critical); +} diff --git a/src/main/java/org/bukkit/entity/Bat.java b/src/main/java/org/bukkit/entity/Bat.java new file mode 100644 index 0000000..bd73f22 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Bat.java @@ -0,0 +1,27 @@ +package org.bukkit.entity; + +/** + * Represents a Bat + */ +public interface Bat extends Ambient { + + /** + * Checks the current waking state of this bat. + *

          + * This does not imply any persistence of state past the method call. + * + * @return true if the bat is awake or false if it is currently hanging + * from a block + */ + boolean isAwake(); + + /** + * This method modifies the current waking state of this bat. + *

          + * This does not prevent a bat from spontaneously awaking itself, or from + * reattaching itself to a block. + * + * @param state the new state + */ + void setAwake(boolean state); +} diff --git a/src/main/java/org/bukkit/entity/Blaze.java b/src/main/java/org/bukkit/entity/Blaze.java new file mode 100644 index 0000000..7a5505b --- /dev/null +++ b/src/main/java/org/bukkit/entity/Blaze.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a Blaze monster + */ +public interface Blaze extends Monster { + +} diff --git a/src/main/java/org/bukkit/entity/Boat.java b/src/main/java/org/bukkit/entity/Boat.java new file mode 100644 index 0000000..ed2d178 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Boat.java @@ -0,0 +1,72 @@ +package org.bukkit.entity; + +/** + * Represents a boat entity. + */ +public interface Boat extends Vehicle { + + /** + * Gets the maximum speed of a boat. The speed is unrelated to the + * velocity. + * + * @return The max speed. + */ + public double getMaxSpeed(); + + /** + * Sets the maximum speed of a boat. Must be nonnegative. Default is 0.4D. + * + * @param speed The max speed. + */ + public void setMaxSpeed(double speed); + + /** + * Gets the deceleration rate (newSpeed = curSpeed * rate) of occupied + * boats. The default is 0.2. + * + * @return The rate of deceleration + */ + public double getOccupiedDeceleration(); + + /** + * Sets the deceleration rate (newSpeed = curSpeed * rate) of occupied + * boats. Setting this to a higher value allows for quicker acceleration. + * The default is 0.2. + * + * @param rate deceleration rate + */ + public void setOccupiedDeceleration(double rate); + + /** + * Gets the deceleration rate (newSpeed = curSpeed * rate) of unoccupied + * boats. The default is -1. Values below 0 indicate that no additional + * deceleration is imposed. + * + * @return The rate of deceleration + */ + public double getUnoccupiedDeceleration(); + + /** + * Sets the deceleration rate (newSpeed = curSpeed * rate) of unoccupied + * boats. Setting this to a higher value allows for quicker deceleration + * of boats when a player disembarks. The default is -1. Values below 0 + * indicate that no additional deceleration is imposed. + * + * @param rate deceleration rate + */ + public void setUnoccupiedDeceleration(double rate); + + /** + * Get whether boats can work on land. + * + * @return whether boats can work on land + */ + public boolean getWorkOnLand(); + + /** + * Set whether boats can work on land. + * + * @param workOnLand whether boats can work on land + */ + public void setWorkOnLand(boolean workOnLand); +} diff --git a/src/main/java/org/bukkit/entity/CaveSpider.java b/src/main/java/org/bukkit/entity/CaveSpider.java new file mode 100644 index 0000000..9c37646 --- /dev/null +++ b/src/main/java/org/bukkit/entity/CaveSpider.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Spider. + */ +public interface CaveSpider extends Spider {} diff --git a/src/main/java/org/bukkit/entity/Chicken.java b/src/main/java/org/bukkit/entity/Chicken.java new file mode 100644 index 0000000..cb3ec6e --- /dev/null +++ b/src/main/java/org/bukkit/entity/Chicken.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Chicken. + */ +public interface Chicken extends Animals {} diff --git a/src/main/java/org/bukkit/entity/ComplexEntityPart.java b/src/main/java/org/bukkit/entity/ComplexEntityPart.java new file mode 100644 index 0000000..f4ab0bb --- /dev/null +++ b/src/main/java/org/bukkit/entity/ComplexEntityPart.java @@ -0,0 +1,14 @@ +package org.bukkit.entity; + +/** + * Represents a single part of a {@link ComplexLivingEntity} + */ +public interface ComplexEntityPart extends Entity { + + /** + * Gets the parent {@link ComplexLivingEntity} of this part. + * + * @return Parent complex entity + */ + public ComplexLivingEntity getParent(); +} diff --git a/src/main/java/org/bukkit/entity/ComplexLivingEntity.java b/src/main/java/org/bukkit/entity/ComplexLivingEntity.java new file mode 100644 index 0000000..f74411c --- /dev/null +++ b/src/main/java/org/bukkit/entity/ComplexLivingEntity.java @@ -0,0 +1,16 @@ +package org.bukkit.entity; + +import java.util.Set; + +/** + * Represents a complex living entity - one that is made up of various smaller + * parts + */ +public interface ComplexLivingEntity extends LivingEntity { + /** + * Gets a list of parts that belong to this complex entity + * + * @return List of parts + */ + public Set getParts(); +} diff --git a/src/main/java/org/bukkit/entity/Cow.java b/src/main/java/org/bukkit/entity/Cow.java new file mode 100644 index 0000000..cd4ed4d --- /dev/null +++ b/src/main/java/org/bukkit/entity/Cow.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Cow. + */ +public interface Cow extends Animals {} diff --git a/src/main/java/org/bukkit/entity/Creature.java b/src/main/java/org/bukkit/entity/Creature.java new file mode 100644 index 0000000..f223f55 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Creature.java @@ -0,0 +1,26 @@ +package org.bukkit.entity; + +/** + * Represents a Creature. Creatures are non-intelligent monsters or animals + * which have very simple abilities. + */ +public interface Creature extends LivingEntity { + + /** + * Instructs this Creature to set the specified LivingEntity as its + * target. + *

          + * Hostile creatures may attack their target, and friendly creatures may + * follow their target. + * + * @param target New LivingEntity to target, or null to clear the target + */ + public void setTarget(LivingEntity target); + + /** + * Gets the current target of this Creature + * + * @return Current target of this creature, or null if none exists + */ + public LivingEntity getTarget(); +} diff --git a/src/main/java/org/bukkit/entity/CreatureType.java b/src/main/java/org/bukkit/entity/CreatureType.java new file mode 100644 index 0000000..fd23093 --- /dev/null +++ b/src/main/java/org/bukkit/entity/CreatureType.java @@ -0,0 +1,102 @@ +package org.bukkit.entity; + +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; + +/** + * Represents a type of creature. + * + * @deprecated Use EntityType instead. + */ +@Deprecated +public enum CreatureType { + // These strings MUST match the strings in nms.EntityTypes and are case sensitive. + CREEPER("Creeper", Creeper.class, 50), + SKELETON("Skeleton", Skeleton.class, 51), + SPIDER("Spider", Spider.class, 52), + GIANT("Giant", Giant.class, 53), + ZOMBIE("Zombie", Zombie.class, 54), + SLIME("Slime", Slime.class, 55), + GHAST("Ghast", Ghast.class, 56), + PIG_ZOMBIE("PigZombie", PigZombie.class, 57), + ENDERMAN("Enderman", Enderman.class, 58), + CAVE_SPIDER("CaveSpider", CaveSpider.class, 59), + SILVERFISH("Silverfish", Silverfish.class, 60), + BLAZE("Blaze", Blaze.class, 61), + MAGMA_CUBE("LavaSlime", MagmaCube.class, 62), + ENDER_DRAGON("EnderDragon", EnderDragon.class, 63), + PIG("Pig", Pig.class, 90), + SHEEP("Sheep", Sheep.class, 91), + COW("Cow", Cow.class, 92), + CHICKEN("Chicken", Chicken.class, 93), + SQUID("Squid", Squid.class, 94), + WOLF("Wolf", Wolf.class, 95), + MUSHROOM_COW("MushroomCow", MushroomCow.class, 96), + SNOWMAN("SnowMan", Snowman.class, 97), + VILLAGER("Villager", Villager.class, 120); + + private String name; + private Class clazz; + private short typeId; + + private static final Map NAME_MAP = new HashMap(); + private static final Map ID_MAP = new HashMap(); + + static { + for (CreatureType type : EnumSet.allOf(CreatureType.class)) { + NAME_MAP.put(type.name, type); + if (type.typeId != 0) { + ID_MAP.put(type.typeId, type); + } + } + } + + private CreatureType(String name, Class clazz, int typeId) { + this.name = name; + this.clazz = clazz; + this.typeId = (short) typeId; + } + + public String getName() { + return name; + } + + public Class getEntityClass() { + return clazz; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public short getTypeId() { + return typeId; + } + + public static CreatureType fromName(String name) { + return NAME_MAP.get(name); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public static CreatureType fromId(int id) { + if (id > Short.MAX_VALUE) { + return null; + } + return ID_MAP.get((short) id); + } + + @Deprecated + public EntityType toEntityType() { + return EntityType.fromName(getName()); + } + + public static CreatureType fromEntityType(EntityType creatureType) { + return fromName(creatureType.getName()); + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/entity/Creeper.java b/src/main/java/org/bukkit/entity/Creeper.java new file mode 100644 index 0000000..a2f7809 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Creeper.java @@ -0,0 +1,21 @@ +package org.bukkit.entity; + +/** + * Represents a Creeper + */ +public interface Creeper extends Monster { + + /** + * Checks if this Creeper is powered (Electrocuted) + * + * @return true if this creeper is powered + */ + public boolean isPowered(); + + /** + * Sets the Powered status of this Creeper + * + * @param value New Powered status + */ + public void setPowered(boolean value); +} diff --git a/src/main/java/org/bukkit/entity/Damageable.java b/src/main/java/org/bukkit/entity/Damageable.java new file mode 100644 index 0000000..53877a8 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Damageable.java @@ -0,0 +1,112 @@ +package org.bukkit.entity; + +/** + * Represents an {@link Entity} that has health and can take damage. + */ +public interface Damageable extends Entity { + /** + * Deals the given amount of damage to this entity. + * + * @param amount Amount of damage to deal + */ + void damage(double amount); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + void _INVALID_damage(int amount); + + /** + * Deals the given amount of damage to this entity, from a specified + * entity. + * + * @param amount Amount of damage to deal + * @param source Entity which to attribute this damage from + */ + void damage(double amount, Entity source); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + void _INVALID_damage(int amount, Entity source); + + /** + * Gets the entity's health from 0 to {@link #getMaxHealth()}, where 0 is dead. + * + * @return Health represented from 0 to max + */ + double getHealth(); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + int _INVALID_getHealth(); + + /** + * Sets the entity's health from 0 to {@link #getMaxHealth()}, where 0 is + * dead. + * + * @param health New health represented from 0 to max + * @throws IllegalArgumentException Thrown if the health is < 0 or > + * {@link #getMaxHealth()} + */ + void setHealth(double health); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + void _INVALID_setHealth(int health); + + /** + * Gets the maximum health this entity has. + * + * @return Maximum health + */ + double getMaxHealth(); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + int _INVALID_getMaxHealth(); + + /** + * Sets the maximum health this entity can have. + *

          + * If the health of the entity is above the value provided it will be set + * to that value. + *

          + * Note: An entity with a health bar ({@link Player}, {@link EnderDragon}, + * {@link Wither}, etc...} will have their bar scaled accordingly. + * + * @param health amount of health to set the maximum to + */ + void setMaxHealth(double health); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + void _INVALID_setMaxHealth(int health); + + /** + * Resets the max health to the original amount. + */ + void resetMaxHealth(); +} diff --git a/src/main/java/org/bukkit/entity/Egg.java b/src/main/java/org/bukkit/entity/Egg.java new file mode 100644 index 0000000..2dcc00b --- /dev/null +++ b/src/main/java/org/bukkit/entity/Egg.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a thrown egg. + */ +public interface Egg extends Projectile {} diff --git a/src/main/java/org/bukkit/entity/EnderCrystal.java b/src/main/java/org/bukkit/entity/EnderCrystal.java new file mode 100644 index 0000000..bac547e --- /dev/null +++ b/src/main/java/org/bukkit/entity/EnderCrystal.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * A crystal that heals nearby EnderDragons + */ +public interface EnderCrystal extends Entity { +} diff --git a/src/main/java/org/bukkit/entity/EnderDragon.java b/src/main/java/org/bukkit/entity/EnderDragon.java new file mode 100644 index 0000000..609f3ba --- /dev/null +++ b/src/main/java/org/bukkit/entity/EnderDragon.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents an Ender Dragon + */ +public interface EnderDragon extends ComplexLivingEntity { + +} diff --git a/src/main/java/org/bukkit/entity/EnderDragonPart.java b/src/main/java/org/bukkit/entity/EnderDragonPart.java new file mode 100644 index 0000000..9516f56 --- /dev/null +++ b/src/main/java/org/bukkit/entity/EnderDragonPart.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents an ender dragon part + */ +public interface EnderDragonPart extends ComplexEntityPart, Damageable { + public EnderDragon getParent(); +} diff --git a/src/main/java/org/bukkit/entity/EnderPearl.java b/src/main/java/org/bukkit/entity/EnderPearl.java new file mode 100644 index 0000000..db18a90 --- /dev/null +++ b/src/main/java/org/bukkit/entity/EnderPearl.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a thrown Ender Pearl entity + */ +public interface EnderPearl extends Projectile { + +} diff --git a/src/main/java/org/bukkit/entity/EnderSignal.java b/src/main/java/org/bukkit/entity/EnderSignal.java new file mode 100644 index 0000000..3d2d76c --- /dev/null +++ b/src/main/java/org/bukkit/entity/EnderSignal.java @@ -0,0 +1,9 @@ +package org.bukkit.entity; + +/** + * Represents an Ender Signal, which is often created upon throwing an ender + * eye + */ +public interface EnderSignal extends Entity { + +} diff --git a/src/main/java/org/bukkit/entity/Enderman.java b/src/main/java/org/bukkit/entity/Enderman.java new file mode 100644 index 0000000..0b66a92 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Enderman.java @@ -0,0 +1,23 @@ +package org.bukkit.entity; + +import org.bukkit.material.MaterialData; + +/** + * Represents an Enderman. + */ +public interface Enderman extends Monster { + + /** + * Get the id and data of the block that the Enderman is carrying. + * + * @return MaterialData containing the id and data of the block + */ + public MaterialData getCarriedMaterial(); + + /** + * Set the id and data of the block that the Enderman is carring. + * + * @param material data to set the carried block to + */ + public void setCarriedMaterial(MaterialData material); +} diff --git a/src/main/java/org/bukkit/entity/Entity.java b/src/main/java/org/bukkit/entity/Entity.java new file mode 100644 index 0000000..396ea20 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Entity.java @@ -0,0 +1,294 @@ +package org.bukkit.entity; + +import org.bukkit.Location; +import org.bukkit.EntityEffect; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.metadata.Metadatable; +import org.bukkit.util.Vector; + +import java.util.List; +import java.util.UUID; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + +/** + * Represents a base entity in the world + */ +public interface Entity extends Metadatable { + + /** + * Gets the entity's current position + * + * @return a new copy of Location containing the position of this entity + */ + public Location getLocation(); + + /** + * Stores the entity's current position in the provided Location object. + *

          + * If the provided Location is null this method does nothing and returns + * null. + * + * @return The Location object provided or null + */ + public Location getLocation(Location loc); + + /** + * Sets this entity's velocity + * + * @param velocity New velocity to travel with + */ + public void setVelocity(Vector velocity); + + /** + * Gets this entity's current velocity + * + * @return Current travelling velocity of this entity + */ + public Vector getVelocity(); + + /** + * Returns true if the entity is supported by a block. This value is a + * state updated by the server and is not recalculated unless the entity + * moves. + * + * @return True if entity is on ground. + */ + public boolean isOnGround(); + + /** + * Gets the current world this entity resides in + * + * @return World + */ + public World getWorld(); + + /** + * Teleports this entity to the given location + * + * @param location New location to teleport this entity to + * @return true if the teleport was successful + */ + public boolean teleport(Location location); + + /** + * Teleports this entity to the given location + * + * @param location New location to teleport this entity to + * @param cause The cause of this teleportation + * @return true if the teleport was successful + */ + public boolean teleport(Location location, TeleportCause cause); + + /** + * Teleports this entity to the target Entity + * + * @param destination Entity to teleport this entity to + * @return true if the teleport was successful + */ + public boolean teleport(Entity destination); + + /** + * Teleports this entity to the target Entity + * + * @param destination Entity to teleport this entity to + * @param cause The cause of this teleportation + * @return true if the teleport was successful + */ + public boolean teleport(Entity destination, TeleportCause cause); + + /** + * Returns a list of entities within a bounding box centered around this + * entity + * + * @param x 1/2 the size of the box along x axis + * @param y 1/2 the size of the box along y axis + * @param z 1/2 the size of the box along z axis + * @return List List of entities nearby + */ + public List getNearbyEntities(double x, double y, double z); + + /** + * Returns a unique id for this entity + * + * @return Entity id + */ + public int getEntityId(); + + /** + * Returns the entity's current fire ticks (ticks before the entity stops + * being on fire). + * + * @return int fireTicks + */ + public int getFireTicks(); + + /** + * Returns the entity's maximum fire ticks. + * + * @return int maxFireTicks + */ + public int getMaxFireTicks(); + + /** + * Sets the entity's current fire ticks (ticks before the entity stops + * being on fire). + * + * @param ticks Current ticks remaining + */ + public void setFireTicks(int ticks); + + /** + * Mark the entity's removal. + */ + public void remove(); + + /** + * Returns true if this entity has been marked for removal. + * + * @return True if it is dead. + */ + public boolean isDead(); + + /** + * Returns false if the entity has died or been despawned for some other + * reason. + * + * @return True if valid. + */ + public boolean isValid(); + + /** + * Gets the {@link Server} that contains this Entity + * + * @return Server instance running this Entity + */ + public Server getServer(); + + /** + * Gets the primary passenger of a vehicle. For vehicles that could have + * multiple passengers, this will only return the primary passenger. + * + * @return an entity + */ + public abstract Entity getPassenger(); + + /** + * Set the passenger of a vehicle. + * + * @param passenger The new passenger. + * @return false if it could not be done for whatever reason + */ + public abstract boolean setPassenger(Entity passenger); + + /** + * Check if a vehicle has passengers. + * + * @return True if the vehicle has no passengers. + */ + public abstract boolean isEmpty(); + + /** + * Eject any passenger. + * + * @return True if there was a passenger. + */ + public abstract boolean eject(); + + /** + * Returns the distance this entity has fallen + * + * @return The distance. + */ + public float getFallDistance(); + + /** + * Sets the fall distance for this entity + * + * @param distance The new distance. + */ + public void setFallDistance(float distance); + + /** + * Record the last {@link EntityDamageEvent} inflicted on this entity + * + * @param event a {@link EntityDamageEvent} + */ + public void setLastDamageCause(EntityDamageEvent event); + + /** + * Retrieve the last {@link EntityDamageEvent} inflicted on this entity. + * This event may have been cancelled. + * + * @return the last known {@link EntityDamageEvent} or null if hitherto + * unharmed + */ + public EntityDamageEvent getLastDamageCause(); + + /** + * Returns a unique and persistent id for this entity + * + * @return unique id + */ + public UUID getUniqueId(); + + /** + * Gets the amount of ticks this entity has lived for. + *

          + * This is the equivalent to "age" in entities. + * + * @return Age of entity + */ + public int getTicksLived(); + + /** + * Sets the amount of ticks this entity has lived for. + *

          + * This is the equivalent to "age" in entities. May not be less than one + * tick. + * + * @param value Age of entity + */ + public void setTicksLived(int value); + + /** + * Performs the specified {@link EntityEffect} for this entity. + *

          + * This will be viewable to all players near the entity. + * + * @param type Effect to play. + */ + public void playEffect(EntityEffect type); + + /** + * Get the type of the entity. + * + * @return The entity type. + */ + public EntityType getType(); + + /** + * Returns whether this entity is inside a vehicle. + * + * @return True if the entity is in a vehicle. + */ + public boolean isInsideVehicle(); + + /** + * Leave the current vehicle. If the entity is currently in a vehicle (and + * is removed from it), true will be returned, otherwise false will be + * returned. + * + * @return True if the entity was in a vehicle. + */ + public boolean leaveVehicle(); + + /** + * Get the vehicle that this player is inside. If there is no vehicle, + * null will be returned. + * + * @return The current vehicle. + */ + public Entity getVehicle(); +} diff --git a/src/main/java/org/bukkit/entity/EntityType.java b/src/main/java/org/bukkit/entity/EntityType.java new file mode 100644 index 0000000..39ecb13 --- /dev/null +++ b/src/main/java/org/bukkit/entity/EntityType.java @@ -0,0 +1,267 @@ +package org.bukkit.entity; + +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.entity.minecart.CommandMinecart; +import org.bukkit.entity.minecart.HopperMinecart; +import org.bukkit.entity.minecart.SpawnerMinecart; +import org.bukkit.entity.minecart.RideableMinecart; +import org.bukkit.entity.minecart.ExplosiveMinecart; +import org.bukkit.entity.minecart.PoweredMinecart; +import org.bukkit.entity.minecart.StorageMinecart; +import org.bukkit.inventory.ItemStack; +import org.bukkit.Location; +import org.bukkit.World; + +public enum EntityType { + + // These strings MUST match the strings in nms.EntityTypes and are case sensitive. + /** + * An item resting on the ground. + *

          + * Spawn with {@link World#dropItem(Location, ItemStack)} or {@link + * World#dropItemNaturally(Location, ItemStack)} + */ + DROPPED_ITEM("Item", Item.class, 1, false), + /** + * An experience orb. + */ + EXPERIENCE_ORB("XPOrb", ExperienceOrb.class, 2), + /** + * A leash attached to a fencepost. + */ + LEASH_HITCH("LeashKnot", LeashHitch.class, 8), + /** + * A painting on a wall. + */ + PAINTING("Painting", Painting.class, 9), + /** + * An arrow projectile; may get stuck in the ground. + */ + ARROW("Arrow", Arrow.class, 10), + /** + * A flying snowball. + */ + SNOWBALL("Snowball", Snowball.class, 11), + /** + * A flying large fireball, as thrown by a Ghast for example. + */ + FIREBALL("Fireball", LargeFireball.class, 12), + /** + * A flying small fireball, such as thrown by a Blaze or player. + */ + SMALL_FIREBALL("SmallFireball", SmallFireball.class, 13), + /** + * A flying ender pearl. + */ + ENDER_PEARL("ThrownEnderpearl", EnderPearl.class, 14), + /** + * An ender eye signal. + */ + ENDER_SIGNAL("EyeOfEnderSignal", EnderSignal.class, 15), + /** + * A flying experience bottle. + */ + THROWN_EXP_BOTTLE("ThrownExpBottle", ThrownExpBottle.class, 17), + /** + * An item frame on a wall. + */ + ITEM_FRAME("ItemFrame", ItemFrame.class, 18), + /** + * A flying wither skull projectile. + */ + WITHER_SKULL("WitherSkull", WitherSkull.class, 19), + /** + * Primed TNT that is about to explode. + */ + PRIMED_TNT("PrimedTnt", TNTPrimed.class, 20), + /** + * A block that is going to or is about to fall. + */ + FALLING_BLOCK("FallingSand", FallingBlock.class, 21, false), + FIREWORK("FireworksRocketEntity", Firework.class, 22, false), + /** + * @see CommandMinecart + */ + MINECART_COMMAND("MinecartCommandBlock", CommandMinecart.class, 40), + /** + * A placed boat. + */ + BOAT("Boat", Boat.class, 41), + /** + * @see RideableMinecart + */ + MINECART("MinecartRideable", RideableMinecart.class, 42), + /** + * @see StorageMinecart + */ + MINECART_CHEST("MinecartChest", StorageMinecart.class, 43), + /** + * @see PoweredMinecart + */ + MINECART_FURNACE("MinecartFurnace", PoweredMinecart.class, 44), + /** + * @see ExplosiveMinecart + */ + MINECART_TNT("MinecartTNT", ExplosiveMinecart.class, 45), + /** + * @see HopperMinecart + */ + MINECART_HOPPER("MinecartHopper", HopperMinecart.class, 46), + /** + * @see SpawnerMinecart + */ + MINECART_MOB_SPAWNER("MinecartMobSpawner", SpawnerMinecart.class, 47), + CREEPER("Creeper", Creeper.class, 50), + SKELETON("Skeleton", Skeleton.class, 51), + SPIDER("Spider", Spider.class, 52), + GIANT("Giant", Giant.class, 53), + ZOMBIE("Zombie", Zombie.class, 54), + SLIME("Slime", Slime.class, 55), + GHAST("Ghast", Ghast.class, 56), + PIG_ZOMBIE("PigZombie", PigZombie.class, 57), + ENDERMAN("Enderman", Enderman.class, 58), + CAVE_SPIDER("CaveSpider", CaveSpider.class, 59), + SILVERFISH("Silverfish", Silverfish.class, 60), + BLAZE("Blaze", Blaze.class, 61), + MAGMA_CUBE("LavaSlime", MagmaCube.class, 62), + ENDER_DRAGON("EnderDragon", EnderDragon.class, 63), + WITHER("WitherBoss", Wither.class, 64), + BAT("Bat", Bat.class, 65), + WITCH("Witch", Witch.class, 66), + PIG("Pig", Pig.class, 90), + SHEEP("Sheep", Sheep.class, 91), + COW("Cow", Cow.class, 92), + CHICKEN("Chicken", Chicken.class, 93), + SQUID("Squid", Squid.class, 94), + WOLF("Wolf", Wolf.class, 95), + MUSHROOM_COW("MushroomCow", MushroomCow.class, 96), + SNOWMAN("SnowMan", Snowman.class, 97), + OCELOT("Ozelot", Ocelot.class, 98), + IRON_GOLEM("VillagerGolem", IronGolem.class, 99), + HORSE("EntityHorse", Horse.class, 100), + VILLAGER("Villager", Villager.class, 120), + ENDER_CRYSTAL("EnderCrystal", EnderCrystal.class, 200), + // These don't have an entity ID in nms.EntityTypes. + /** + * A flying splash potion. + */ + SPLASH_POTION(null, ThrownPotion.class, -1, false), + /** + * A flying chicken egg. + */ + EGG(null, Egg.class, -1, false), + /** + * A fishing line and bobber. + */ + FISHING_HOOK(null, Fish.class, -1, false), + /** + * A bolt of lightning. + *

          + * Spawn with {@link World#strikeLightning(Location)}. + */ + LIGHTNING(null, LightningStrike.class, -1, false), + WEATHER(null, Weather.class, -1, false), + PLAYER(null, Player.class, -1, false), + COMPLEX_PART(null, ComplexEntityPart.class, -1, false), + /** + * An unknown entity without an Entity Class + */ + UNKNOWN(null, null, -1, false); + + private String name; + private Class clazz; + private short typeId; + private boolean independent, living; + + private static final Map NAME_MAP = new HashMap(); + private static final Map ID_MAP = new HashMap(); + + static { + for (EntityType type : values()) { + if (type.name != null) { + NAME_MAP.put(type.name.toLowerCase(), type); + } + if (type.typeId > 0) { + ID_MAP.put(type.typeId, type); + } + } + } + + private EntityType(String name, Class clazz, int typeId) { + this(name, clazz, typeId, true); + } + + private EntityType(String name, Class clazz, int typeId, boolean independent) { + this.name = name; + this.clazz = clazz; + this.typeId = (short) typeId; + this.independent = independent; + if (clazz != null) { + this.living = LivingEntity.class.isAssignableFrom(clazz); + } + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public String getName() { + return name; + } + + public Class getEntityClass() { + return clazz; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public short getTypeId() { + return typeId; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public static EntityType fromName(String name) { + if (name == null) { + return null; + } + return NAME_MAP.get(name.toLowerCase()); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public static EntityType fromId(int id) { + if (id > Short.MAX_VALUE) { + return null; + } + return ID_MAP.get((short) id); + } + + /** + * Some entities cannot be spawned using {@link + * World#spawnEntity(Location, EntityType)} or {@link + * World#spawn(Location, Class)}, usually because they require additional + * information in order to spawn. + * + * @return False if the entity type cannot be spawned + */ + public boolean isSpawnable() { + return independent; + } + + public boolean isAlive() { + return living; + } +} diff --git a/src/main/java/org/bukkit/entity/ExperienceOrb.java b/src/main/java/org/bukkit/entity/ExperienceOrb.java new file mode 100644 index 0000000..c286edf --- /dev/null +++ b/src/main/java/org/bukkit/entity/ExperienceOrb.java @@ -0,0 +1,21 @@ +package org.bukkit.entity; + +/** + * Represents an Experience Orb. + */ +public interface ExperienceOrb extends Entity { + + /** + * Gets how much experience is contained within this orb + * + * @return Amount of experience + */ + public int getExperience(); + + /** + * Sets how much experience is contained within this orb + * + * @param value Amount of experience + */ + public void setExperience(int value); +} diff --git a/src/main/java/org/bukkit/entity/Explosive.java b/src/main/java/org/bukkit/entity/Explosive.java new file mode 100644 index 0000000..48650f6 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Explosive.java @@ -0,0 +1,35 @@ +package org.bukkit.entity; + +/** + * A representation of an explosive entity + */ +public interface Explosive extends Entity { + + /** + * Set the radius affected by this explosive's explosion + * + * @param yield The explosive yield + */ + public void setYield(float yield); + + /** + * Return the radius or yield of this explosive's explosion + * + * @return the radius of blocks affected + */ + public float getYield(); + + /** + * Set whether or not this explosive's explosion causes fire + * + * @param isIncendiary Whether it should cause fire + */ + public void setIsIncendiary(boolean isIncendiary); + + /** + * Return whether or not this explosive creates a fire when exploding + * + * @return true if the explosive creates fire, false otherwise + */ + public boolean isIncendiary(); +} diff --git a/src/main/java/org/bukkit/entity/FallingBlock.java b/src/main/java/org/bukkit/entity/FallingBlock.java new file mode 100644 index 0000000..1edd6e0 --- /dev/null +++ b/src/main/java/org/bukkit/entity/FallingBlock.java @@ -0,0 +1,48 @@ +package org.bukkit.entity; + +import org.bukkit.Material; + +/** + * Represents a falling block + */ +public interface FallingBlock extends Entity { + + /** + * Get the Material of the falling block + * + * @return Material of the block + */ + Material getMaterial(); + + /** + * Get the ID of the falling block + * + * @return ID type of the block + * @deprecated Magic value + */ + @Deprecated + int getBlockId(); + + /** + * Get the data for the falling block + * + * @return data of the block + * @deprecated Magic value + */ + @Deprecated + byte getBlockData(); + + /** + * Get if the falling block will break into an item if it cannot be placed + * + * @return true if the block will break into an item when obstructed + */ + boolean getDropItem(); + + /** + * Set if the falling block will break into an item if it cannot be placed + * + * @param drop true to break into an item when obstructed + */ + void setDropItem(boolean drop); +} diff --git a/src/main/java/org/bukkit/entity/FallingSand.java b/src/main/java/org/bukkit/entity/FallingSand.java new file mode 100644 index 0000000..758d47d --- /dev/null +++ b/src/main/java/org/bukkit/entity/FallingSand.java @@ -0,0 +1,9 @@ +package org.bukkit.entity; + +/** + * Represents a falling block. + * + * @deprecated See {@link FallingBlock} + */ +@Deprecated +public interface FallingSand extends FallingBlock {} diff --git a/src/main/java/org/bukkit/entity/Fireball.java b/src/main/java/org/bukkit/entity/Fireball.java new file mode 100644 index 0000000..56ed578 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Fireball.java @@ -0,0 +1,24 @@ +package org.bukkit.entity; + +import org.bukkit.util.Vector; + +/** + * Represents a Fireball. + */ +public interface Fireball extends Projectile, Explosive { + + /** + * Fireballs fly straight and do not take setVelocity(...) well. + * + * @param direction the direction this fireball is flying toward + */ + public void setDirection(Vector direction); + + /** + * Retrieve the direction this fireball is heading toward + * + * @return the direction + */ + public Vector getDirection(); + +} diff --git a/src/main/java/org/bukkit/entity/Firework.java b/src/main/java/org/bukkit/entity/Firework.java new file mode 100644 index 0000000..b8a8c07 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Firework.java @@ -0,0 +1,26 @@ +package org.bukkit.entity; + +import org.bukkit.inventory.meta.FireworkMeta; + +public interface Firework extends Entity { + + /** + * Get a copy of the fireworks meta + * + * @return A copy of the current Firework meta + */ + FireworkMeta getFireworkMeta(); + + /** + * Apply the provided meta to the fireworks + * + * @param meta The FireworkMeta to apply + */ + void setFireworkMeta(FireworkMeta meta); + + /** + * Cause this firework to explode at earliest opportunity, as if it has no + * remaining fuse. + */ + void detonate(); +} diff --git a/src/main/java/org/bukkit/entity/Fish.java b/src/main/java/org/bukkit/entity/Fish.java new file mode 100644 index 0000000..9ecc4a3 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Fish.java @@ -0,0 +1,29 @@ +package org.bukkit.entity; + +/** + * Represents a fishing hook. + */ +public interface Fish extends Projectile { + + /** + * Gets the chance of a fish biting. + *

          + * 0.0 = No Chance.
          + * 1.0 = Instant catch. + * + * @return chance the bite chance + */ + public double getBiteChance(); + + /** + * Sets the chance of a fish biting. + *

          + * 0.0 = No Chance.
          + * 1.0 = Instant catch. + * + * @param chance the bite chance + * @throws IllegalArgumentException if the bite chance is not between 0 + * and 1 + */ + public void setBiteChance(double chance) throws IllegalArgumentException; +} diff --git a/src/main/java/org/bukkit/entity/Flying.java b/src/main/java/org/bukkit/entity/Flying.java new file mode 100644 index 0000000..4f16a26 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Flying.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Flying Entity. + */ +public interface Flying extends LivingEntity {} diff --git a/src/main/java/org/bukkit/entity/Ghast.java b/src/main/java/org/bukkit/entity/Ghast.java new file mode 100644 index 0000000..3f5edf7 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Ghast.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Ghast. + */ +public interface Ghast extends Flying {} diff --git a/src/main/java/org/bukkit/entity/Giant.java b/src/main/java/org/bukkit/entity/Giant.java new file mode 100644 index 0000000..610de57 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Giant.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Giant. + */ +public interface Giant extends Monster {} diff --git a/src/main/java/org/bukkit/entity/Golem.java b/src/main/java/org/bukkit/entity/Golem.java new file mode 100644 index 0000000..4165977 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Golem.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * A mechanical creature that may harm enemies. + */ +public interface Golem extends Creature { + +} diff --git a/src/main/java/org/bukkit/entity/Hanging.java b/src/main/java/org/bukkit/entity/Hanging.java new file mode 100644 index 0000000..67e9b61 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Hanging.java @@ -0,0 +1,22 @@ +package org.bukkit.entity; + +import org.bukkit.block.BlockFace; +import org.bukkit.material.Attachable; + +/** + * Represents a Hanging entity + */ +public interface Hanging extends Entity, Attachable { + + /** + * Sets the direction of the hanging entity, potentially overriding rules + * of placement. Note that if the result is not valid the object would + * normally drop as an item. + * + * @param face The new direction. + * @param force Whether to force it. + * @return False if force was false and there was no block for it to + * attach to in order to face the given direction. + */ + public boolean setFacingDirection(BlockFace face, boolean force); +} diff --git a/src/main/java/org/bukkit/entity/Horse.java b/src/main/java/org/bukkit/entity/Horse.java new file mode 100644 index 0000000..e90d318 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Horse.java @@ -0,0 +1,256 @@ +package org.bukkit.entity; + +import org.bukkit.inventory.HorseInventory; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a Horse. + */ +public interface Horse extends Animals, Vehicle, InventoryHolder, Tameable { + + /** + * Represents the different types of horses that may exist. + */ + public enum Variant { + /** + * A normal horse + */ + HORSE, + /** + * A donkey + */ + DONKEY, + /** + * A mule + */ + MULE, + /** + * An undead horse + */ + UNDEAD_HORSE, + /** + * A skeleton horse + */ + SKELETON_HORSE, + ; + } + + /** + * Represents the base color that the horse has. + */ + public enum Color { + /** + * Snow white + */ + WHITE, + /** + * Very light brown + */ + CREAMY, + /** + * Chestnut + */ + CHESTNUT, + /** + * Light brown + */ + BROWN, + /** + * Pitch black + */ + BLACK, + /** + * Gray + */ + GRAY, + /** + * Dark brown + */ + DARK_BROWN, + ; + } + + /** + * Represents the style, or markings, that the horse has. + */ + public enum Style { + /** + * No markings + */ + NONE, + /** + * White socks or stripes + */ + WHITE, + /** + * Milky splotches + */ + WHITEFIELD, + /** + * Round white dots + */ + WHITE_DOTS, + /** + * Small black dots + */ + BLACK_DOTS, + ; + } + + /** + * Gets the horse's variant. + *

          + * A horse's variant defines its physical appearance and capabilities. + * Whether a horse is a regular horse, donkey, mule, or other kind of + * horse is determined using the variant. + * + * @return a {@link Variant} representing the horse's variant + */ + public Variant getVariant(); + + /** + * Sets the horse's variant. + *

          + * A horse's variant defines its physical appearance and capabilities. + * Whether a horse is a regular horse, donkey, mule, or other kind of + * horse can be set using the variant. + *

          + * Setting a horse's variant does not change its attributes such as + * its owner and its tamed status, but changing a mule or donkey + * with a chest to another variant which does not support a chest + * will remove the chest and its contents. + * + * @param variant a {@link Variant} for this horse + */ + public void setVariant(Variant variant); + + /** + * Gets the horse's color. + *

          + * Colors only apply to horses, not to donkeys, mules, skeleton horses + * or undead horses. + * + * @return a {@link Color} representing the horse's group + */ + public Color getColor(); + + /** + * Sets the horse's color. + *

          + * Attempting to set a color for any donkey, mule, skeleton horse or + * undead horse will not result in a change. + * + * @param color a {@link Color} for this horse + */ + public void setColor(Color color); + + /** + * Gets the horse's style. + * Styles determine what kind of markings or patterns a horse has. + *

          + * Styles only apply to horses, not to donkeys, mules, skeleton horses + * or undead horses. + * + * @return a {@link Style} representing the horse's style + */ + public Style getStyle(); + + /** + * Sets the style of this horse. + * Styles determine what kind of markings or patterns a horse has. + *

          + * Attempting to set a style for any donkey, mule, skeleton horse or + * undead horse will not result in a change. + * + * @param style a {@link Style} for this horse + */ + public void setStyle(Style style); + + /** + * Gets whether the horse has a chest equipped. + * + * @return true if the horse has chest storage + */ + public boolean isCarryingChest(); + + /** + * Sets whether the horse has a chest equipped. + * Removing a chest will also clear the chest's inventory. + * + * @param chest true if the horse should have a chest + */ + public void setCarryingChest(boolean chest); + + /** + * Gets the domestication level of this horse. + *

          + * A higher domestication level indicates that the horse is closer to + * becoming tame. As the domestication level gets closer to the max + * domestication level, the chance of the horse becoming tame increases. + * + * @return domestication level + */ + public int getDomestication(); + + /** + * Sets the domestication level of this horse. + *

          + * Setting the domestication level to a high value will increase the + * horse's chances of becoming tame. + *

          + * Domestication level must be greater than zero and no greater than + * the max domestication level of the horse, determined with + * {@link #getMaxDomestication()} + * + * @param level domestication level + */ + public void setDomestication(int level); + + /** + * Gets the maximum domestication level of this horse. + *

          + * The higher this level is, the longer it will likely take + * for the horse to be tamed. + * + * @return the max domestication level + */ + public int getMaxDomestication(); + + /** + * Sets the maximum domestication level of this horse. + *

          + * Setting a higher max domestication will increase the amount of + * domesticating (feeding, riding, etc.) necessary in order to tame it, + * while setting a lower max value will have the opposite effect. + *

          + * Maximum domestication must be greater than zero. + * + * @param level the max domestication level + */ + public void setMaxDomestication(int level); + + /** + * Gets the jump strength of this horse. + *

          + * Jump strength defines how high the horse can jump. A higher jump strength + * increases how high a jump will go. + * + * @return the horse's jump strength + */ + public double getJumpStrength(); + + /** + * Sets the jump strength of this horse. + *

          + * A higher jump strength increases how high a jump will go. + * Setting a jump strength to 0 will result in no jump. + * You cannot set a jump strength to a value below 0 or + * above 2. + * + * @param strength jump strength for this horse + */ + public void setJumpStrength(double strength); + + @Override + public HorseInventory getInventory(); +} diff --git a/src/main/java/org/bukkit/entity/HumanEntity.java b/src/main/java/org/bukkit/entity/HumanEntity.java new file mode 100644 index 0000000..6f70db4 --- /dev/null +++ b/src/main/java/org/bukkit/entity/HumanEntity.java @@ -0,0 +1,177 @@ +package org.bukkit.entity; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.permissions.Permissible; + +/** + * Represents a human entity, such as an NPC or a player + */ +public interface HumanEntity extends LivingEntity, AnimalTamer, Permissible, InventoryHolder { + + /** + * Returns the name of this player + * + * @return Player name + */ + public String getName(); + + /** + * Get the player's inventory. + * + * @return The inventory of the player, this also contains the armor + * slots. + */ + public PlayerInventory getInventory(); + + /** + * Get the player's EnderChest inventory + * + * @return The EnderChest of the player + */ + public Inventory getEnderChest(); + + /** + * If the player currently has an inventory window open, this method will + * set a property of that window, such as the state of a progress bar. + * + * @param prop The property. + * @param value The value to set the property to. + * @return True if the property was successfully set. + */ + public boolean setWindowProperty(InventoryView.Property prop, int value); + + /** + * Gets the inventory view the player is currently viewing. If they do not + * have an inventory window open, it returns their internal crafting view. + * + * @return The inventory view. + */ + public InventoryView getOpenInventory(); + + /** + * Opens an inventory window with the specified inventory on the top and + * the player's inventory on the bottom. + * + * @param inventory The inventory to open + * @return The newly opened inventory view + */ + public InventoryView openInventory(Inventory inventory); + + /** + * Opens an empty workbench inventory window with the player's inventory + * on the bottom. + * + * @param location The location to attach it to. If null, the player's + * location is used. + * @param force If false, and there is no workbench block at the location, + * no inventory will be opened and null will be returned. + * @return The newly opened inventory view, or null if it could not be + * opened. + */ + public InventoryView openWorkbench(Location location, boolean force); + + /** + * Opens an empty enchanting inventory window with the player's inventory + * on the bottom. + * + * @param location The location to attach it to. If null, the player's + * location is used. + * @param force If false, and there is no enchanting table at the + * location, no inventory will be opened and null will be returned. + * @return The newly opened inventory view, or null if it could not be + * opened. + */ + public InventoryView openEnchanting(Location location, boolean force); + + /** + * Opens an inventory window to the specified inventory view. + * + * @param inventory The view to open + */ + public void openInventory(InventoryView inventory); + + /** + * Force-closes the currently open inventory view for this player, if any. + */ + public void closeInventory(); + + /** + * Returns the ItemStack currently in your hand, can be empty. + * + * @return The ItemStack of the item you are currently holding. + */ + public ItemStack getItemInHand(); + + /** + * Sets the item to the given ItemStack, this will replace whatever the + * user was holding. + * + * @param item The ItemStack which will end up in the hand + */ + public void setItemInHand(ItemStack item); + + /** + * Returns the ItemStack currently on your cursor, can be empty. Will + * always be empty if the player currently has no open window. + * + * @return The ItemStack of the item you are currently moving around. + */ + public ItemStack getItemOnCursor(); + + /** + * Sets the item to the given ItemStack, this will replace whatever the + * user was moving. Will always be empty if the player currently has no + * open window. + * + * @param item The ItemStack which will end up in the hand + */ + public void setItemOnCursor(ItemStack item); + + /** + * Returns whether this player is slumbering. + * + * @return slumber state + */ + public boolean isSleeping(); + + /** + * Get the sleep ticks of the player. This value may be capped. + * + * @return slumber ticks + */ + public int getSleepTicks(); + + /** + * Gets this humans current {@link GameMode} + * + * @return Current game mode + */ + public GameMode getGameMode(); + + /** + * Sets this humans current {@link GameMode} + * + * @param mode New game mode + */ + public void setGameMode(GameMode mode); + + /** + * Check if the player is currently blocking (ie with a sword). + * + * @return Whether they are blocking. + */ + public boolean isBlocking(); + + /** + * Get the total amount of experience required for the player to level + * + * @return Experience required to level up + */ + public int getExpToLevel(); +} diff --git a/src/main/java/org/bukkit/entity/IronGolem.java b/src/main/java/org/bukkit/entity/IronGolem.java new file mode 100644 index 0000000..655e37c --- /dev/null +++ b/src/main/java/org/bukkit/entity/IronGolem.java @@ -0,0 +1,22 @@ +package org.bukkit.entity; + +/** + * An iron Golem that protects Villages. + */ +public interface IronGolem extends Golem { + + /** + * Gets whether this iron golem was built by a player. + * + * @return Whether this iron golem was built by a player + */ + public boolean isPlayerCreated(); + + /** + * Sets whether this iron golem was built by a player or not. + * + * @param playerCreated true if you want to set the iron golem as being + * player created, false if you want it to be a natural village golem. + */ + public void setPlayerCreated(boolean playerCreated); +} diff --git a/src/main/java/org/bukkit/entity/Item.java b/src/main/java/org/bukkit/entity/Item.java new file mode 100644 index 0000000..90260b7 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Item.java @@ -0,0 +1,37 @@ +package org.bukkit.entity; + +import org.bukkit.inventory.ItemStack; + +/** + * Represents an Item. + */ +public interface Item extends Entity { + + /** + * Gets the item stack associated with this item drop. + * + * @return An item stack. + */ + public ItemStack getItemStack(); + + /** + * Sets the item stack associated with this item drop. + * + * @param stack An item stack. + */ + public void setItemStack(ItemStack stack); + + /** + * Gets the delay before this Item is available to be picked up by players + * + * @return Remaining delay + */ + public int getPickupDelay(); + + /** + * Sets the delay before this Item is available to be picked up by players + * + * @param delay New delay + */ + public void setPickupDelay(int delay); +} diff --git a/src/main/java/org/bukkit/entity/ItemFrame.java b/src/main/java/org/bukkit/entity/ItemFrame.java new file mode 100644 index 0000000..8b86815 --- /dev/null +++ b/src/main/java/org/bukkit/entity/ItemFrame.java @@ -0,0 +1,39 @@ +package org.bukkit.entity; + +import org.bukkit.Rotation; +import org.bukkit.inventory.ItemStack; + +/** + * Represents an Item Frame + */ +public interface ItemFrame extends Hanging { + + /** + * Get the item in this frame + * + * @return a defensive copy the item in this item frame + */ + public ItemStack getItem(); + + /** + * Set the item in this frame + * + * @param item the new item + */ + public void setItem(ItemStack item); + + /** + * Get the rotation of the frame's item + * + * @return the direction + */ + public Rotation getRotation(); + + /** + * Set the rotation of the frame's item + * + * @param rotation the new rotation + * @throws IllegalArgumentException if rotation is null + */ + public void setRotation(Rotation rotation) throws IllegalArgumentException; +} diff --git a/src/main/java/org/bukkit/entity/LargeFireball.java b/src/main/java/org/bukkit/entity/LargeFireball.java new file mode 100644 index 0000000..fc3a109 --- /dev/null +++ b/src/main/java/org/bukkit/entity/LargeFireball.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a large {@link Fireball} + */ +public interface LargeFireball extends Fireball { +} diff --git a/src/main/java/org/bukkit/entity/LeashHitch.java b/src/main/java/org/bukkit/entity/LeashHitch.java new file mode 100644 index 0000000..9ac04c1 --- /dev/null +++ b/src/main/java/org/bukkit/entity/LeashHitch.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a Leash Hitch on a fence + */ +public interface LeashHitch extends Hanging { +} diff --git a/src/main/java/org/bukkit/entity/LightningStrike.java b/src/main/java/org/bukkit/entity/LightningStrike.java new file mode 100644 index 0000000..c8b5154 --- /dev/null +++ b/src/main/java/org/bukkit/entity/LightningStrike.java @@ -0,0 +1,15 @@ +package org.bukkit.entity; + +/** + * Represents an instance of a lightning strike. May or may not do damage. + */ +public interface LightningStrike extends Weather { + + /** + * Returns whether the strike is an effect that does no damage. + * + * @return whether the strike is an effect + */ + public boolean isEffect(); + +} diff --git a/src/main/java/org/bukkit/entity/LivingEntity.java b/src/main/java/org/bukkit/entity/LivingEntity.java new file mode 100644 index 0000000..6c8b4f8 --- /dev/null +++ b/src/main/java/org/bukkit/entity/LivingEntity.java @@ -0,0 +1,394 @@ +package org.bukkit.entity; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.projectiles.ProjectileSource; + +/** + * Represents a living entity, such as a monster or player + */ +public interface LivingEntity extends Entity, Damageable, ProjectileSource { + + /** + * Gets the height of the living entity's eyes above its Location. + * + * @return height of the living entity's eyes above its location + */ + public double getEyeHeight(); + + /** + * Gets the height of the living entity's eyes above its Location. + * + * @param ignoreSneaking if set to true, the effects of sneaking will be + * ignored + * @return height of the living entity's eyes above its location + */ + public double getEyeHeight(boolean ignoreSneaking); + + /** + * Get a Location detailing the current eye position of the living entity. + * + * @return a location at the eyes of the living entity + */ + public Location getEyeLocation(); + + /** + * Gets all blocks along the living entity's line of sight. + *

          + * This list contains all blocks from the living entity's eye position to + * target inclusive. + * + * @param transparent HashSet containing all transparent block IDs (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan (may be limited + * by server by at least 100 blocks, no less) + * @return list containing all blocks along the living entity's line of + * sight + * @deprecated Magic value + */ + @Deprecated + public List getLineOfSight(HashSet transparent, int maxDistance); + + /** + * Gets the block that the living entity has targeted. + * + * @param transparent HashSet containing all transparent block IDs (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan (may be limited + * by server by at least 100 blocks, no less) + * @return block that the living entity has targeted + * @deprecated Magic value + */ + @Deprecated + public Block getTargetBlock(HashSet transparent, int maxDistance); + + /** + * Gets the last two blocks along the living entity's line of sight. + *

          + * The target block will be the last block in the list. + * + * @param transparent HashSet containing all transparent block IDs (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan. This may be + * further limited by the server, but never to less than 100 blocks + * @return list containing the last 2 blocks along the living entity's + * line of sight + * @deprecated Magic value + */ + @Deprecated + public List getLastTwoTargetBlocks(HashSet transparent, int maxDistance); + + /** + * Throws an egg from the living entity. + * + * @deprecated use launchProjectile(Egg.class) instead + * @return the egg thrown + */ + @Deprecated + public Egg throwEgg(); + + /** + * Throws a snowball from the living entity. + * + * @deprecated use launchProjectile(Snowball.class) instead + * @return the snowball thrown + */ + @Deprecated + public Snowball throwSnowball(); + + /** + * Shoots an arrow from the living entity. + * + * @deprecated use launchProjectile(Arrow.class) instead + * @return the arrow shot + */ + @Deprecated + public Arrow shootArrow(); + + /** + * Returns the amount of air that the living entity has remaining, in + * ticks. + * + * @return amount of air remaining + */ + public int getRemainingAir(); + + /** + * Sets the amount of air that the living entity has remaining, in ticks. + * + * @param ticks amount of air remaining + */ + public void setRemainingAir(int ticks); + + /** + * Returns the maximum amount of air the living entity can have, in ticks. + * + * @return maximum amount of air + */ + public int getMaximumAir(); + + /** + * Sets the maximum amount of air the living entity can have, in ticks. + * + * @param ticks maximum amount of air + */ + public void setMaximumAir(int ticks); + + /** + * Returns the living entity's current maximum no damage ticks. + *

          + * This is the maximum duration in which the living entity will not take + * damage. + * + * @return maximum no damage ticks + */ + public int getMaximumNoDamageTicks(); + + /** + * Sets the living entity's current maximum no damage ticks. + * + * @param ticks maximum amount of no damage ticks + */ + public void setMaximumNoDamageTicks(int ticks); + + /** + * Returns the living entity's last damage taken in the current no damage + * ticks time. + *

          + * Only damage higher than this amount will further damage the living + * entity. + * + * @return damage taken since the last no damage ticks time period + */ + public double getLastDamage(); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public int _INVALID_getLastDamage(); + + /** + * Sets the damage dealt within the current no damage ticks time period. + * + * @param damage amount of damage + */ + public void setLastDamage(double damage); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public void _INVALID_setLastDamage(int damage); + + /** + * Returns the living entity's current no damage ticks. + * + * @return amount of no damage ticks + */ + public int getNoDamageTicks(); + + /** + * Sets the living entity's current no damage ticks. + * + * @param ticks amount of no damage ticks + */ + public void setNoDamageTicks(int ticks); + + /** + * Gets the player identified as the killer of the living entity. + *

          + * May be null. + * + * @return killer player, or null if none found + */ + public Player getKiller(); + + /** + * Adds the given {@link PotionEffect} to the living entity. + *

          + * Only one potion effect can be present for a given {@link + * PotionEffectType}. + * + * @param effect PotionEffect to be added + * @return whether the effect could be added + */ + public boolean addPotionEffect(PotionEffect effect); + + /** + * Adds the given {@link PotionEffect} to the living entity. + *

          + * Only one potion effect can be present for a given {@link + * PotionEffectType}. + * + * @param effect PotionEffect to be added + * @param force whether conflicting effects should be removed + * @return whether the effect could be added + */ + public boolean addPotionEffect(PotionEffect effect, boolean force); + + /** + * Attempts to add all of the given {@link PotionEffect} to the living + * entity. + * + * @param effects the effects to add + * @return whether all of the effects could be added + */ + public boolean addPotionEffects(Collection effects); + + /** + * Returns whether the living entity already has an existing effect of + * the given {@link PotionEffectType} applied to it. + * + * @param type the potion type to check + * @return whether the living entity has this potion effect active on them + */ + public boolean hasPotionEffect(PotionEffectType type); + + /** + * Removes any effects present of the given {@link PotionEffectType}. + * + * @param type the potion type to remove + */ + public void removePotionEffect(PotionEffectType type); + + /** + * Returns all currently active {@link PotionEffect}s on the living + * entity. + * + * @return a collection of {@link PotionEffect}s + */ + public Collection getActivePotionEffects(); + + /** + * Checks whether the living entity has block line of sight to another. + *

          + * This uses the same algorithm that hostile mobs use to find the closest + * player. + * + * @param other the entity to determine line of sight to + * @return true if there is a line of sight, false if not + */ + public boolean hasLineOfSight(Entity other); + + /** + * Returns if the living entity despawns when away from players or not. + *

          + * By default, animals are not removed while other mobs are. + * + * @return true if the living entity is removed when away from players + */ + public boolean getRemoveWhenFarAway(); + + /** + * Sets whether or not the living entity despawns when away from players + * or not. + * + * @param remove the removal status + */ + public void setRemoveWhenFarAway(boolean remove); + + /** + * Gets the inventory with the equipment worn by the living entity. + * + * @return the living entity's inventory + */ + public EntityEquipment getEquipment(); + + /** + * Sets whether or not the living entity can pick up items. + * + * @param pickup whether or not the living entity can pick up items + */ + public void setCanPickupItems(boolean pickup); + + /** + * Gets if the living entity can pick up items. + * + * @return whether or not the living entity can pick up items + */ + public boolean getCanPickupItems(); + + /** + * Sets a custom name on a mob. This name will be used in death messages + * and can be sent to the client as a nameplate over the mob. + *

          + * Setting the name to null or an empty string will clear it. + *

          + * This value has no effect on players, they will always use their real + * name. + * + * @param name the name to set + */ + public void setCustomName(String name); + + /** + * Gets the custom name on a mob. If there is no name this method will + * return null. + *

          + * This value has no effect on players, they will always use their real + * name. + * + * @return name of the mob or null + */ + public String getCustomName(); + + /** + * Sets whether or not to display the mob's custom name client side. The + * name will be displayed above the mob similarly to a player. + *

          + * This value has no effect on players, they will always display their + * name. + * + * @param flag custom name or not + */ + public void setCustomNameVisible(boolean flag); + + /** + * Gets whether or not the mob's custom name is displayed client side. + *

          + * This value has no effect on players, they will always display their + * name. + * + * @return if the custom name is displayed + */ + public boolean isCustomNameVisible(); + + /** + * Returns whether the entity is currently leashed. + * + * @return whether the entity is leashed + */ + public boolean isLeashed(); + + /** + * Gets the entity that is currently leading this entity. + * + * @return the entity holding the leash + * @throws IllegalStateException if not currently leashed + */ + public Entity getLeashHolder() throws IllegalStateException; + + /** + * Sets the leash on this entity to be held by the supplied entity. + *

          + * This method has no effect on EnderDragons, Withers, Players, or Bats. + * Non-living entities excluding leashes will not persist as leash + * holders. + * + * @param holder the entity to leash this entity to + * @return whether the operation was successful + */ + public boolean setLeashHolder(Entity holder); +} diff --git a/src/main/java/org/bukkit/entity/MagmaCube.java b/src/main/java/org/bukkit/entity/MagmaCube.java new file mode 100644 index 0000000..714b442 --- /dev/null +++ b/src/main/java/org/bukkit/entity/MagmaCube.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a MagmaCube. + */ +public interface MagmaCube extends Slime { +} diff --git a/src/main/java/org/bukkit/entity/Minecart.java b/src/main/java/org/bukkit/entity/Minecart.java new file mode 100644 index 0000000..a7bb094 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Minecart.java @@ -0,0 +1,108 @@ +package org.bukkit.entity; + +import org.bukkit.util.Vector; + +/** + * Represents a minecart entity. + */ +public interface Minecart extends Vehicle { + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public void _INVALID_setDamage(int damage); + + /** + * Sets a minecart's damage. + * + * @param damage over 40 to "kill" a minecart + */ + public void setDamage(double damage); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public int _INVALID_getDamage(); + + /** + * Gets a minecart's damage. + * + * @return The damage + */ + public double getDamage(); + + /** + * Gets the maximum speed of a minecart. The speed is unrelated to the + * velocity. + * + * @return The max speed + */ + public double getMaxSpeed(); + + /** + * Sets the maximum speed of a minecart. Must be nonnegative. Default is + * 0.4D. + * + * @param speed The max speed + */ + public void setMaxSpeed(double speed); + + /** + * Returns whether this minecart will slow down faster without a passenger + * occupying it + * + * @return Whether it decelerates faster + */ + public boolean isSlowWhenEmpty(); + + /** + * Sets whether this minecart will slow down faster without a passenger + * occupying it + * + * @param slow Whether it will decelerate faster + */ + public void setSlowWhenEmpty(boolean slow); + + /** + * Gets the flying velocity modifier. Used for minecarts that are in + * mid-air. A flying minecart's velocity is multiplied by this factor each + * tick. + * + * @return The vector factor + */ + public Vector getFlyingVelocityMod(); + + /** + * Sets the flying velocity modifier. Used for minecarts that are in + * mid-air. A flying minecart's velocity is multiplied by this factor each + * tick. + * + * @param flying velocity modifier vector + */ + public void setFlyingVelocityMod(Vector flying); + + /** + * Gets the derailed velocity modifier. Used for minecarts that are on the + * ground, but not on rails. + *

          + * A derailed minecart's velocity is multiplied by this factor each tick. + * + * @return derailed visible speed + */ + public Vector getDerailedVelocityMod(); + + /** + * Sets the derailed velocity modifier. Used for minecarts that are on the + * ground, but not on rails. A derailed minecart's velocity is multiplied + * by this factor each tick. + * + * @param derailed visible speed + */ + public void setDerailedVelocityMod(Vector derailed); +} diff --git a/src/main/java/org/bukkit/entity/Monster.java b/src/main/java/org/bukkit/entity/Monster.java new file mode 100644 index 0000000..fce2efd --- /dev/null +++ b/src/main/java/org/bukkit/entity/Monster.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Monster. + */ +public interface Monster extends Creature {} diff --git a/src/main/java/org/bukkit/entity/MushroomCow.java b/src/main/java/org/bukkit/entity/MushroomCow.java new file mode 100644 index 0000000..84154de --- /dev/null +++ b/src/main/java/org/bukkit/entity/MushroomCow.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a mushroom {@link Cow} + */ +public interface MushroomCow extends Cow { + +} diff --git a/src/main/java/org/bukkit/entity/NPC.java b/src/main/java/org/bukkit/entity/NPC.java new file mode 100644 index 0000000..0c6b175 --- /dev/null +++ b/src/main/java/org/bukkit/entity/NPC.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a non-player character + */ +public interface NPC extends Creature { + +} diff --git a/src/main/java/org/bukkit/entity/Ocelot.java b/src/main/java/org/bukkit/entity/Ocelot.java new file mode 100644 index 0000000..d5d034d --- /dev/null +++ b/src/main/java/org/bukkit/entity/Ocelot.java @@ -0,0 +1,83 @@ + +package org.bukkit.entity; + +/** + * A wild tameable cat + */ +public interface Ocelot extends Animals, Tameable { + + /** + * Gets the current type of this cat. + * + * @return Type of the cat. + */ + public Type getCatType(); + + /** + * Sets the current type of this cat. + * + * @param type New type of this cat. + */ + public void setCatType(Type type); + + /** + * Checks if this ocelot is sitting + * + * @return true if sitting + */ + public boolean isSitting(); + + /** + * Sets if this ocelot is sitting. Will remove any path that the ocelot + * was following beforehand. + * + * @param sitting true if sitting + */ + public void setSitting(boolean sitting); + + /** + * Represents the various different cat types there are. + */ + public enum Type { + WILD_OCELOT(0), + BLACK_CAT(1), + RED_CAT(2), + SIAMESE_CAT(3); + + private static final Type[] types = new Type[Type.values().length]; + private final int id; + + static { + for (Type type : values()) { + types[type.getId()] = type; + } + } + + private Type(int id) { + this.id = id; + } + + /** + * Gets the ID of this cat type. + * + * @return Type ID. + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets a cat type by its ID. + * + * @param id ID of the cat type to get. + * @return Resulting type, or null if not found. + * @deprecated Magic value + */ + @Deprecated + public static Type getType(int id) { + return (id >= types.length) ? null : types[id]; + } + } +} diff --git a/src/main/java/org/bukkit/entity/Painting.java b/src/main/java/org/bukkit/entity/Painting.java new file mode 100644 index 0000000..ca7a4cf --- /dev/null +++ b/src/main/java/org/bukkit/entity/Painting.java @@ -0,0 +1,39 @@ +package org.bukkit.entity; + +import org.bukkit.Art; +import org.bukkit.event.painting.PaintingBreakEvent; + +/** + * Represents a Painting. + */ +public interface Painting extends Hanging { + + /** + * Get the art on this painting + * + * @return The art + */ + public Art getArt(); + + /** + * Set the art on this painting + * + * @param art The new art + * @return False if the new art won't fit at the painting's current + * location + */ + public boolean setArt(Art art); + + /** + * Set the art on this painting + * + * @param art The new art + * @param force If true, force the new art regardless of whether it fits + * at the current location. Note that forcing it where it can't fit + * normally causes it to drop as an item unless you override this by + * catching the {@link PaintingBreakEvent}. + * @return False if force was false and the new art won't fit at the + * painting's current location + */ + public boolean setArt(Art art, boolean force); +} diff --git a/src/main/java/org/bukkit/entity/Pig.java b/src/main/java/org/bukkit/entity/Pig.java new file mode 100644 index 0000000..28f59f2 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Pig.java @@ -0,0 +1,21 @@ +package org.bukkit.entity; + +/** + * Represents a Pig. + */ +public interface Pig extends Animals, Vehicle { + + /** + * Check if the pig has a saddle. + * + * @return if the pig has been saddled. + */ + public boolean hasSaddle(); + + /** + * Sets if the pig has a saddle or not + * + * @param saddled set if the pig has a saddle or not. + */ + public void setSaddle(boolean saddled); +} diff --git a/src/main/java/org/bukkit/entity/PigZombie.java b/src/main/java/org/bukkit/entity/PigZombie.java new file mode 100644 index 0000000..2f08672 --- /dev/null +++ b/src/main/java/org/bukkit/entity/PigZombie.java @@ -0,0 +1,36 @@ +package org.bukkit.entity; + +/** + * Represents a Pig Zombie. + */ +public interface PigZombie extends Zombie { + + /** + * Get the pig zombie's current anger level. + * + * @return The anger level. + */ + int getAnger(); + + /** + * Set the pig zombie's current anger level. + * + * @param level The anger level. Higher levels of anger take longer to + * wear off. + */ + void setAnger(int level); + + /** + * Shorthand; sets to either 0 or the default level. + * + * @param angry Whether the zombie should be angry. + */ + void setAngry(boolean angry); + + /** + * Shorthand; gets whether the zombie is angry. + * + * @return True if the zombie is angry, otherwise false. + */ + boolean isAngry(); +} diff --git a/src/main/java/org/bukkit/entity/Player.java b/src/main/java/org/bukkit/entity/Player.java new file mode 100644 index 0000000..fe8a0bd --- /dev/null +++ b/src/main/java/org/bukkit/entity/Player.java @@ -0,0 +1,1038 @@ +package org.bukkit.entity; + +import java.net.InetSocketAddress; + +import org.bukkit.Achievement; +import org.bukkit.ChatColor; +import org.bukkit.Effect; +import org.bukkit.Instrument; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Note; +import org.bukkit.OfflinePlayer; +import org.bukkit.Sound; +import org.bukkit.Statistic; +import org.bukkit.WeatherType; +import org.bukkit.command.CommandSender; +import org.bukkit.conversations.Conversable; +import org.bukkit.map.MapView; +import org.bukkit.plugin.messaging.PluginMessageRecipient; +import org.bukkit.scoreboard.Scoreboard; + +/** + * Represents a player, connected or not + */ +public interface Player extends HumanEntity, Conversable, CommandSender, OfflinePlayer, PluginMessageRecipient { + + /** + * Gets the "friendly" name to display of this player. This may include + * color. + *

          + * Note that this name will not be displayed in game, only in chat and + * places defined by plugins. + * + * @return the friendly name + */ + public String getDisplayName(); + + /** + * Sets the "friendly" name to display of this player. This may include + * color. + *

          + * Note that this name will not be displayed in game, only in chat and + * places defined by plugins. + * + * @param name The new display name. + */ + public void setDisplayName(String name); + + /** + * Gets the name that is shown on the player list. + * + * @return the player list name + */ + public String getPlayerListName(); + + /** + * Sets the name that is shown on the in-game player list. + *

          + * The name cannot be longer than 16 characters, but {@link ChatColor} is + * supported. + *

          + * If the value is null, the name will be identical to {@link #getName()}. + *

          + * This name is case sensitive and unique, two names with different casing + * will appear as two different people. If a player joins afterwards with + * a name that conflicts with a player's custom list name, the joining + * player's player list name will have a random number appended to it (1-2 + * characters long in the default implementation). If the joining player's + * name is 15 or 16 characters long, part of the name will be truncated at + * the end to allow the addition of the two digits. + * + * @param name new player list name + * @throws IllegalArgumentException if the name is already used by someone + * else + * @throws IllegalArgumentException if the length of the name is too long + */ + public void setPlayerListName(String name); + + /** + * Set the target of the player's compass. + * + * @param loc Location to point to + */ + public void setCompassTarget(Location loc); + + /** + * Get the previously set compass target. + * + * @return location of the target + */ + public Location getCompassTarget(); + + /** + * Gets the socket address of this player + * + * @return the player's address + */ + public InetSocketAddress getAddress(); + + /** + * Sends this sender a message raw + * + * @param message Message to be displayed + */ + public void sendRawMessage(String message); + + /** + * Kicks player with custom kick message. + * + * @param message kick message + */ + public void kickPlayer(String message); + + /** + * Says a message (or runs a command). + * + * @param msg message to print + */ + public void chat(String msg); + + /** + * Makes the player perform the given command + * + * @param command Command to perform + * @return true if the command was successful, otherwise false + */ + public boolean performCommand(String command); + + /** + * Returns if the player is in sneak mode + * + * @return true if player is in sneak mode + */ + public boolean isSneaking(); + + /** + * Sets the sneak mode the player + * + * @param sneak true if player should appear sneaking + */ + public void setSneaking(boolean sneak); + + /** + * Gets whether the player is sprinting or not. + * + * @return true if player is sprinting. + */ + public boolean isSprinting(); + + /** + * Sets whether the player is sprinting or not. + * + * @param sprinting true if the player should be sprinting + */ + public void setSprinting(boolean sprinting); + + /** + * Saves the players current location, health, inventory, motion, and + * other information into the username.dat file, in the world/player + * folder + */ + public void saveData(); + + /** + * Loads the players current location, health, inventory, motion, and + * other information from the username.dat file, in the world/player + * folder. + *

          + * Note: This will overwrite the players current inventory, health, + * motion, etc, with the state from the saved dat file. + */ + public void loadData(); + + /** + * Sets whether the player is ignored as not sleeping. If everyone is + * either sleeping or has this flag set, then time will advance to the + * next day. If everyone has this flag set but no one is actually in bed, + * then nothing will happen. + * + * @param isSleeping Whether to ignore. + */ + public void setSleepingIgnored(boolean isSleeping); + + /** + * Returns whether the player is sleeping ignored. + * + * @return Whether player is ignoring sleep. + */ + public boolean isSleepingIgnored(); + + /** + * Play a note for a player at a location. This requires a note block + * at the particular location (as far as the client is concerned). This + * will not work without a note block. This will not work with cake. + * + * @param loc The location of a note block. + * @param instrument The instrument ID. + * @param note The note ID. + * @deprecated Magic value + */ + @Deprecated + public void playNote(Location loc, byte instrument, byte note); + + /** + * Play a note for a player at a location. This requires a note block + * at the particular location (as far as the client is concerned). This + * will not work without a note block. This will not work with cake. + * + * @param loc The location of a note block + * @param instrument The instrument + * @param note The note + */ + public void playNote(Location loc, Instrument instrument, Note note); + + + /** + * Play a sound for a player at the location. + *

          + * This function will fail silently if Location or Sound are null. + * + * @param location The location to play the sound + * @param sound The sound to play + * @param volume The volume of the sound + * @param pitch The pitch of the sound + */ + public void playSound(Location location, Sound sound, float volume, float pitch); + + /** + * Play a sound for a player at the location. + *

          + * This function will fail silently if Location or Sound are null. No + * sound will be heard by the player if their client does not have the + * respective sound for the value passed. + * + * @param location the location to play the sound + * @param sound the internal sound name to play + * @param volume the volume of the sound + * @param pitch the pitch of the sound + * @deprecated Magic value + */ + @Deprecated + public void playSound(Location location, String sound, float volume, float pitch); + + /** + * Plays an effect to just this player. + * + * @param loc the location to play the effect at + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + * @deprecated Magic value + */ + @Deprecated + public void playEffect(Location loc, Effect effect, int data); + + /** + * Plays an effect to just this player. + * + * @param loc the location to play the effect at + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + */ + public void playEffect(Location loc, Effect effect, T data); + + /** + * Send a block change. This fakes a block change packet for a user at a + * certain location. This will not actually change the world in any way. + * + * @param loc The location of the changed block + * @param material The new block + * @param data The block data + * @deprecated Magic value + */ + @Deprecated + public void sendBlockChange(Location loc, Material material, byte data); + + /** + * Send a chunk change. This fakes a chunk change packet for a user at a + * certain location. The updated cuboid must be entirely within a single + * chunk. This will not actually change the world in any way. + *

          + * At least one of the dimensions of the cuboid must be even. The size of + * the data buffer must be 2.5*sx*sy*sz and formatted in accordance with + * the Packet51 format. + * + * @param loc The location of the cuboid + * @param sx The x size of the cuboid + * @param sy The y size of the cuboid + * @param sz The z size of the cuboid + * @param data The data to be sent + * @return true if the chunk change packet was sent + * @deprecated Magic value + */ + @Deprecated + public boolean sendChunkChange(Location loc, int sx, int sy, int sz, byte[] data); + + /** + * Send a block change. This fakes a block change packet for a user at a + * certain location. This will not actually change the world in any way. + * + * @param loc The location of the changed block + * @param material The new block ID + * @param data The block data + * @deprecated Magic value + */ + @Deprecated + public void sendBlockChange(Location loc, int material, byte data); + + /** + * Send a sign change. This fakes a sign change packet for a user at + * a certain location. This will not actually change the world in any way. + * This method will use a sign at the location's block or a faked sign + * sent via {@link #sendBlockChange(org.bukkit.Location, int, byte)} or + * {@link #sendBlockChange(org.bukkit.Location, org.bukkit.Material, byte)}. + *

          + * If the client does not have a sign at the given location it will + * display an error message to the user. + * + * @param loc the location of the sign + * @param lines the new text on the sign or null to clear it + * @throws IllegalArgumentException if location is null + * @throws IllegalArgumentException if lines is non-null and has a length less than 4 + */ + public void sendSignChange(Location loc, String[] lines) throws IllegalArgumentException; + + /** + * Render a map and send it to the player in its entirety. This may be + * used when streaming the map in the normal manner is not desirable. + * + * @param map The map to be sent + */ + public void sendMap(MapView map); + + /** + * Forces an update of the player's entire inventory. + * + * @deprecated This method should not be relied upon as it is a temporary + * work-around for a larger, more complicated issue. + */ + @Deprecated + public void updateInventory(); + + /** + * Awards the given achievement and any parent achievements that the + * player does not have. + * + * @param achievement Achievement to award + * @throws IllegalArgumentException if achievement is null + */ + public void awardAchievement(Achievement achievement); + + /** + * Removes the given achievement and any children achievements that the + * player has. + * + * @param achievement Achievement to remove + * @throws IllegalArgumentException if achievement is null + */ + public void removeAchievement(Achievement achievement); + + /** + * Gets whether this player has the given achievement. + * + * @return whether the player has the achievement + * @throws IllegalArgumentException if achievement is null + */ + public boolean hasAchievement(Achievement achievement); + + /** + * Increments the given statistic for this player. + *

          + * This is equivalent to the following code: + * incrementStatistic(Statistic, 1) + * + * @param statistic Statistic to increment + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + public void incrementStatistic(Statistic statistic) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player. + *

          + * This is equivalent to the following code: + * decrementStatistic(Statistic, 1) + * + * @param statistic Statistic to decrement + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + public void decrementStatistic(Statistic statistic) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player. + * + * @param statistic Statistic to increment + * @param amount Amount to increment this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + public void incrementStatistic(Statistic statistic, int amount) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player. + * + * @param statistic Statistic to decrement + * @param amount Amount to decrement this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + public void decrementStatistic(Statistic statistic, int amount) throws IllegalArgumentException; + + /** + * Sets the given statistic for this player. + * + * @param statistic Statistic to set + * @param newValue The value to set this statistic to + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if newValue is negative + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + public void setStatistic(Statistic statistic, int newValue) throws IllegalArgumentException; + + /** + * Gets the value of the given statistic for this player. + * + * @param statistic Statistic to check + * @return the value of the given statistic + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + public int getStatistic(Statistic statistic) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player for the given material. + *

          + * This is equivalent to the following code: + * incrementStatistic(Statistic, Material, 1) + * + * @param statistic Statistic to increment + * @param material Material to offset the statistic with + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void incrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player for the given material. + *

          + * This is equivalent to the following code: + * decrementStatistic(Statistic, Material, 1) + * + * @param statistic Statistic to decrement + * @param material Material to offset the statistic with + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void decrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException; + + /** + * Gets the value of the given statistic for this player. + * + * @param statistic Statistic to check + * @param material Material offset of the statistic + * @return the value of the given statistic + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public int getStatistic(Statistic statistic, Material material) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player for the given material. + * + * @param statistic Statistic to increment + * @param material Material to offset the statistic with + * @param amount Amount to increment this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void incrementStatistic(Statistic statistic, Material material, int amount) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player for the given material. + * + * @param statistic Statistic to decrement + * @param material Material to offset the statistic with + * @param amount Amount to decrement this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void decrementStatistic(Statistic statistic, Material material, int amount) throws IllegalArgumentException; + + /** + * Sets the given statistic for this player for the given material. + * + * @param statistic Statistic to set + * @param material Material to offset the statistic with + * @param newValue The value to set this statistic to + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if newValue is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void setStatistic(Statistic statistic, Material material, int newValue) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player for the given entity. + *

          + * This is equivalent to the following code: + * incrementStatistic(Statistic, EntityType, 1) + * + * @param statistic Statistic to increment + * @param entityType EntityType to offset the statistic with + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void incrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player for the given entity. + *

          + * This is equivalent to the following code: + * decrementStatistic(Statistic, EntityType, 1) + * + * @param statistic Statistic to decrement + * @param entityType EntityType to offset the statistic with + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void decrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException; + + /** + * Gets the value of the given statistic for this player. + * + * @param statistic Statistic to check + * @param entityType EntityType offset of the statistic + * @return the value of the given statistic + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public int getStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player for the given entity. + * + * @param statistic Statistic to increment + * @param entityType EntityType to offset the statistic with + * @param amount Amount to increment this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void incrementStatistic(Statistic statistic, EntityType entityType, int amount) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player for the given entity. + * + * @param statistic Statistic to decrement + * @param entityType EntityType to offset the statistic with + * @param amount Amount to decrement this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void decrementStatistic(Statistic statistic, EntityType entityType, int amount); + + /** + * Sets the given statistic for this player for the given entity. + * + * @param statistic Statistic to set + * @param entityType EntityType to offset the statistic with + * @param newValue The value to set this statistic to + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if newValue is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + public void setStatistic(Statistic statistic, EntityType entityType, int newValue); + + /** + * Sets the current time on the player's client. When relative is true the + * player's time will be kept synchronized to its world time with the + * specified offset. + *

          + * When using non relative time the player's time will stay fixed at the + * specified time parameter. It's up to the caller to continue updating + * the player's time. To restore player time to normal use + * resetPlayerTime(). + * + * @param time The current player's perceived time or the player's time + * offset from the server time. + * @param relative When true the player time is kept relative to its world + * time. + */ + public void setPlayerTime(long time, boolean relative); + + /** + * Returns the player's current timestamp. + * + * @return The player's time + */ + public long getPlayerTime(); + + /** + * Returns the player's current time offset relative to server time, or + * the current player's fixed time if the player's time is absolute. + * + * @return The player's time + */ + public long getPlayerTimeOffset(); + + /** + * Returns true if the player's time is relative to the server time, + * otherwise the player's time is absolute and will not change its current + * time unless done so with setPlayerTime(). + * + * @return true if the player's time is relative to the server time. + */ + public boolean isPlayerTimeRelative(); + + /** + * Restores the normal condition where the player's time is synchronized + * with the server time. + *

          + * Equivalent to calling setPlayerTime(0, true). + */ + public void resetPlayerTime(); + + /** + * Sets the type of weather the player will see. When used, the weather + * status of the player is locked until {@link #resetPlayerWeather()} is + * used. + * + * @param type The WeatherType enum type the player should experience + */ + public void setPlayerWeather(WeatherType type); + + /** + * Returns the type of weather the player is currently experiencing. + * + * @return The WeatherType that the player is currently experiencing or + * null if player is seeing server weather. + */ + public WeatherType getPlayerWeather(); + + /** + * Restores the normal condition where the player's weather is controlled + * by server conditions. + */ + public void resetPlayerWeather(); + + /** + * Gives the player the amount of experience specified. + * + * @param amount Exp amount to give + */ + public void giveExp(int amount); + + /** + * Gives the player the amount of experience levels specified. Levels can + * be taken by specifying a negative amount. + * + * @param amount amount of experience levels to give or take + */ + public void giveExpLevels(int amount); + + /** + * Gets the players current experience points towards the next level. + *

          + * This is a percentage value. 0 is "no progress" and 1 is "next level". + * + * @return Current experience points + */ + public float getExp(); + + /** + * Sets the players current experience points towards the next level + *

          + * This is a percentage value. 0 is "no progress" and 1 is "next level". + * + * @param exp New experience points + */ + public void setExp(float exp); + + /** + * Gets the players current experience level + * + * @return Current experience level + */ + public int getLevel(); + + /** + * Sets the players current experience level + * + * @param level New experience level + */ + public void setLevel(int level); + + /** + * Gets the players total experience points + * + * @return Current total experience points + */ + public int getTotalExperience(); + + /** + * Sets the players current experience level + * + * @param exp New experience level + */ + public void setTotalExperience(int exp); + + /** + * Gets the players current exhaustion level. + *

          + * Exhaustion controls how fast the food level drops. While you have a + * certain amount of exhaustion, your saturation will drop to zero, and + * then your food will drop to zero. + * + * @return Exhaustion level + */ + public float getExhaustion(); + + /** + * Sets the players current exhaustion level + * + * @param value Exhaustion level + */ + public void setExhaustion(float value); + + /** + * Gets the players current saturation level. + *

          + * Saturation is a buffer for food level. Your food level will not drop if + * you are saturated > 0. + * + * @return Saturation level + */ + public float getSaturation(); + + /** + * Sets the players current saturation level + * + * @param value Saturation level + */ + public void setSaturation(float value); + + /** + * Gets the players current food level + * + * @return Food level + */ + public int getFoodLevel(); + + /** + * Sets the players current food level + * + * @param value New food level + */ + public void setFoodLevel(int value); + + /** + * Gets the Location where the player will spawn at their bed, null if + * they have not slept in one or their current bed spawn is invalid. + * + * @return Bed Spawn Location if bed exists, otherwise null. + */ + public Location getBedSpawnLocation(); + + /** + * Sets the Location where the player will spawn at their bed. + * + * @param location where to set the respawn location + */ + public void setBedSpawnLocation(Location location); + + /** + * Sets the Location where the player will spawn at their bed. + * + * @param location where to set the respawn location + * @param force whether to forcefully set the respawn location even if a + * valid bed is not present + */ + public void setBedSpawnLocation(Location location, boolean force); + + /** + * Determines if the Player is allowed to fly via jump key double-tap like + * in creative mode. + * + * @return True if the player is allowed to fly. + */ + public boolean getAllowFlight(); + + /** + * Sets if the Player is allowed to fly via jump key double-tap like in + * creative mode. + * + * @param flight If flight should be allowed. + */ + public void setAllowFlight(boolean flight); + + /** + * Hides a player from this player + * + * @param player Player to hide + */ + public void hidePlayer(Player player); + + /** + * Allows this player to see a player that was previously hidden + * + * @param player Player to show + */ + public void showPlayer(Player player); + + /** + * Checks to see if a player has been hidden from this player + * + * @param player Player to check + * @return True if the provided player is not being hidden from this + * player + */ + public boolean canSee(Player player); + + /** + * Checks to see if this player is currently standing on a block. This + * information may not be reliable, as it is a state provided by the + * client, and may therefore not be accurate. + * + * @return True if the player standing on a solid block, else false. + * @deprecated Inconsistent with {@link + * org.bukkit.entity.Entity#isOnGround()} + */ + @Deprecated + public boolean isOnGround(); + + /** + * Checks to see if this player is currently flying or not. + * + * @return True if the player is flying, else false. + */ + public boolean isFlying(); + + /** + * Makes this player start or stop flying. + * + * @param value True to fly. + */ + public void setFlying(boolean value); + + /** + * Sets the speed at which a client will fly. Negative values indicate + * reverse directions. + * + * @param value The new speed, from -1 to 1. + * @throws IllegalArgumentException If new speed is less than -1 or + * greater than 1 + */ + public void setFlySpeed(float value) throws IllegalArgumentException; + + /** + * Sets the speed at which a client will walk. Negative values indicate + * reverse directions. + * + * @param value The new speed, from -1 to 1. + * @throws IllegalArgumentException If new speed is less than -1 or + * greater than 1 + */ + public void setWalkSpeed(float value) throws IllegalArgumentException; + + /** + * Gets the current allowed speed that a client can fly. + * + * @return The current allowed speed, from -1 to 1 + */ + public float getFlySpeed(); + + /** + * Gets the current allowed speed that a client can walk. + * + * @return The current allowed speed, from -1 to 1 + */ + public float getWalkSpeed(); + + /** + * Request that the player's client download and switch texture packs. + *

          + * The player's client will download the new texture pack asynchronously + * in the background, and will automatically switch to it once the + * download is complete. If the client has downloaded and cached the same + * texture pack in the past, it will perform a quick timestamp check over + * the network to determine if the texture pack has changed and needs to + * be downloaded again. When this request is sent for the very first time + * from a given server, the client will first display a confirmation GUI + * to the player before proceeding with the download. + *

          + * Notes: + *

            + *
          • Players can disable server textures on their client, in which + * case this method will have no affect on them. + *
          • There is no concept of resetting texture packs back to default + * within Minecraft, so players will have to relog to do so. + *
          + * + * @param url The URL from which the client will download the texture + * pack. The string must contain only US-ASCII characters and should + * be encoded as per RFC 1738. + * @throws IllegalArgumentException Thrown if the URL is null. + * @throws IllegalArgumentException Thrown if the URL is too long. + * @deprecated Minecraft no longer uses textures packs. Instead you + * should use {@link #setResourcePack(String)}. + */ + @Deprecated + public void setTexturePack(String url); + + /** + * Request that the player's client download and switch resource packs. + *

          + * The player's client will download the new resource pack asynchronously + * in the background, and will automatically switch to it once the + * download is complete. If the client has downloaded and cached the same + * resource pack in the past, it will perform a quick timestamp check + * over the network to determine if the resource pack has changed and + * needs to be downloaded again. When this request is sent for the very + * first time from a given server, the client will first display a + * confirmation GUI to the player before proceeding with the download. + *

          + * Notes: + *

            + *
          • Players can disable server resources on their client, in which + * case this method will have no affect on them. + *
          • There is no concept of resetting resource packs back to default + * within Minecraft, so players will have to relog to do so. + *
          + * + * @param url The URL from which the client will download the resource + * pack. The string must contain only US-ASCII characters and should + * be encoded as per RFC 1738. + * @throws IllegalArgumentException Thrown if the URL is null. + * @throws IllegalArgumentException Thrown if the URL is too long. The + * length restriction is an implementation specific arbitrary value. + */ + public void setResourcePack(String url); + + /** + * Gets the Scoreboard displayed to this player + * + * @return The current scoreboard seen by this player + */ + public Scoreboard getScoreboard(); + + /** + * Sets the player's visible Scoreboard. + * + * @param scoreboard New Scoreboard for the player + * @throws IllegalArgumentException if scoreboard is null + * @throws IllegalArgumentException if scoreboard was not created by the + * {@link org.bukkit.scoreboard.ScoreboardManager scoreboard manager} + * @throws IllegalStateException if this is a player that is not logged + * yet or has logged out + */ + public void setScoreboard(Scoreboard scoreboard) throws IllegalArgumentException, IllegalStateException; + + /** + * Gets if the client is displayed a 'scaled' health, that is, health on a + * scale from 0-{@link #getHealthScale()}. + * + * @return if client health display is scaled + * @see Player#setHealthScaled(boolean) + */ + public boolean isHealthScaled(); + + /** + * Sets if the client is displayed a 'scaled' health, that is, health on a + * scale from 0-{@link #getHealthScale()}. + *

          + * Displayed health follows a simple formula displayedHealth = + * getHealth() / getMaxHealth() * getHealthScale(). + * + * @param scale if the client health display is scaled + */ + public void setHealthScaled(boolean scale); + + /** + * Sets the number to scale health to for the client; this will also + * {@link #setHealthScaled(boolean) setHealthScaled(true)}. + *

          + * Displayed health follows a simple formula displayedHealth = + * getHealth() / getMaxHealth() * getHealthScale(). + * + * @param scale the number to scale health to + * @throws IllegalArgumentException if scale is <0 + * @throws IllegalArgumentException if scale is {@link Double#NaN} + * @throws IllegalArgumentException if scale is too high + */ + public void setHealthScale(double scale) throws IllegalArgumentException; + + /** + * Gets the number that health is scaled to for the client. + * + * @return the number that health would be scaled to for the client if + * HealthScaling is set to true + * @see Player#setHealthScale(double) + * @see Player#setHealthScaled(boolean) + */ + public double getHealthScale(); +} diff --git a/src/main/java/org/bukkit/entity/PoweredMinecart.java b/src/main/java/org/bukkit/entity/PoweredMinecart.java new file mode 100644 index 0000000..38240a9 --- /dev/null +++ b/src/main/java/org/bukkit/entity/PoweredMinecart.java @@ -0,0 +1,9 @@ +package org.bukkit.entity; + +/** + * @deprecated This class has been moved into a sub package; {@link + * org.bukkit.entity.minecart.PoweredMinecart} should be used instead. + * @see org.bukkit.entity.minecart.PoweredMinecart + */ +@Deprecated +public interface PoweredMinecart extends org.bukkit.entity.minecart.PoweredMinecart {} diff --git a/src/main/java/org/bukkit/entity/Projectile.java b/src/main/java/org/bukkit/entity/Projectile.java new file mode 100644 index 0000000..90ce3b3 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Projectile.java @@ -0,0 +1,56 @@ +package org.bukkit.entity; + +import org.bukkit.projectiles.ProjectileSource; + +/** + * Represents a shootable entity. + */ +public interface Projectile extends Entity { + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public LivingEntity _INVALID_getShooter(); + + /** + * Retrieve the shooter of this projectile. + * + * @return the {@link ProjectileSource} that shot this projectile + */ + public ProjectileSource getShooter(); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public void _INVALID_setShooter(LivingEntity shooter); + + /** + * Set the shooter of this projectile. + * + * @param source the {@link ProjectileSource} that shot this projectile + */ + public void setShooter(ProjectileSource source); + + /** + * Determine if this projectile should bounce or not when it hits. + *

          + * If a small fireball does not bounce it will set the target on fire. + * + * @return true if it should bounce. + */ + public boolean doesBounce(); + + /** + * Set whether or not this projectile should bounce or not when it hits + * something. + * + * @param doesBounce whether or not it should bounce. + */ + public void setBounce(boolean doesBounce); +} diff --git a/src/main/java/org/bukkit/entity/Sheep.java b/src/main/java/org/bukkit/entity/Sheep.java new file mode 100644 index 0000000..f4ce312 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Sheep.java @@ -0,0 +1,19 @@ +package org.bukkit.entity; + +import org.bukkit.material.Colorable; + +/** + * Represents a Sheep. + */ +public interface Sheep extends Animals, Colorable { + + /** + * @return Whether the sheep is sheared. + */ + public boolean isSheared(); + + /** + * @param flag Whether to shear the sheep + */ + public void setSheared(boolean flag); +} diff --git a/src/main/java/org/bukkit/entity/Silverfish.java b/src/main/java/org/bukkit/entity/Silverfish.java new file mode 100644 index 0000000..fe01007 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Silverfish.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Silverfish. + */ +public interface Silverfish extends Monster {} diff --git a/src/main/java/org/bukkit/entity/Skeleton.java b/src/main/java/org/bukkit/entity/Skeleton.java new file mode 100644 index 0000000..02b76c3 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Skeleton.java @@ -0,0 +1,65 @@ +package org.bukkit.entity; + +/** + * Represents a Skeleton. + */ +public interface Skeleton extends Monster { + + /** + * Gets the current type of this skeleton. + * + * @return Current type + */ + public SkeletonType getSkeletonType(); + + /** + * Sets the new type of this skeleton. + * + * @param type New type + */ + public void setSkeletonType(SkeletonType type); + + /* + * Represents the various different Skeleton types. + */ + public enum SkeletonType { + NORMAL(0), + WITHER(1); + + private static final SkeletonType[] types = new SkeletonType[SkeletonType.values().length]; + private final int id; + + static { + for (SkeletonType type : values()) { + types[type.getId()] = type; + } + } + + private SkeletonType(int id) { + this.id = id; + } + + /** + * Gets the ID of this skeleton type. + * + * @return Skeleton type ID + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets a skeleton type by its ID. + * + * @param id ID of the skeleton type to get. + * @return Resulting skeleton type, or null if not found. + * @deprecated Magic value + */ + @Deprecated + public static SkeletonType getType(int id) { + return (id >= types.length) ? null : types[id]; + } + } +} diff --git a/src/main/java/org/bukkit/entity/Slime.java b/src/main/java/org/bukkit/entity/Slime.java new file mode 100644 index 0000000..cbf50c8 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Slime.java @@ -0,0 +1,17 @@ +package org.bukkit.entity; + +/** + * Represents a Slime. + */ +public interface Slime extends LivingEntity { + + /** + * @return The size of the slime + */ + public int getSize(); + + /** + * @param sz The new size of the slime. + */ + public void setSize(int sz); +} diff --git a/src/main/java/org/bukkit/entity/SmallFireball.java b/src/main/java/org/bukkit/entity/SmallFireball.java new file mode 100644 index 0000000..33f54d3 --- /dev/null +++ b/src/main/java/org/bukkit/entity/SmallFireball.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a small {@link Fireball} + */ +public interface SmallFireball extends Fireball { + +} diff --git a/src/main/java/org/bukkit/entity/Snowball.java b/src/main/java/org/bukkit/entity/Snowball.java new file mode 100644 index 0000000..8c6b433 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Snowball.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a snowball. + */ +public interface Snowball extends Projectile {} diff --git a/src/main/java/org/bukkit/entity/Snowman.java b/src/main/java/org/bukkit/entity/Snowman.java new file mode 100644 index 0000000..c8070ff --- /dev/null +++ b/src/main/java/org/bukkit/entity/Snowman.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a snowman entity + */ +public interface Snowman extends Golem { + +} diff --git a/src/main/java/org/bukkit/entity/Spider.java b/src/main/java/org/bukkit/entity/Spider.java new file mode 100644 index 0000000..f9ee8cc --- /dev/null +++ b/src/main/java/org/bukkit/entity/Spider.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Spider. + */ +public interface Spider extends Monster {} diff --git a/src/main/java/org/bukkit/entity/Squid.java b/src/main/java/org/bukkit/entity/Squid.java new file mode 100644 index 0000000..fb47968 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Squid.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Squid. + */ +public interface Squid extends WaterMob {} diff --git a/src/main/java/org/bukkit/entity/StorageMinecart.java b/src/main/java/org/bukkit/entity/StorageMinecart.java new file mode 100644 index 0000000..5436d70 --- /dev/null +++ b/src/main/java/org/bukkit/entity/StorageMinecart.java @@ -0,0 +1,9 @@ +package org.bukkit.entity; + +/** + * @deprecated This class has been moved into a sub package; {@link + * org.bukkit.entity.minecart.StorageMinecart} should be used instead. + * @see org.bukkit.entity.minecart.StorageMinecart + */ +@Deprecated +public interface StorageMinecart extends org.bukkit.entity.minecart.StorageMinecart {} diff --git a/src/main/java/org/bukkit/entity/TNTPrimed.java b/src/main/java/org/bukkit/entity/TNTPrimed.java new file mode 100644 index 0000000..3ce322d --- /dev/null +++ b/src/main/java/org/bukkit/entity/TNTPrimed.java @@ -0,0 +1,38 @@ +package org.bukkit.entity; + +/** + * Represents a Primed TNT. + */ +public interface TNTPrimed extends Explosive { + + /** + * Set the number of ticks until the TNT blows up after being primed. + * + * @param fuseTicks The fuse ticks + */ + public void setFuseTicks(int fuseTicks); + + /** + * Retrieve the number of ticks until the explosion of this TNTPrimed + * entity + * + * @return the number of ticks until this TNTPrimed explodes + */ + public int getFuseTicks(); + + /** + * Gets the source of this primed TNT. The source is the entity + * responsible for the creation of this primed TNT. (I.E. player ignites + * TNT with flint and steel.) Take note that this can be null if there is + * no suitable source. (created by the {@link + * org.bukkit.World#spawn(Location, Class)} method, for example.) + *

          + * The source will become null if the chunk this primed TNT is in is + * unloaded then reloaded. If the source Entity becomes invalidated for + * any reason, such being removed from the world, the returned value will + * be null. + * + * @return the source of this primed TNT + */ + public Entity getSource(); +} diff --git a/src/main/java/org/bukkit/entity/Tameable.java b/src/main/java/org/bukkit/entity/Tameable.java new file mode 100644 index 0000000..014885d --- /dev/null +++ b/src/main/java/org/bukkit/entity/Tameable.java @@ -0,0 +1,44 @@ +package org.bukkit.entity; + +public interface Tameable { + + /** + * Check if this is tamed + *

          + * If something is tamed then a player can not tame it through normal + * methods, even if it does not belong to anyone in particular. + * + * @return true if this has been tamed + */ + public boolean isTamed(); + + /** + * Sets if this has been tamed. Not necessary if the method setOwner has + * been used, as it tames automatically. + *

          + * If something is tamed then a player can not tame it through normal + * methods, even if it does not belong to anyone in particular. + * + * @param tame true if tame + */ + public void setTamed(boolean tame); + + /** + * Gets the current owning AnimalTamer + * + * @return the owning AnimalTamer, or null if not owned + */ + public AnimalTamer getOwner(); + + /** + * Set this to be owned by given AnimalTamer. + *

          + * If the owner is not null, this will be tamed and will have any current + * path it is following removed. If the owner is set to null, this will be + * untamed, and the current owner removed. + * + * @param tamer the AnimalTamer who should own this + */ + public void setOwner(AnimalTamer tamer); + +} diff --git a/src/main/java/org/bukkit/entity/ThrownExpBottle.java b/src/main/java/org/bukkit/entity/ThrownExpBottle.java new file mode 100644 index 0000000..671282e --- /dev/null +++ b/src/main/java/org/bukkit/entity/ThrownExpBottle.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a thrown Experience bottle. + */ +public interface ThrownExpBottle extends Projectile { + +} diff --git a/src/main/java/org/bukkit/entity/ThrownPotion.java b/src/main/java/org/bukkit/entity/ThrownPotion.java new file mode 100644 index 0000000..8b382db --- /dev/null +++ b/src/main/java/org/bukkit/entity/ThrownPotion.java @@ -0,0 +1,39 @@ +package org.bukkit.entity; + +import java.util.Collection; + +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; + +/** + * Represents a thrown potion bottle + */ +public interface ThrownPotion extends Projectile { + + /** + * Returns the effects that are applied by this potion. + * + * @return The potion effects + */ + public Collection getEffects(); + + /** + * Returns a copy of the ItemStack for this thrown potion. + *

          + * Altering this copy will not alter the thrown potion directly. If you + * want to alter the thrown potion, you must use the {@link + * #setItem(ItemStack) setItemStack} method. + * + * @return A copy of the ItemStack for this thrown potion. + */ + public ItemStack getItem(); + + /** + * Set the ItemStack for this thrown potion. + *

          + * The ItemStack must be a potion, otherwise an exception is thrown. + * + * @param item New ItemStack + */ + public void setItem(ItemStack item); +} diff --git a/src/main/java/org/bukkit/entity/Vehicle.java b/src/main/java/org/bukkit/entity/Vehicle.java new file mode 100644 index 0000000..7d7607c --- /dev/null +++ b/src/main/java/org/bukkit/entity/Vehicle.java @@ -0,0 +1,23 @@ +package org.bukkit.entity; + +import org.bukkit.util.Vector; + +/** + * Represents a vehicle entity. + */ +public interface Vehicle extends Entity { + + /** + * Gets the vehicle's velocity. + * + * @return velocity vector + */ + public Vector getVelocity(); + + /** + * Sets the vehicle's velocity. + * + * @param vel velocity vector + */ + public void setVelocity(Vector vel); +} diff --git a/src/main/java/org/bukkit/entity/Villager.java b/src/main/java/org/bukkit/entity/Villager.java new file mode 100644 index 0000000..51035c9 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Villager.java @@ -0,0 +1,69 @@ +package org.bukkit.entity; + +/** + * Represents a villager NPC + */ +public interface Villager extends Ageable, NPC { + + /** + * Gets the current profession of this villager. + * + * @return Current profession. + */ + public Profession getProfession(); + + /** + * Sets the new profession of this villager. + * + * @param profession New profession. + */ + public void setProfession(Profession profession); + + + /** + * Represents the various different Villager professions there may be. + */ + public enum Profession { + FARMER(0), + LIBRARIAN(1), + PRIEST(2), + BLACKSMITH(3), + BUTCHER(4); + + private static final Profession[] professions = new Profession[Profession.values().length]; + private final int id; + + static { + for (Profession type : values()) { + professions[type.getId()] = type; + } + } + + private Profession(int id) { + this.id = id; + } + + /** + * Gets the ID of this profession. + * + * @return Profession ID. + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets a profession by its ID. + * + * @param id ID of the profession to get. + * @return Resulting profession, or null if not found. + * @deprecated Magic value + */ + @Deprecated + public static Profession getProfession(int id) { + return (id >= professions.length) ? null : professions[id]; + } + } +} diff --git a/src/main/java/org/bukkit/entity/WaterMob.java b/src/main/java/org/bukkit/entity/WaterMob.java new file mode 100644 index 0000000..62b4e89 --- /dev/null +++ b/src/main/java/org/bukkit/entity/WaterMob.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Water Mob + */ +public interface WaterMob extends Creature {} diff --git a/src/main/java/org/bukkit/entity/Weather.java b/src/main/java/org/bukkit/entity/Weather.java new file mode 100644 index 0000000..6d77851 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Weather.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Weather related entity, such as a storm + */ +public interface Weather extends Entity {} diff --git a/src/main/java/org/bukkit/entity/Witch.java b/src/main/java/org/bukkit/entity/Witch.java new file mode 100644 index 0000000..9c5dc1f --- /dev/null +++ b/src/main/java/org/bukkit/entity/Witch.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a Witch + */ +public interface Witch extends Monster { +} diff --git a/src/main/java/org/bukkit/entity/Wither.java b/src/main/java/org/bukkit/entity/Wither.java new file mode 100644 index 0000000..0922c5c --- /dev/null +++ b/src/main/java/org/bukkit/entity/Wither.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a Wither boss + */ +public interface Wither extends Monster { +} diff --git a/src/main/java/org/bukkit/entity/WitherSkull.java b/src/main/java/org/bukkit/entity/WitherSkull.java new file mode 100644 index 0000000..33d20ab --- /dev/null +++ b/src/main/java/org/bukkit/entity/WitherSkull.java @@ -0,0 +1,21 @@ +package org.bukkit.entity; + +/** + * Represents a wither skull {@link Fireball}. + */ +public interface WitherSkull extends Fireball { + + /** + * Sets the charged status of the wither skull. + * + * @param charged whether it should be charged + */ + public void setCharged(boolean charged); + + /** + * Gets whether or not the wither skull is charged. + * + * @return whether the wither skull is charged + */ + public boolean isCharged(); +} diff --git a/src/main/java/org/bukkit/entity/Wolf.java b/src/main/java/org/bukkit/entity/Wolf.java new file mode 100644 index 0000000..9d5a896 --- /dev/null +++ b/src/main/java/org/bukkit/entity/Wolf.java @@ -0,0 +1,56 @@ +package org.bukkit.entity; + +import org.bukkit.DyeColor; + +/** + * Represents a Wolf + */ +public interface Wolf extends Animals, Tameable { + + /** + * Checks if this wolf is angry + * + * @return Anger true if angry + */ + public boolean isAngry(); + + /** + * Sets the anger of this wolf. + *

          + * An angry wolf can not be fed or tamed, and will actively look for + * targets to attack. + * + * @param angry true if angry + */ + public void setAngry(boolean angry); + + /** + * Checks if this wolf is sitting + * + * @return true if sitting + */ + public boolean isSitting(); + + /** + * Sets if this wolf is sitting. + *

          + * Will remove any path that the wolf was following beforehand. + * + * @param sitting true if sitting + */ + public void setSitting(boolean sitting); + + /** + * Get the collar color of this wolf + * + * @return the color of the collar + */ + public DyeColor getCollarColor(); + + /** + * Set the collar color of this wolf + * + * @param color the color to apply + */ + public void setCollarColor(DyeColor color); +} diff --git a/src/main/java/org/bukkit/entity/Zombie.java b/src/main/java/org/bukkit/entity/Zombie.java new file mode 100644 index 0000000..59b52fd --- /dev/null +++ b/src/main/java/org/bukkit/entity/Zombie.java @@ -0,0 +1,35 @@ +package org.bukkit.entity; + +/** + * Represents a Zombie. + */ +public interface Zombie extends Monster { + + /** + * Gets whether the zombie is a baby + * + * @return Whether the zombie is a baby + */ + public boolean isBaby(); + + /** + * Sets whether the zombie is a baby + * + * @param flag Whether the zombie is a baby + */ + public void setBaby(boolean flag); + + /** + * Gets whether the zombie is a villager + * + * @return Whether the zombie is a villager + */ + public boolean isVillager(); + + /** + * Sets whether the zombie is a villager + * + * @param flag Whether the zombie is a villager + */ + public void setVillager(boolean flag); +} diff --git a/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java b/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java new file mode 100644 index 0000000..e502680 --- /dev/null +++ b/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java @@ -0,0 +1,36 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Minecart; + +public interface CommandMinecart extends Minecart, CommandSender { + + /** + * Gets the command that this CommandMinecart will run when activated. + * This will never return null. If the CommandMinecart does not have a + * command, an empty String will be returned instead. + * + * @return Command that this CommandMinecart will run when powered. + */ + public String getCommand(); + + /** + * Sets the command that this CommandMinecart will run when activated. + * Setting the command to null is the same as setting it to an empty + * String. + * + * @param command Command that this CommandMinecart will run when + * activated. + */ + public void setCommand(String command); + + /** + * Sets the name of this CommandMinecart. The name is used with commands + * that this CommandMinecart executes. Setting the name to null is the + * same as setting it to "@". + * + * @param name New name for this CommandMinecart. + */ + public void setName(String name); + +} diff --git a/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java b/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java new file mode 100644 index 0000000..a4411da --- /dev/null +++ b/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java @@ -0,0 +1,9 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; + +/** + * Represents a Minecart with TNT inside it that can explode when triggered. + */ +public interface ExplosiveMinecart extends Minecart { +} diff --git a/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java b/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java new file mode 100644 index 0000000..5da9ce4 --- /dev/null +++ b/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java @@ -0,0 +1,10 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a Minecart with a Hopper inside it + */ +public interface HopperMinecart extends Minecart, InventoryHolder { +} diff --git a/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java b/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java new file mode 100644 index 0000000..57e8b1d --- /dev/null +++ b/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java @@ -0,0 +1,10 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; + +/** + * Represents a powered minecart. A powered minecart moves on its own when a + * player deposits {@link org.bukkit.Material#COAL fuel}. + */ +public interface PoweredMinecart extends Minecart { +} diff --git a/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java b/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java new file mode 100644 index 0000000..1b82645 --- /dev/null +++ b/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java @@ -0,0 +1,14 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; + +/** + * Represents a minecart that can have certain {@link + * org.bukkit.entity.Entity entities} as passengers. Normal passengers + * include all {@link org.bukkit.entity.LivingEntity living entities} with + * the exception of {@link org.bukkit.entity.IronGolem iron golems}. + * Non-player entities that meet normal passenger criteria automatically + * mount these minecarts when close enough. + */ +public interface RideableMinecart extends Minecart { +} diff --git a/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java b/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java new file mode 100644 index 0000000..0ce3592 --- /dev/null +++ b/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java @@ -0,0 +1,10 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; + +/** + * Represents a Minecart with an {@link org.bukkit.block.CreatureSpawner + * entity spawner} inside it. + */ +public interface SpawnerMinecart extends Minecart { +} diff --git a/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java b/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java new file mode 100644 index 0000000..4f04ab4 --- /dev/null +++ b/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java @@ -0,0 +1,12 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a minecart with a chest. These types of {@link Minecart + * minecarts} have their own inventory that can be accessed using methods + * from the {@link InventoryHolder} interface. + */ +public interface StorageMinecart extends Minecart, InventoryHolder { +} diff --git a/src/main/java/org/bukkit/event/Cancellable.java b/src/main/java/org/bukkit/event/Cancellable.java new file mode 100644 index 0000000..799b0b0 --- /dev/null +++ b/src/main/java/org/bukkit/event/Cancellable.java @@ -0,0 +1,20 @@ +package org.bukkit.event; + +public interface Cancellable { + + /** + * Gets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins + * + * @return true if this event is cancelled + */ + public boolean isCancelled(); + + /** + * Sets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins. + * + * @param cancel true if you wish to cancel this event + */ + public void setCancelled(boolean cancel); +} diff --git a/src/main/java/org/bukkit/event/Event.java b/src/main/java/org/bukkit/event/Event.java new file mode 100644 index 0000000..fa29c27 --- /dev/null +++ b/src/main/java/org/bukkit/event/Event.java @@ -0,0 +1,96 @@ +package org.bukkit.event; + +import org.bukkit.plugin.PluginManager; + +/** + * Represents an event. + * + * @see PluginManager#callEvent(Event) + * @see PluginManager#registerEvents(Listener,Plugin) + */ +public abstract class Event { + private String name; + private final boolean async; + + /** + * The default constructor is defined for cleaner code. This constructor + * assumes the event is synchronous. + */ + public Event() { + this(false); + } + + /** + * This constructor is used to explicitly declare an event as synchronous + * or asynchronous. + * + * @param isAsync true indicates the event will fire asynchronously, false + * by default from default constructor + */ + public Event(boolean isAsync) { + this.async = isAsync; + } + + /** + * Convenience method for providing a user-friendly identifier. By + * default, it is the event's class's {@linkplain Class#getSimpleName() + * simple name}. + * + * @return name of this event + */ + public String getEventName() { + if (name == null) { + name = getClass().getSimpleName(); + } + return name; + } + + public abstract HandlerList getHandlers(); + + /** + * Any custom event that should not by synchronized with other events must + * use the specific constructor. These are the caveats of using an + * asynchronous event: + *

            + *
          • The event is never fired from inside code triggered by a + * synchronous event. Attempting to do so results in an {@link + * java.lang.IllegalStateException}. + *
          • However, asynchronous event handlers may fire synchronous or + * asynchronous events + *
          • The event may be fired multiple times simultaneously and in any + * order. + *
          • Any newly registered or unregistered handler is ignored after an + * event starts execution. + *
          • The handlers for this event may block for any length of time. + *
          • Some implementations may selectively declare a specific event use + * as asynchronous. This behavior should be clearly defined. + *
          • Asynchronous calls are not calculated in the plugin timing system. + *
          + * + * @return false by default, true if the event fires asynchronously + */ + public final boolean isAsynchronous() { + return async; + } + + public enum Result { + + /** + * Deny the event. Depending on the event, the action indicated by the + * event will either not take place or will be reverted. Some actions + * may not be denied. + */ + DENY, + /** + * Neither deny nor allow the event. The server will proceed with its + * normal handling. + */ + DEFAULT, + /** + * Allow / Force the event. The action indicated by the event will + * take place if possible, even if the server would not normally allow + * the action. Some actions may not be allowed. + */ + ALLOW; + } +} diff --git a/src/main/java/org/bukkit/event/EventException.java b/src/main/java/org/bukkit/event/EventException.java new file mode 100644 index 0000000..84638e8 --- /dev/null +++ b/src/main/java/org/bukkit/event/EventException.java @@ -0,0 +1,53 @@ +package org.bukkit.event; + +public class EventException extends Exception { + private static final long serialVersionUID = 3532808232324183999L; + private final Throwable cause; + + /** + * Constructs a new EventException based on the given Exception + * + * @param throwable Exception that triggered this Exception + */ + public EventException(Throwable throwable) { + cause = throwable; + } + + /** + * Constructs a new EventException + */ + public EventException() { + cause = null; + } + + /** + * Constructs a new EventException with the given message + * + * @param cause The exception that caused this + * @param message The message + */ + public EventException(Throwable cause, String message) { + super(message); + this.cause = cause; + } + + /** + * Constructs a new EventException with the given message + * + * @param message The message + */ + public EventException(String message) { + super(message); + cause = null; + } + + /** + * If applicable, returns the Exception that triggered this Exception + * + * @return Inner exception, or null if one does not exist + */ + @Override + public Throwable getCause() { + return cause; + } +} diff --git a/src/main/java/org/bukkit/event/EventHandler.java b/src/main/java/org/bukkit/event/EventHandler.java new file mode 100644 index 0000000..e42acc1 --- /dev/null +++ b/src/main/java/org/bukkit/event/EventHandler.java @@ -0,0 +1,37 @@ +package org.bukkit.event; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * An annotation to mark methods as being event handler methods + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface EventHandler { + + /** + * Define the priority of the event. + *

          + * First priority to the last priority executed: + *

            + *
          1. LOWEST + *
          2. LOW + *
          3. NORMAL + *
          4. HIGH + *
          5. HIGHEST + *
          6. MONITOR + *
          + */ + EventPriority priority() default EventPriority.NORMAL; + + /** + * Define if the handler ignores a cancelled event. + *

          + * If ignoreCancelled is true and the event is cancelled, the method is + * not called. Otherwise, the method is always called. + */ + boolean ignoreCancelled() default false; +} diff --git a/src/main/java/org/bukkit/event/EventPriority.java b/src/main/java/org/bukkit/event/EventPriority.java new file mode 100644 index 0000000..61ffa50 --- /dev/null +++ b/src/main/java/org/bukkit/event/EventPriority.java @@ -0,0 +1,47 @@ +package org.bukkit.event; + +/** + * Represents an event's priority in execution + */ +public enum EventPriority { + + /** + * Event call is of very low importance and should be ran first, to allow + * other plugins to further customise the outcome + */ + LOWEST(0), + /** + * Event call is of low importance + */ + LOW(1), + /** + * Event call is neither important nor unimportant, and may be ran + * normally + */ + NORMAL(2), + /** + * Event call is of high importance + */ + HIGH(3), + /** + * Event call is critical and must have the final say in what happens + * to the event + */ + HIGHEST(4), + /** + * Event is listened to purely for monitoring the outcome of an event. + *

          + * No modifications to the event should be made under this priority + */ + MONITOR(5); + + private final int slot; + + private EventPriority(int slot) { + this.slot = slot; + } + + public int getSlot() { + return slot; + } +} diff --git a/src/main/java/org/bukkit/event/HandlerList.java b/src/main/java/org/bukkit/event/HandlerList.java new file mode 100644 index 0000000..7d5efff --- /dev/null +++ b/src/main/java/org/bukkit/event/HandlerList.java @@ -0,0 +1,231 @@ +package org.bukkit.event; + +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredListener; + +import java.util.*; +import java.util.Map.Entry; + +/** + * A list of event handlers, stored per-event. Based on lahwran's fevents. + */ +public class HandlerList { + + /** + * Handler array. This field being an array is the key to this system's + * speed. + */ + private volatile RegisteredListener[] handlers = null; + + /** + * Dynamic handler lists. These are changed using register() and + * unregister() and are automatically baked to the handlers array any time + * they have changed. + */ + private final EnumMap> handlerslots; + + /** + * List of all HandlerLists which have been created, for use in bakeAll() + */ + private static ArrayList allLists = new ArrayList(); + + /** + * Bake all handler lists. Best used just after all normal event + * registration is complete, ie just after all plugins are loaded if + * you're using fevents in a plugin system. + */ + public static void bakeAll() { + synchronized (allLists) { + for (HandlerList h : allLists) { + h.bake(); + } + } + } + + /** + * Unregister all listeners from all handler lists. + */ + public static void unregisterAll() { + synchronized (allLists) { + for (HandlerList h : allLists) { + synchronized (h) { + for (List list : h.handlerslots.values()) { + list.clear(); + } + h.handlers = null; + } + } + } + } + + /** + * Unregister a specific plugin's listeners from all handler lists. + * + * @param plugin plugin to unregister + */ + public static void unregisterAll(Plugin plugin) { + synchronized (allLists) { + for (HandlerList h : allLists) { + h.unregister(plugin); + } + } + } + + /** + * Unregister a specific listener from all handler lists. + * + * @param listener listener to unregister + */ + public static void unregisterAll(Listener listener) { + synchronized (allLists) { + for (HandlerList h : allLists) { + h.unregister(listener); + } + } + } + + /** + * Create a new handler list and initialize using EventPriority. + *

          + * The HandlerList is then added to meta-list for use in bakeAll() + */ + public HandlerList() { + handlerslots = new EnumMap>(EventPriority.class); + for (EventPriority o : EventPriority.values()) { + handlerslots.put(o, new ArrayList()); + } + synchronized (allLists) { + allLists.add(this); + } + } + + /** + * Register a new listener in this handler list + * + * @param listener listener to register + */ + public synchronized void register(RegisteredListener listener) { + if (handlerslots.get(listener.getPriority()).contains(listener)) + throw new IllegalStateException("This listener is already registered to priority " + listener.getPriority().toString()); + handlers = null; + handlerslots.get(listener.getPriority()).add(listener); + } + + /** + * Register a collection of new listeners in this handler list + * + * @param listeners listeners to register + */ + public void registerAll(Collection listeners) { + for (RegisteredListener listener : listeners) { + register(listener); + } + } + + /** + * Remove a listener from a specific order slot + * + * @param listener listener to remove + */ + public synchronized void unregister(RegisteredListener listener) { + if (handlerslots.get(listener.getPriority()).remove(listener)) { + handlers = null; + } + } + + /** + * Remove a specific plugin's listeners from this handler + * + * @param plugin plugin to remove + */ + public synchronized void unregister(Plugin plugin) { + boolean changed = false; + for (List list : handlerslots.values()) { + for (ListIterator i = list.listIterator(); i.hasNext();) { + if (i.next().getPlugin().equals(plugin)) { + i.remove(); + changed = true; + } + } + } + if (changed) handlers = null; + } + + /** + * Remove a specific listener from this handler + * + * @param listener listener to remove + */ + public synchronized void unregister(Listener listener) { + boolean changed = false; + for (List list : handlerslots.values()) { + for (ListIterator i = list.listIterator(); i.hasNext();) { + if (i.next().getListener().equals(listener)) { + i.remove(); + changed = true; + } + } + } + if (changed) handlers = null; + } + + /** + * Bake HashMap and ArrayLists to 2d array - does nothing if not necessary + */ + public synchronized void bake() { + if (handlers != null) return; // don't re-bake when still valid + List entries = new ArrayList(); + for (Entry> entry : handlerslots.entrySet()) { + entries.addAll(entry.getValue()); + } + handlers = entries.toArray(new RegisteredListener[entries.size()]); + } + + /** + * Get the baked registered listeners associated with this handler list + * + * @return the array of registered listeners + */ + public RegisteredListener[] getRegisteredListeners() { + RegisteredListener[] handlers; + while ((handlers = this.handlers) == null) bake(); // This prevents fringe cases of returning null + return handlers; + } + + /** + * Get a specific plugin's registered listeners associated with this + * handler list + * + * @param plugin the plugin to get the listeners of + * @return the list of registered listeners + */ + public static ArrayList getRegisteredListeners(Plugin plugin) { + ArrayList listeners = new ArrayList(); + synchronized (allLists) { + for (HandlerList h : allLists) { + synchronized (h) { + for (List list : h.handlerslots.values()) { + for (RegisteredListener listener : list) { + if (listener.getPlugin().equals(plugin)) { + listeners.add(listener); + } + } + } + } + } + } + return listeners; + } + + /** + * Get a list of all handler lists for every event type + * + * @return the list of all handler lists + */ + @SuppressWarnings("unchecked") + public static ArrayList getHandlerLists() { + synchronized (allLists) { + return (ArrayList) allLists.clone(); + } + } +} diff --git a/src/main/java/org/bukkit/event/Listener.java b/src/main/java/org/bukkit/event/Listener.java new file mode 100644 index 0000000..ff083e6 --- /dev/null +++ b/src/main/java/org/bukkit/event/Listener.java @@ -0,0 +1,6 @@ +package org.bukkit.event; + +/** + * Simple interface for tagging all EventListeners + */ +public interface Listener {} diff --git a/src/main/java/org/bukkit/event/block/Action.java b/src/main/java/org/bukkit/event/block/Action.java new file mode 100644 index 0000000..25d26e3 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/Action.java @@ -0,0 +1,33 @@ +package org.bukkit.event.block; + +public enum Action { + + /** + * Left-clicking a block + */ + LEFT_CLICK_BLOCK, + /** + * Right-clicking a block + */ + RIGHT_CLICK_BLOCK, + /** + * Left-clicking the air + */ + LEFT_CLICK_AIR, + /** + * Right-clicking the air + */ + RIGHT_CLICK_AIR, + /** + * Stepping onto or into a block (Ass-pressure) + * + * Examples: + *

            + *
          • Jumping on soil + *
          • Standing on pressure plate + *
          • Triggering redstone ore + *
          • Triggering tripwire + *
          + */ + PHYSICAL, +} diff --git a/src/main/java/org/bukkit/event/block/BlockBreakEvent.java b/src/main/java/org/bukkit/event/block/BlockBreakEvent.java new file mode 100644 index 0000000..a011f61 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockBreakEvent.java @@ -0,0 +1,55 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block is broken by a player. + *

          + * If you wish to have the block drop experience, you must set the experience + * value above 0. By default, experience will be set in the event if: + *

            + *
          1. The player is not in creative or adventure mode + *
          2. The player can loot the block (ie: does not destroy it completely, by + * using the correct tool) + *
          3. The player does not have silk touch + *
          4. The block drops experience in vanilla Minecraft + *
          + *

          + * Note: + * Plugins wanting to simulate a traditional block drop should set the block + * to air and utilize their own methods for determining what the default drop + * for the block being broken is and what to do about it, if anything. + *

          + * If a Block Break event is cancelled, the block will not break and + * experience will not drop. + */ +public class BlockBreakEvent extends BlockExpEvent implements Cancellable { + private final Player player; + private boolean cancel; + + public BlockBreakEvent(final Block theBlock, final Player player) { + super(theBlock, 0); + + this.player = player; + } + + /** + * Gets the Player that is breaking the block involved in this event. + * + * @return The Player that is breaking the block involved in this event + */ + public Player getPlayer() { + return player; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockBurnEvent.java b/src/main/java/org/bukkit/event/block/BlockBurnEvent.java new file mode 100644 index 0000000..1592a15 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockBurnEvent.java @@ -0,0 +1,38 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block is destroyed as a result of being burnt by fire. + *

          + * If a Block Burn event is cancelled, the block will not be destroyed as a + * result of being burnt by fire. + */ +public class BlockBurnEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + + public BlockBurnEvent(final Block block) { + super(block); + this.cancelled = false; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java b/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java new file mode 100644 index 0000000..3860f44 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java @@ -0,0 +1,90 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.Material; +import org.bukkit.event.HandlerList; + +/** + * Called when we try to place a block, to see if we can build it here or not. + *

          + * Note: + *

            + *
          • The Block returned by getBlock() is the block we are trying to place + * on, not the block we are trying to place. + *
          • If you want to figure out what is being placed, use {@link + * #getMaterial()} or {@link #getMaterialId()} instead. + *
          + */ +public class BlockCanBuildEvent extends BlockEvent { + private static final HandlerList handlers = new HandlerList(); + protected boolean buildable; + + /** + * + * @deprecated Magic value + */ + @Deprecated + protected int material; + + /** + * + * @deprecated Magic value + */ + @Deprecated + public BlockCanBuildEvent(final Block block, final int id, final boolean canBuild) { + super(block); + buildable = canBuild; + material = id; + } + + /** + * Gets whether or not the block can be built here. + *

          + * By default, returns Minecraft's answer on whether the block can be + * built here or not. + * + * @return boolean whether or not the block can be built + */ + public boolean isBuildable() { + return buildable; + } + + /** + * Sets whether the block can be built here or not. + * + * @param cancel true if you want to allow the block to be built here + * despite Minecraft's default behaviour + */ + public void setBuildable(boolean cancel) { + this.buildable = cancel; + } + + /** + * Gets the Material that we are trying to place. + * + * @return The Material that we are trying to place + */ + public Material getMaterial() { + return Material.getMaterial(material); + } + + /** + * Gets the Material ID for the Material that we are trying to place. + * + * @return The Material ID for the Material that we are trying to place + * @deprecated Magic value + */ + @Deprecated + public int getMaterialId() { + return material; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockDamageEvent.java b/src/main/java/org/bukkit/event/block/BlockDamageEvent.java new file mode 100644 index 0000000..d80e00e --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockDamageEvent.java @@ -0,0 +1,83 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a block is damaged by a player. + *

          + * If a Block Damage event is cancelled, the block will not be damaged. + */ +public class BlockDamageEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private boolean instaBreak; + private boolean cancel; + private final ItemStack itemstack; + + public BlockDamageEvent(final Player player, final Block block, final ItemStack itemInHand, final boolean instaBreak) { + super(block); + this.instaBreak = instaBreak; + this.player = player; + this.itemstack = itemInHand; + this.cancel = false; + } + + /** + * Gets the player damaging the block involved in this event. + * + * @return The player damaging the block involved in this event + */ + public Player getPlayer() { + return player; + } + + /** + * Gets if the block is set to instantly break when damaged by the player. + * + * @return true if the block should instantly break when damaged by the + * player + */ + public boolean getInstaBreak() { + return instaBreak; + } + + /** + * Sets if the block should instantly break when damaged by the player. + * + * @param bool true if you want the block to instantly break when damaged + * by the player + */ + public void setInstaBreak(boolean bool) { + this.instaBreak = bool; + } + + /** + * Gets the ItemStack for the item currently in the player's hand. + * + * @return The ItemStack for the item currently in the player's hand + */ + public ItemStack getItemInHand() { + return itemstack; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java b/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java new file mode 100644 index 0000000..16ee59b --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java @@ -0,0 +1,84 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +/** + * Called when an item is dispensed from a block. + *

          + * If a Block Dispense event is cancelled, the block will not dispense the + * item. + */ +public class BlockDispenseEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled = false; + private ItemStack item; + private Vector velocity; + + public BlockDispenseEvent(final Block block, final ItemStack dispensed, final Vector velocity) { + super(block); + this.item = dispensed; + this.velocity = velocity; + } + + /** + * Gets the item that is being dispensed. Modifying the returned item will + * have no effect, you must use {@link + * #setItem(org.bukkit.inventory.ItemStack)} instead. + * + * @return An ItemStack for the item being dispensed + */ + public ItemStack getItem() { + return item.clone(); + } + + /** + * Sets the item being dispensed. + * + * @param item the item being dispensed + */ + public void setItem(ItemStack item) { + this.item = item; + } + + /** + * Gets the velocity. + *

          + * Note: Modifying the returned Vector will not change the velocity, you + * must use {@link #setVelocity(org.bukkit.util.Vector)} instead. + * + * @return A Vector for the dispensed item's velocity + */ + public Vector getVelocity() { + return velocity.clone(); + } + + /** + * Sets the velocity of the item being dispensed. + * + * @param vel the velocity of the item being dispensed + */ + public void setVelocity(Vector vel) { + velocity = vel; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockEvent.java b/src/main/java/org/bukkit/event/block/BlockEvent.java new file mode 100644 index 0000000..2405205 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Event; + +/** + * Represents a block related event. + */ +public abstract class BlockEvent extends Event { + protected Block block; + + public BlockEvent(final Block theBlock) { + block = theBlock; + } + + /** + * Gets the block involved in this event. + * + * @return The Block which block is involved in this event + */ + public final Block getBlock() { + return block; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockExpEvent.java b/src/main/java/org/bukkit/event/block/BlockExpEvent.java new file mode 100644 index 0000000..08636a2 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockExpEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.HandlerList; + +/** + * An event that's called when a block yields experience. + */ +public class BlockExpEvent extends BlockEvent { + private static final HandlerList handlers = new HandlerList(); + private int exp; + + public BlockExpEvent(Block block, int exp) { + super(block); + + this.exp = exp; + } + + /** + * Get the experience dropped by the block after the event has processed + * + * @return The experience to drop + */ + public int getExpToDrop() { + return exp; + } + + /** + * Set the amount of experience dropped by the block after the event has + * processed + * + * @param exp 1 or higher to drop experience, else nothing will drop + */ + public void setExpToDrop(int exp) { + this.exp = exp; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockFadeEvent.java b/src/main/java/org/bukkit/event/block/BlockFadeEvent.java new file mode 100644 index 0000000..673bc5f --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockFadeEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block fades, melts or disappears based on world conditions + *

          + * Examples: + *

            + *
          • Snow melting due to being near a light source. + *
          • Ice melting due to being near a light source. + *
          • Fire burning out after time, without destroying fuel block. + *
          + *

          + * If a Block Fade event is cancelled, the block will not fade, melt or + * disappear. + */ +public class BlockFadeEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final BlockState newState; + + public BlockFadeEvent(final Block block, final BlockState newState) { + super(block); + this.newState = newState; + this.cancelled = false; + } + + /** + * Gets the state of the block that will be fading, melting or + * disappearing. + * + * @return The block state of the block that will be fading, melting or + * disappearing + */ + public BlockState getNewState() { + return newState; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockFormEvent.java b/src/main/java/org/bukkit/event/block/BlockFormEvent.java new file mode 100644 index 0000000..df0401f --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockFormEvent.java @@ -0,0 +1,39 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block is formed or spreads based on world conditions. + *

          + * Use {@link BlockSpreadEvent} to catch blocks that actually spread and don't + * just "randomly" form. + *

          + * Examples: + *

            + *
          • Snow forming due to a snow storm. + *
          • Ice forming in a snowy Biome like Taiga or Tundra. + *
          + *

          + * If a Block Form event is cancelled, the block will not be formed. + * + * @see BlockSpreadEvent + */ +public class BlockFormEvent extends BlockGrowEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + + public BlockFormEvent(final Block block, final BlockState newState) { + super(block, newState); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockFromToEvent.java b/src/main/java/org/bukkit/event/block/BlockFromToEvent.java new file mode 100644 index 0000000..f976bea --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockFromToEvent.java @@ -0,0 +1,71 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Represents events with a source block and a destination block, currently + * only applies to liquid (lava and water) and teleporting dragon eggs. + *

          + * If a Block From To event is cancelled, the block will not move (the liquid + * will not flow). + */ +public class BlockFromToEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected Block to; + protected BlockFace face; + protected boolean cancel; + + public BlockFromToEvent(final Block block, final BlockFace face) { + super(block); + this.face = face; + this.cancel = false; + } + + public BlockFromToEvent(final Block block, final Block toBlock) { + super(block); + this.to = toBlock; + this.face = BlockFace.SELF; + this.cancel = false; + } + + /** + * Gets the BlockFace that the block is moving to. + * + * @return The BlockFace that the block is moving to + */ + public BlockFace getFace() { + return face; + } + + /** + * Convenience method for getting the faced Block. + * + * @return The faced Block + */ + public Block getToBlock() { + if (to == null) { + to = block.getRelative(face); + } + return to; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockGrowEvent.java b/src/main/java/org/bukkit/event/block/BlockGrowEvent.java new file mode 100644 index 0000000..2a959fd --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockGrowEvent.java @@ -0,0 +1,56 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block grows naturally in the world. + *

          + * Examples: + *

            + *
          • Wheat + *
          • Sugar Cane + *
          • Cactus + *
          • Watermelon + *
          • Pumpkin + *
          + *

          + * If a Block Grow event is cancelled, the block will not grow. + */ +public class BlockGrowEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final BlockState newState; + private boolean cancelled = false; + + public BlockGrowEvent(final Block block, final BlockState newState) { + super(block); + this.newState = newState; + } + + /** + * Gets the state of the block where it will form or spread to. + * + * @return The block state for this events block + */ + public BlockState getNewState() { + return newState; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java b/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java new file mode 100644 index 0000000..733a15e --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java @@ -0,0 +1,138 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block is ignited. If you want to catch when a Player places + * fire, you need to use {@link BlockPlaceEvent}. + *

          + * If a Block Ignite event is cancelled, the block will not be ignited. + */ +public class BlockIgniteEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final IgniteCause cause; + private final Entity ignitingEntity; + private final Block ignitingBlock; + private boolean cancel; + + /** + * @deprecated use {@link BlockIgniteEvent#BlockIgniteEvent(Block, + * IgniteCause, Entity)} instead. + */ + @Deprecated + public BlockIgniteEvent(final Block theBlock, final IgniteCause cause, final Player thePlayer) { + this(theBlock, cause, (Entity) thePlayer); + } + + public BlockIgniteEvent(final Block theBlock, final IgniteCause cause, final Entity ignitingEntity) { + this(theBlock, cause, ignitingEntity, null); + } + + public BlockIgniteEvent(final Block theBlock, final IgniteCause cause, final Block ignitingBlock) { + this(theBlock, cause, null, ignitingBlock); + } + + public BlockIgniteEvent(final Block theBlock, final IgniteCause cause, final Entity ignitingEntity, final Block ignitingBlock) { + super(theBlock); + this.cause = cause; + this.ignitingEntity = ignitingEntity; + this.ignitingBlock = ignitingBlock; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the cause of block ignite. + * + * @return An IgniteCause value detailing the cause of block ignition + */ + public IgniteCause getCause() { + return cause; + } + + /** + * Gets the player who ignited this block + * + * @return The Player that placed/ignited the fire block, or null if not ignited by a Player. + */ + public Player getPlayer() { + if (ignitingEntity instanceof Player) { + return (Player) ignitingEntity; + } + + return null; + } + + /** + * Gets the entity who ignited this block + * + * @return The Entity that placed/ignited the fire block, or null if not ignited by a Entity. + */ + public Entity getIgnitingEntity() { + return ignitingEntity; + } + + /** + * Gets the block who ignited this block + * + * @return The Block that placed/ignited the fire block, or null if not ignited by a Block. + */ + public Block getIgnitingBlock() { + return ignitingBlock; + } + + /** + * An enum to specify the cause of the ignite + */ + public enum IgniteCause { + + /** + * Block ignition caused by lava. + */ + LAVA, + /** + * Block ignition caused by a player or dispenser using flint-and-steel. + */ + FLINT_AND_STEEL, + /** + * Block ignition caused by dynamic spreading of fire. + */ + SPREAD, + /** + * Block ignition caused by lightning. + */ + LIGHTNING, + /** + * Block ignition caused by an entity using a fireball. + */ + FIREBALL, + /** + * Block ignition caused by an Ender Crystal. + */ + ENDER_CRYSTAL, + /** + * Block ignition caused by explosion. + */ + EXPLOSION, + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java b/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java new file mode 100644 index 0000000..d16e4be --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.block; + +import com.google.common.collect.ImmutableList; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +/** + * Fired when a single block placement action of a player triggers the + * creation of multiple blocks(e.g. placing a bed block). The block returned + * by {@link #getBlockPlaced()} and its related methods is the block where + * the placed block would exist if the placement only affected a single + * block. + */ +public class BlockMultiPlaceEvent extends BlockPlaceEvent { + private final List states; + + public BlockMultiPlaceEvent(List states, Block clicked, ItemStack itemInHand, Player thePlayer, boolean canBuild) { + super(states.get(0).getBlock(), states.get(0), clicked, itemInHand, thePlayer, canBuild); + this.states = ImmutableList.copyOf(states); + } + + /** + * Gets a list of blockstates for all blocks which were replaced by the + * placement of the new blocks. Most of these blocks will just have a + * Material type of AIR. + * + * @return immutable list of replaced BlockStates + */ + public List getReplacedBlockStates() { + return states; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java b/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java new file mode 100644 index 0000000..e05d1ca --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java @@ -0,0 +1,62 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.Material; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a block physics check is called + */ +public class BlockPhysicsEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final int changed; + private boolean cancel = false; + + /** + * + * @deprecated Magic value + */ + @Deprecated + public BlockPhysicsEvent(final Block block, final int changed) { + super(block); + this.changed = changed; + } + + /** + * Gets the type of block that changed, causing this event + * + * @return Changed block's type id + * @deprecated Magic value + */ + @Deprecated + public int getChangedTypeId() { + return changed; + } + + /** + * Gets the type of block that changed, causing this event + * + * @return Changed block's type + */ + public Material getChangedType() { + return Material.getMaterial(changed); + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockPistonEvent.java b/src/main/java/org/bukkit/event/block/BlockPistonEvent.java new file mode 100644 index 0000000..b89006f --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockPistonEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.block; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.Cancellable; + +/** + * Called when a piston block is triggered + */ +public abstract class BlockPistonEvent extends BlockEvent implements Cancellable { + private boolean cancelled; + private final BlockFace direction; + + public BlockPistonEvent(final Block block, final BlockFace direction) { + super(block); + this.direction = direction; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + /** + * Returns true if the Piston in the event is sticky. + * + * @return stickiness of the piston + */ + public boolean isSticky() { + return block.getType() == Material.PISTON_STICKY_BASE; + } + + /** + * Return the direction in which the piston will operate. + * + * @return direction of the piston + */ + public BlockFace getDirection() { + // Both are meh! + // return ((PistonBaseMaterial) block.getType().getNewData(block.getData())).getFacing(); + // return ((PistonBaseMaterial) block.getState().getData()).getFacing(); + return direction; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java b/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java new file mode 100644 index 0000000..1058b8b --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.block; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.HandlerList; + +/** + * Called when a piston extends + */ +public class BlockPistonExtendEvent extends BlockPistonEvent { + private static final HandlerList handlers = new HandlerList(); + private final int length; + private List blocks; + + public BlockPistonExtendEvent(final Block block, final int length, final BlockFace direction) { + super(block, direction); + + this.length = length; + } + + /** + * Get the amount of blocks which will be moved while extending. + * + * @return the amount of moving blocks + */ + public int getLength() { + return this.length; + } + + /** + * Get an immutable list of the blocks which will be moved by the + * extending. + * + * @return Immutable list of the moved blocks. + */ + public List getBlocks() { + if (blocks == null) { + ArrayList tmp = new ArrayList(); + for (int i = 0; i < this.getLength(); i++) { + tmp.add(block.getRelative(getDirection(), i + 1)); + } + blocks = Collections.unmodifiableList(tmp); + } + return blocks; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java b/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java new file mode 100644 index 0000000..0190c4c --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java @@ -0,0 +1,35 @@ +package org.bukkit.event.block; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.HandlerList; + +/** + * Called when a piston retracts + */ +public class BlockPistonRetractEvent extends BlockPistonEvent { + private static final HandlerList handlers = new HandlerList(); + public BlockPistonRetractEvent(final Block block, final BlockFace direction) { + super(block, direction); + } + + /** + * Gets the location where the possible moving block might be if the + * retracting piston is sticky. + * + * @return The possible location of the possibly moving block. + */ + public Location getRetractLocation() { + return getBlock().getRelative(getDirection(), 2).getLocation(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java b/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java new file mode 100644 index 0000000..6d0ffe8 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java @@ -0,0 +1,121 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a block is placed by a player. + *

          + * If a Block Place event is cancelled, the block will not be placed. + */ +public class BlockPlaceEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected boolean cancel; + protected boolean canBuild; + protected Block placedAgainst; + protected BlockState replacedBlockState; + protected ItemStack itemInHand; + protected Player player; + + public BlockPlaceEvent(final Block placedBlock, final BlockState replacedBlockState, final Block placedAgainst, final ItemStack itemInHand, final Player thePlayer, final boolean canBuild) { + super(placedBlock); + this.placedAgainst = placedAgainst; + this.itemInHand = itemInHand; + this.player = thePlayer; + this.replacedBlockState = replacedBlockState; + this.canBuild = canBuild; + cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the player who placed the block involved in this event. + * + * @return The Player who placed the block involved in this event + */ + public Player getPlayer() { + return player; + } + + /** + * Clarity method for getting the placed block. Not really needed except + * for reasons of clarity. + * + * @return The Block that was placed + */ + public Block getBlockPlaced() { + return getBlock(); + } + + /** + * Gets the BlockState for the block which was replaced. Material type air + * mostly. + * + * @return The BlockState for the block which was replaced. + */ + public BlockState getBlockReplacedState() { + return this.replacedBlockState; + } + + /** + * Gets the block that this block was placed against + * + * @return Block the block that the new block was placed against + */ + public Block getBlockAgainst() { + return placedAgainst; + } + + /** + * Gets the item in the player's hand when they placed the block. + * + * @return The ItemStack for the item in the player's hand when they + * placed the block + */ + public ItemStack getItemInHand() { + return itemInHand; + } + + /** + * Gets the value whether the player would be allowed to build here. + * Defaults to spawn if the server was going to stop them (such as, the + * player is in Spawn). Note that this is an entirely different check + * than BLOCK_CANBUILD, as this refers to a player, not universe-physics + * rule like cactus on dirt. + * + * @return boolean whether the server would allow a player to build here + */ + public boolean canBuild() { + return this.canBuild; + } + + /** + * Sets the canBuild state of this event. Set to true if you want the + * player to be able to build. + * + * @param canBuild true if you want the player to be able to build + */ + public void setBuild(boolean canBuild) { + this.canBuild = canBuild; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java b/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java new file mode 100644 index 0000000..625ec90 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java @@ -0,0 +1,55 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.HandlerList; + +/** + * Called when a redstone current changes + */ +public class BlockRedstoneEvent extends BlockEvent { + private static final HandlerList handlers = new HandlerList(); + private final int oldCurrent; + private int newCurrent; + + public BlockRedstoneEvent(final Block block, final int oldCurrent, final int newCurrent) { + super(block); + this.oldCurrent = oldCurrent; + this.newCurrent = newCurrent; + } + + /** + * Gets the old current of this block + * + * @return The previous current + */ + public int getOldCurrent() { + return oldCurrent; + } + + /** + * Gets the new current of this block + * + * @return The new current + */ + public int getNewCurrent() { + return newCurrent; + } + + /** + * Sets the new current of this block + * + * @param newCurrent The new current to set + */ + public void setNewCurrent(int newCurrent) { + this.newCurrent = newCurrent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java b/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java new file mode 100644 index 0000000..a1fb363 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java @@ -0,0 +1,49 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.event.HandlerList; + +/** + * Called when a block spreads based on world conditions. + *

          + * Use {@link BlockFormEvent} to catch blocks that "randomly" form instead of + * actually spread. + *

          + * Examples: + *

            + *
          • Mushrooms spreading. + *
          • Fire spreading. + *
          + *

          + * If a Block Spread event is cancelled, the block will not spread. + * + * @see BlockFormEvent + */ +public class BlockSpreadEvent extends BlockFormEvent { + private static final HandlerList handlers = new HandlerList(); + private final Block source; + + public BlockSpreadEvent(final Block block, final Block source, final BlockState newState) { + super(block, newState); + this.source = source; + } + + /** + * Gets the source block involved in this event. + * + * @return the Block for the source block involved in this event. + */ + public Block getSource() { + return source; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java b/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java new file mode 100644 index 0000000..45efc32 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java @@ -0,0 +1,32 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Entity; + +/** + * Called when a block is formed by entities. + *

          + * Examples: + *

            + *
          • Snow formed by a {@link org.bukkit.entity.Snowman}. + *
          + */ +public class EntityBlockFormEvent extends BlockFormEvent { + private final Entity entity; + + public EntityBlockFormEvent(final Entity entity, final Block block, final BlockState blockstate) { + super(block, blockstate); + + this.entity = entity; + } + + /** + * Get the entity that formed the block. + * + * @return Entity involved in event + */ + public Entity getEntity() { + return entity; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java b/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java new file mode 100644 index 0000000..84d8cfd --- /dev/null +++ b/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when leaves are decaying naturally. + *

          + * If a Leaves Decay event is cancelled, the leaves will not decay. + */ +public class LeavesDecayEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + + public LeavesDecayEvent(final Block block) { + super(block); + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/NotePlayEvent.java b/src/main/java/org/bukkit/event/block/NotePlayEvent.java new file mode 100644 index 0000000..d4d4381 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/NotePlayEvent.java @@ -0,0 +1,83 @@ +package org.bukkit.event.block; + +import org.bukkit.Instrument; +import org.bukkit.Note; +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a note block is being played through player interaction or a + * redstone current. + */ +public class NotePlayEvent extends BlockEvent implements Cancellable { + + private static HandlerList handlers = new HandlerList(); + private Instrument instrument; + private Note note; + private boolean cancelled = false; + + public NotePlayEvent(Block block, Instrument instrument, Note note) { + super(block); + this.instrument = instrument; + this.note = note; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Gets the {@link Instrument} to be used. + * + * @return the Instrument; + */ + public Instrument getInstrument() { + return instrument; + } + + /** + * Gets the {@link Note} to be played. + * + * @return the Note. + */ + public Note getNote() { + return note; + } + + /** + * Overrides the {@link Instrument} to be used. + * + * @param instrument the Instrument. Has no effect if null. + */ + public void setInstrument(Instrument instrument) { + if (instrument != null) { + this.instrument = instrument; + } + + } + + /** + * Overrides the {@link Note} to be played. + * + * @param note the Note. Has no effect if null. + */ + public void setNote(Note note) { + if (note != null) { + this.note = note; + } + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/block/SignChangeEvent.java b/src/main/java/org/bukkit/event/block/SignChangeEvent.java new file mode 100644 index 0000000..d1b7908 --- /dev/null +++ b/src/main/java/org/bukkit/event/block/SignChangeEvent.java @@ -0,0 +1,84 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a sign is changed by a player. + *

          + * If a Sign Change event is cancelled, the sign will not be changed. + */ +public class SignChangeEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private final Player player; + private final String[] lines; + + public SignChangeEvent(final Block theBlock, final Player thePlayer, final String[] theLines) { + super(theBlock); + this.player = thePlayer; + this.lines = theLines; + } + + /** + * Gets the player changing the sign involved in this event. + * + * @return the Player involved in this event + */ + public Player getPlayer() { + return player; + } + + /** + * Gets all of the lines of text from the sign involved in this event. + * + * @return the String array for the sign's lines new text + */ + public String[] getLines() { + return lines; + } + + /** + * Gets a single line of text from the sign involved in this event. + * + * @param index index of the line to get + * @return the String containing the line of text associated with the + * provided index + * @throws IndexOutOfBoundsException thrown when the provided index is > 3 + * or < 0 + */ + public String getLine(int index) throws IndexOutOfBoundsException { + return lines[index]; + } + + /** + * Sets a single line for the sign involved in this event + * + * @param index index of the line to set + * @param line text to set + * @throws IndexOutOfBoundsException thrown when the provided index is > 3 + * or < 0 + */ + public void setLine(int index, String line) throws IndexOutOfBoundsException { + lines[index] = line; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java b/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java new file mode 100644 index 0000000..de28f1d --- /dev/null +++ b/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java @@ -0,0 +1,121 @@ +package org.bukkit.event.enchantment; + +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.block.Block; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.InventoryEvent; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +/** + * Called when an ItemStack is successfully enchanted (currently at + * enchantment table) + */ +public class EnchantItemEvent extends InventoryEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Block table; + private final ItemStack item; + private int level; + private boolean cancelled; + private final Map enchants; + private final Player enchanter; + private int button; + + public EnchantItemEvent(final Player enchanter, final InventoryView view, final Block table, final ItemStack item, final int level, final Map enchants, final int i) { + super(view); + this.enchanter = enchanter; + this.table = table; + this.item = item; + this.level = level; + this.enchants = new HashMap(enchants); + this.cancelled = false; + this.button = i; + } + + /** + * Gets the player enchanting the item + * + * @return enchanting player + */ + public Player getEnchanter() { + return enchanter; + } + + /** + * Gets the block being used to enchant the item + * + * @return the block used for enchanting + */ + public Block getEnchantBlock() { + return table; + } + + /** + * Gets the item to be enchanted (can be modified) + * + * @return ItemStack of item + */ + public ItemStack getItem() { + return item; + } + + /** + * Get cost in exp levels of the enchantment + * + * @return experience level cost + */ + public int getExpLevelCost() { + return level; + } + + /** + * Set cost in exp levels of the enchantment + * + * @param level - cost in levels + */ + public void setExpLevelCost(int level) { + this.level = level; + } + + /** + * Get map of enchantment (levels, keyed by type) to be added to item + * (modify map returned to change values). Note: Any enchantments not + * allowed for the item will be ignored + * + * @return map of enchantment levels, keyed by enchantment + */ + public Map getEnchantsToAdd() { + return enchants; + } + + /** + * Which button was pressed to initiate the enchanting. + * + * @return The button index (0, 1, or 2). + */ + public int whichButton() { + return button; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java b/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java new file mode 100644 index 0000000..6c0aa9f --- /dev/null +++ b/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java @@ -0,0 +1,96 @@ +package org.bukkit.event.enchantment; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.InventoryEvent; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +/** + * Called when an ItemStack is inserted in an enchantment table - can be + * called multiple times + */ +public class PrepareItemEnchantEvent extends InventoryEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Block table; + private final ItemStack item; + private final int[] levelsOffered; + private final int bonus; + private boolean cancelled; + private final Player enchanter; + + public PrepareItemEnchantEvent(final Player enchanter, InventoryView view, final Block table, final ItemStack item, final int[] levelsOffered, final int bonus) { + super(view); + this.enchanter = enchanter; + this.table = table; + this.item = item; + this.levelsOffered = levelsOffered; + this.bonus = bonus; + this.cancelled = false; + } + + /** + * Gets the player enchanting the item + * + * @return enchanting player + */ + public Player getEnchanter() { + return enchanter; + } + + /** + * Gets the block being used to enchant the item + * + * @return the block used for enchanting + */ + public Block getEnchantBlock() { + return table; + } + + /** + * Gets the item to be enchanted (can be modified) + * + * @return ItemStack of item + */ + public ItemStack getItem() { + return item; + } + + /** + * Get list of offered exp level costs of the enchantment (modify values + * to change offer) + * + * @return experience level costs offered + */ + public int[] getExpLevelCostsOffered() { + return levelsOffered; + } + + /** + * Get enchantment bonus in effect - corresponds to number of bookshelves + * + * @return enchantment bonus + */ + public int getEnchantmentBonus() { + return bonus; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java b/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java new file mode 100644 index 0000000..288e98b --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java @@ -0,0 +1,195 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.CreatureType; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a creature is spawned into a world. + *

          + * If a Creature Spawn event is cancelled, the creature will not spawn. + */ +public class CreatureSpawnEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final SpawnReason spawnReason; + + public CreatureSpawnEvent(final LivingEntity spawnee, final SpawnReason spawnReason) { + super(spawnee); + this.spawnReason = spawnReason; + } + + @Deprecated + public CreatureSpawnEvent(Entity spawnee, CreatureType type, Location loc, SpawnReason reason) { + super(spawnee); + spawnReason = reason; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets the location at which the creature is spawning. + * + * @return The location at which the creature is spawning + */ + public Location getLocation() { + return getEntity().getLocation(); + } + + /** + * Gets the type of creature being spawned. + * + * @return A CreatureType value detailing the type of creature being + * spawned + * @deprecated In favour of {@link #getEntityType()}. + */ + @Deprecated + public CreatureType getCreatureType() { + return CreatureType.fromEntityType(getEntityType()); + } + + /** + * Gets the reason for why the creature is being spawned. + * + * @return A SpawnReason value detailing the reason for the creature being + * spawned + */ + public SpawnReason getSpawnReason() { + return spawnReason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the type of spawning + */ + public enum SpawnReason { + + /** + * When something spawns from natural means + */ + NATURAL, + /** + * When an entity spawns as a jockey of another entity (mostly spider + * jockeys) + */ + JOCKEY, + /** + * When a creature spawns due to chunk generation + */ + CHUNK_GEN, + /** + * When a creature spawns from a spawner + */ + SPAWNER, + /** + * When a creature spawns from an egg + */ + EGG, + /** + * When a creature spawns from a Spawner Egg + */ + SPAWNER_EGG, + /** + * When a creature spawns because of a lightning strike + */ + LIGHTNING, + /** + * When a creature is spawned by a player that is sleeping + * + * @deprecated No longer used + */ + @Deprecated + BED, + /** + * When a snowman is spawned by being built + */ + BUILD_SNOWMAN, + /** + * When an iron golem is spawned by being built + */ + BUILD_IRONGOLEM, + /** + * When a wither boss is spawned by being built + */ + BUILD_WITHER, + /** + * When an iron golem is spawned to defend a village + */ + VILLAGE_DEFENSE, + /** + * When a zombie is spawned to invade a village + */ + VILLAGE_INVASION, + /** + * When an animal breeds to create a child + */ + BREEDING, + /** + * When a slime splits + */ + SLIME_SPLIT, + /** + * When an entity calls for reinforcements + */ + REINFORCEMENTS, + /** + * When a creature is spawned by nether portal + */ + NETHER_PORTAL, + /** + * When a creature is spawned by a dispenser dispensing an egg + */ + DISPENSE_EGG, + /** + * When a zombie infects a villager + */ + INFECTION, + /** + * When a villager is cured from infection + */ + CURED, + /** + * When an ocelot has a baby spawned along with them + */ + OCELOT_BABY, + /** + * When a silverfish spawns from a block + */ + SILVERFISH_BLOCK, + /** + * When an entity spawns as a mount of another entity (mostly chicken + * jockeys) + */ + MOUNT, + /** + * When a creature is spawned by plugins + */ + CUSTOM, + /** + * When an entity is missing a SpawnReason + */ + DEFAULT + } +} diff --git a/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java b/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java new file mode 100644 index 0000000..b103a6a --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java @@ -0,0 +1,93 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Creeper; +import org.bukkit.entity.LightningStrike; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a Creeper is struck by lightning. + *

          + * If a Creeper Power event is cancelled, the Creeper will not be powered. + */ +public class CreeperPowerEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final PowerCause cause; + private LightningStrike bolt; + + public CreeperPowerEvent(final Creeper creeper, final LightningStrike bolt, final PowerCause cause) { + this(creeper, cause); + this.bolt = bolt; + } + + public CreeperPowerEvent(final Creeper creeper, final PowerCause cause) { + super(creeper); + this.cause = cause; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + @Override + public Creeper getEntity() { + return (Creeper) entity; + } + + /** + * Gets the lightning bolt which is striking the Creeper. + * + * @return The Entity for the lightning bolt which is striking the Creeper + */ + public LightningStrike getLightning() { + return bolt; + } + + /** + * Gets the cause of the creeper being (un)powered. + * + * @return A PowerCause value detailing the cause of change in power. + */ + public PowerCause getCause() { + return cause; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the cause of the change in power + */ + public enum PowerCause { + + /** + * Power change caused by a lightning bolt + *

          + * Powered state: true + */ + LIGHTNING, + /** + * Power change caused by something else (probably a plugin) + *

          + * Powered state: true + */ + SET_ON, + /** + * Power change caused by something else (probably a plugin) + *

          + * Powered state: false + */ + SET_OFF + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java b/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java new file mode 100644 index 0000000..2cbbc69 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java @@ -0,0 +1,22 @@ +package org.bukkit.event.entity; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; + +/** + * Called when an {@link Entity} breaks a door + *

          + * Cancelling the event will cause the event to be delayed + */ +public class EntityBreakDoorEvent extends EntityChangeBlockEvent { + public EntityBreakDoorEvent(final LivingEntity entity, final Block targetBlock) { + super(entity, targetBlock, Material.AIR, (byte) 0); + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java b/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java new file mode 100644 index 0000000..41be9ca --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java @@ -0,0 +1,95 @@ +package org.bukkit.event.entity; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when any Entity, excluding players, changes a block. + */ +public class EntityChangeBlockEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Block block; + private boolean cancel; + private final Material to; + private final byte data; + + /** + * + * @param what the LivingEntity causing the change + * @param block the block (before the change) + * @param to the future material being changed to + * @deprecated Provided as a backward compatibility before the data byte + * was provided, and type increased to all entities + */ + @Deprecated + public EntityChangeBlockEvent(final LivingEntity what, final Block block, final Material to) { + this (what, block, to, (byte) 0); + } + + /** + * + * @param what the Entity causing the change + * @param block the block (before the change) + * @param to the future material being changed to + * @param data the future block data + * @deprecated Magic value + */ + @Deprecated + public EntityChangeBlockEvent(final Entity what, final Block block, final Material to, final byte data) { + super(what); + this.block = block; + this.cancel = false; + this.to = to; + this.data = data; + } + + /** + * Gets the block the entity is changing + * + * @return the block that is changing + */ + public Block getBlock() { + return block; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the Material that the block is changing into + * + * @return the material that the block is changing into + */ + public Material getTo() { + return to; + } + + /** + * Gets the data for the block that would be changed into + * + * @return the data for the block that would be changed into + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java b/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java new file mode 100644 index 0000000..c84bda9 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java @@ -0,0 +1,27 @@ +package org.bukkit.event.entity; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; + +/** + * Called when a block causes an entity to combust. + */ +public class EntityCombustByBlockEvent extends EntityCombustEvent { + private final Block combuster; + + public EntityCombustByBlockEvent(final Block combuster, final Entity combustee, final int duration) { + super(combustee, duration); + this.combuster = combuster; + } + + /** + * The combuster can be lava or a block that is on fire. + *

          + * WARNING: block may be null. + * + * @return the Block that set the combustee alight. + */ + public Block getCombuster() { + return combuster; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java b/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java new file mode 100644 index 0000000..639567b --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; + +/** + * Called when an entity causes another entity to combust. + */ +public class EntityCombustByEntityEvent extends EntityCombustEvent { + private final Entity combuster; + + public EntityCombustByEntityEvent(final Entity combuster, final Entity combustee, final int duration) { + super(combustee, duration); + this.combuster = combuster; + } + + /** + * Get the entity that caused the combustion event. + * + * @return the Entity that set the combustee alight. + */ + public Entity getCombuster() { + return combuster; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java b/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java new file mode 100644 index 0000000..43c4482 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity combusts. + *

          + * If an Entity Combust event is cancelled, the entity will not combust. + */ +public class EntityCombustEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private int duration; + private boolean cancel; + + public EntityCombustEvent(final Entity combustee, final int duration) { + super(combustee); + this.duration = duration; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * @return the amount of time (in seconds) the combustee should be alight + * for + */ + public int getDuration() { + return duration; + } + + /** + * The number of seconds the combustee should be alight for. + *

          + * This value will only ever increase the combustion time, not decrease + * existing combustion times. + * + * @param duration the time in seconds to be alight for. + */ + public void setDuration(int duration) { + this.duration = duration; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java b/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java new file mode 100644 index 0000000..286c206 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java @@ -0,0 +1,65 @@ +package org.bukkit.event.entity; + +import java.util.List; +import org.bukkit.PortalType; +import org.bukkit.block.BlockState; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a Living Entity creates a portal in a world. + */ +public class EntityCreatePortalEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final List blocks; + private boolean cancelled = false; + private PortalType type = PortalType.CUSTOM; + + public EntityCreatePortalEvent(final LivingEntity what, final List blocks, final PortalType type) { + super(what); + + this.blocks = blocks; + this.type = type; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets a list of all blocks associated with the portal. + * + * @return List of blocks that will be changed. + */ + public List getBlocks() { + return blocks; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Gets the type of portal that is trying to be created. + * + * @return Type of portal. + */ + public PortalType getPortalType() { + return type; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java b/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java new file mode 100644 index 0000000..49bf2a8 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java @@ -0,0 +1,38 @@ +package org.bukkit.event.entity; + +import java.util.Map; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; + +/** + * Called when an entity is damaged by a block + */ +public class EntityDamageByBlockEvent extends EntityDamageEvent { + private final Block damager; + + @Deprecated + public EntityDamageByBlockEvent(final Block damager, final Entity damagee, final DamageCause cause, final int damage) { + this(damager, damagee, cause, (double) damage); + } + + @Deprecated + public EntityDamageByBlockEvent(final Block damager, final Entity damagee, final DamageCause cause, final double damage) { + super(damagee, cause, damage); + this.damager = damager; + } + + public EntityDamageByBlockEvent(final Block damager, final Entity damagee, final DamageCause cause, final Map modifiers) { + super(damagee, cause, modifiers); + this.damager = damager; + } + + /** + * Returns the block that damaged the player. + * + * @return Block that damaged the player + */ + public Block getDamager() { + return damager; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java b/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java new file mode 100644 index 0000000..e7ea32f --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java @@ -0,0 +1,37 @@ +package org.bukkit.event.entity; + +import java.util.Map; + +import org.bukkit.entity.Entity; + +/** + * Called when an entity is damaged by an entity + */ +public class EntityDamageByEntityEvent extends EntityDamageEvent { + private final Entity damager; + + @Deprecated + public EntityDamageByEntityEvent(final Entity damager, final Entity damagee, final DamageCause cause, final int damage) { + this(damager, damagee, cause, (double) damage); + } + + @Deprecated + public EntityDamageByEntityEvent(final Entity damager, final Entity damagee, final DamageCause cause, final double damage) { + super(damagee, cause, damage); + this.damager = damager; + } + + public EntityDamageByEntityEvent(final Entity damager, final Entity damagee, final DamageCause cause, final Map modifiers) { + super(damagee, cause, modifiers); + this.damager = damager; + } + + /** + * Returns the entity that damaged the defender. + * + * @return Entity that damaged the defender. + */ + public Entity getDamager() { + return damager; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java b/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java new file mode 100644 index 0000000..17d9548 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java @@ -0,0 +1,374 @@ +package org.bukkit.event.entity; + +import java.util.EnumMap; +import java.util.Map; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.util.NumberConversions; + +import com.google.common.collect.ImmutableMap; + +/** + * Stores data for damage events + */ +public class EntityDamageEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private static final DamageModifier[] MODIFIERS = DamageModifier.values(); + private final Map modifiers; + private final Map originals; + private boolean cancelled; + private final DamageCause cause; + + @Deprecated + public EntityDamageEvent(final Entity damagee, final DamageCause cause, final int damage) { + this(damagee, cause, (double) damage); + } + + @Deprecated + public EntityDamageEvent(final Entity damagee, final DamageCause cause, final double damage) { + this(damagee, cause, new EnumMap(ImmutableMap.of(DamageModifier.BASE, damage))); + } + + public EntityDamageEvent(final Entity damagee, final DamageCause cause, final Map modifiers) { + super(damagee); + Validate.isTrue(modifiers.containsKey(DamageModifier.BASE), "BASE DamageModifier missing"); + Validate.isTrue(!modifiers.containsKey(null), "Cannot have null DamageModifier"); + this.originals = new EnumMap(modifiers); + this.cause = cause; + this.modifiers = modifiers; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + /** + * Gets the original damage for the specified modifier, as defined at this + * event's construction. + * + * @param type the modifier + * @throws IllegalArgumentException if type is null + */ + public double getOriginalDamage(DamageModifier type) throws IllegalArgumentException { + final Double damage = originals.get(type); + if (damage != null) { + return damage; + } + if (type == null) { + throw new IllegalArgumentException("Cannot have null DamageModifier"); + } + return 0; + } + + /** + * Sets the damage for the specified modifier. + * + * @param damage the scalar value of the damage's modifier + * @see #getFinalDamage() + * @throws IllegalArgumentException if type is null + * @throws UnsupportedOperationException if the caller does not support + * the particular DamageModifier, or to rephrase, when {@link + * #isApplicable(DamageModifier)} returns false + */ + public void setDamage(DamageModifier type, double damage) throws IllegalArgumentException, UnsupportedOperationException { + if (!modifiers.containsKey(type)) { + throw type == null ? new IllegalArgumentException("Cannot have null DamageModifier") : new UnsupportedOperationException(type + " is not applicable to " + getEntity()); + } + modifiers.put(type, damage); + } + + /** + * Gets the damage change for some modifier + * + * @return The raw amount of damage caused by the event + * @throws IllegalArgumentException if type is null + * @see DamageModifier#BASE + */ + public double getDamage(DamageModifier type) throws IllegalArgumentException { + Validate.notNull(type, "Cannot have null DamageModifier"); + final Double damage = modifiers.get(type); + return damage == null ? 0 : damage; + } + + /** + * This checks to see if a particular modifier is valid for this event's + * caller, such that, {@link #setDamage(DamageModifier, double)} will not + * throw an {@link UnsupportedOperationException}. + *

          + * {@link DamageModifier#BASE} is always applicable. + * + * @param type the modifier + * @return true if the modifier is supported by the caller, false otherwise + * @throws IllegalArgumentException if type is null + */ + public boolean isApplicable(DamageModifier type) throws IllegalArgumentException { + Validate.notNull(type, "Cannot have null DamageModifier"); + return modifiers.containsKey(type); + } + + /** + * Gets the raw amount of damage caused by the event + * + * @return The raw amount of damage caused by the event + * @see DamageModifier#BASE + */ + public double getDamage() { + return getDamage(DamageModifier.BASE); + } + + /** + * Gets the amount of damage caused by the event after all damage + * reduction is applied. + * + * @return the amount of damage caused by the event + */ + public final double getFinalDamage() { + double damage = 0; + for (DamageModifier modifier : MODIFIERS) { + damage += getDamage(modifier); + } + return damage; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public int _INVALID_getDamage() { + return NumberConversions.ceil(getDamage()); + } + + /** + * Sets the raw amount of damage caused by the event + * + * @param damage The raw amount of damage caused by the event + */ + public void setDamage(double damage) { + setDamage(DamageModifier.BASE, damage); + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public void _INVALID_setDamage(int damage) { + setDamage(damage); + } + + /** + * Gets the cause of the damage. + * + * @return A DamageCause value detailing the cause of the damage. + */ + public DamageCause getCause() { + return cause; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the types of modifier + */ + public enum DamageModifier { + /** + * This represents the amount of damage being done, also known as the + * raw {@link EntityDamageEvent#getDamage()}. + */ + BASE, + /** + * This represents the damage reduced by a wearing a helmet when hit + * by a falling block. + */ + HARD_HAT, + /** + * This represents the damage reduction caused by blocking, only present for + * {@link Player Players}. + */ + BLOCKING, + /** + * This represents the damage reduction caused by wearing armor. + */ + ARMOR, + /** + * This represents the damage reduction caused by the Resistance potion effect. + */ + RESISTANCE, + /** + * This represents the damage reduction caused by the combination of: + *

            + *
          • + * Armor enchantments + *
          • + * Witch's potion resistance + *
          • + *
          + */ + MAGIC, + /** + * This represents the damage reduction caused by the absorption potion + * effect. + */ + ABSORPTION, + ; + } + + /** + * An enum to specify the cause of the damage + */ + public enum DamageCause { + + /** + * Damage caused when an entity contacts a block such as a Cactus. + *

          + * Damage: 1 (Cactus) + */ + CONTACT, + /** + * Damage caused when an entity attacks another entity. + *

          + * Damage: variable + */ + ENTITY_ATTACK, + /** + * Damage caused when attacked by a projectile. + *

          + * Damage: variable + */ + PROJECTILE, + /** + * Damage caused by being put in a block + *

          + * Damage: 1 + */ + SUFFOCATION, + /** + * Damage caused when an entity falls a distance greater than 3 blocks + *

          + * Damage: fall height - 3.0 + */ + FALL, + /** + * Damage caused by direct exposure to fire + *

          + * Damage: 1 + */ + FIRE, + /** + * Damage caused due to burns caused by fire + *

          + * Damage: 1 + */ + FIRE_TICK, + /** + * Damage caused due to a snowman melting + *

          + * Damage: 1 + */ + MELTING, + /** + * Damage caused by direct exposure to lava + *

          + * Damage: 4 + */ + LAVA, + /** + * Damage caused by running out of air while in water + *

          + * Damage: 2 + */ + DROWNING, + /** + * Damage caused by being in the area when a block explodes. + *

          + * Damage: variable + */ + BLOCK_EXPLOSION, + /** + * Damage caused by being in the area when an entity, such as a + * Creeper, explodes. + *

          + * Damage: variable + */ + ENTITY_EXPLOSION, + /** + * Damage caused by falling into the void + *

          + * Damage: 4 for players + */ + VOID, + /** + * Damage caused by being struck by lightning + *

          + * Damage: 5 + */ + LIGHTNING, + /** + * Damage caused by committing suicide using the command "/kill" + *

          + * Damage: 1000 + */ + SUICIDE, + /** + * Damage caused by starving due to having an empty hunger bar + *

          + * Damage: 1 + */ + STARVATION, + /** + * Damage caused due to an ongoing poison effect + *

          + * Damage: 1 + */ + POISON, + /** + * Damage caused by being hit by a damage potion or spell + *

          + * Damage: variable + */ + MAGIC, + /** + * Damage caused by Wither potion effect + */ + WITHER, + /** + * Damage caused by being hit by a falling block which deals damage + *

          + * Note: Not every block deals damage + *

          + * Damage: variable + */ + FALLING_BLOCK, + /** + * Damage caused in retaliation to another attack by the Thorns + * enchantment. + *

          + * Damage: 1-4 (Thorns) + */ + THORNS, + /** + * Custom damage. + *

          + * Damage: variable + */ + CUSTOM + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java b/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java new file mode 100644 index 0000000..ab9e81f --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java @@ -0,0 +1,72 @@ +package org.bukkit.event.entity; + +import java.util.List; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Thrown whenever a LivingEntity dies + */ +public class EntityDeathEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + private final List drops; + private int dropExp = 0; + + public EntityDeathEvent(final LivingEntity entity, final List drops) { + this(entity, drops, 0); + } + + public EntityDeathEvent(final LivingEntity what, final List drops, final int droppedExp) { + super(what); + this.drops = drops; + this.dropExp = droppedExp; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets how much EXP should be dropped from this death. + *

          + * This does not indicate how much EXP should be taken from the entity in + * question, merely how much should be created after its death. + * + * @return Amount of EXP to drop. + */ + public int getDroppedExp() { + return dropExp; + } + + /** + * Sets how much EXP should be dropped from this death. + *

          + * This does not indicate how much EXP should be taken from the entity in + * question, merely how much should be created after its death. + * + * @param exp Amount of EXP to drop. + */ + public void setDroppedExp(int exp) { + this.dropExp = exp; + } + + /** + * Gets all the items which will drop when the entity dies + * + * @return Items to drop when the entity dies + */ + public List getDrops() { + return drops; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityEvent.java b/src/main/java/org/bukkit/event/entity/EntityEvent.java new file mode 100644 index 0000000..c9a4ab3 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.Event; + +/** + * Represents an Entity-related event + */ +public abstract class EntityEvent extends Event { + protected Entity entity; + + public EntityEvent(final Entity what) { + entity = what; + } + + /** + * Returns the Entity involved in this event + * + * @return Entity who is involved in this event + */ + public Entity getEntity() { + return entity; + } + + /** + * Gets the EntityType of the Entity involved in this event. + * + * @return EntityType of the Entity involved in this event + */ + public EntityType getEntityType() { + return entity.getType(); + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java b/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java new file mode 100644 index 0000000..287035d --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java @@ -0,0 +1,85 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.List; + +/** + * Called when an entity explodes + */ +public class EntityExplodeEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private final Location location; + private final List blocks; + private float yield; + + public EntityExplodeEvent(final Entity what, final Location location, final List blocks, final float yield) { + super(what); + this.location = location; + this.blocks = blocks; + this.yield = yield; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Returns the list of blocks that would have been removed or were removed + * from the explosion event. + * + * @return All blown-up blocks + */ + public List blockList() { + return blocks; + } + + /** + * Returns the location where the explosion happened. + *

          + * It is not possible to get this value from the Entity as the Entity no + * longer exists in the world. + * + * @return The location of the explosion + */ + public Location getLocation() { + return location; + } + + /** + * Returns the percentage of blocks to drop from this explosion + * + * @return The yield. + */ + public float getYield() { + return yield; + } + + /** + * Sets the percentage of blocks to drop from this explosion + * + * @param yield The new yield percentage + */ + public void setYield(float yield) { + this.yield = yield; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java b/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java new file mode 100644 index 0000000..1c4e100 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.entity; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity interacts with an object + */ +public class EntityInteractEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected Block block; + private boolean cancelled; + + public EntityInteractEvent(final Entity entity, final Block block) { + super(entity); + this.block = block; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + /** + * Returns the involved block + * + * @return the block clicked with this item. + */ + public Block getBlock() { + return block; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java b/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java new file mode 100644 index 0000000..87d57b0 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.Location; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity comes into contact with a portal + */ +public class EntityPortalEnterEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + private final Location location; + + public EntityPortalEnterEvent(final Entity entity, final Location location) { + super(entity); + this.location = location; + } + + /** + * Gets the portal block the entity is touching + * + * @return The portal block the entity is touching + */ + public Location getLocation() { + return location; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java b/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java new file mode 100644 index 0000000..835c054 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java @@ -0,0 +1,82 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.TravelAgent; +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; + +/** + * Called when a non-player entity is about to teleport because it is in + * contact with a portal. + *

          + * For players see {@link org.bukkit.event.player.PlayerPortalEvent} + */ +public class EntityPortalEvent extends EntityTeleportEvent { + private static final HandlerList handlers = new HandlerList(); + protected boolean useTravelAgent = true; + protected TravelAgent travelAgent; + + public EntityPortalEvent(final Entity entity, final Location from, final Location to, final TravelAgent pta) { + super(entity, from, to); + this.travelAgent = pta; + } + + /** + * Sets whether or not the Travel Agent will be used. + *

          + * If this is set to true, the TravelAgent will try to find a Portal at + * the {@link #getTo()} Location, and will try to create one if there is + * none. + *

          + * If this is set to false, the {@link #getEntity()} will only be + * teleported to the {@link #getTo()} Location. + * + * @param useTravelAgent whether to use the Travel Agent + */ + public void useTravelAgent(boolean useTravelAgent) { + this.useTravelAgent = useTravelAgent; + } + + /** + * Gets whether or not the Travel Agent will be used. + *

          + * If this is set to true, the TravelAgent will try to find a Portal at + * the {@link #getTo()} Location, and will try to create one if there is + * none. + *

          + * If this is set to false, the {@link #getEntity()} will only be + * teleported to the {@link #getTo()} Location. + * + * @return whether to use the Travel Agent + */ + public boolean useTravelAgent() { + return useTravelAgent; + } + + /** + * Gets the Travel Agent used (or not) in this event. + * + * @return the Travel Agent used (or not) in this event + */ + public TravelAgent getPortalTravelAgent() { + return this.travelAgent; + } + + /** + * Sets the Travel Agent used (or not) in this event. + * + * @param travelAgent the Travel Agent used (or not) in this event + */ + public void setPortalTravelAgent(TravelAgent travelAgent) { + this.travelAgent = travelAgent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java b/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java new file mode 100644 index 0000000..682fe59 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java @@ -0,0 +1,60 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; +import org.bukkit.util.Vector; + +/** + * Called before an entity exits a portal. + *

          + * This event allows you to modify the velocity of the entity after they have + * successfully exited the portal. + */ +public class EntityPortalExitEvent extends EntityTeleportEvent { + private static final HandlerList handlers = new HandlerList(); + private Vector before; + private Vector after; + + public EntityPortalExitEvent(final Entity entity, final Location from, final Location to, final Vector before, final Vector after) { + super(entity, from, to); + this.before = before; + this.after = after; + } + + /** + * Gets a copy of the velocity that the entity has before entering the + * portal. + * + * @return velocity of entity before entering portal + */ + public Vector getBefore() { + return this.before.clone(); + } + + /** + * Gets a copy of the velocity that the entity will have after exiting the + * portal. + * + * @return velocity of entity after exiting portal + */ + public Vector getAfter() { + return this.after.clone(); + } + + /** + * Sets the velocity that the entity will have after exiting the portal. + */ + public void setAfter(Vector after) { + this.after = after.clone(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java b/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java new file mode 100644 index 0000000..b4291b0 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java @@ -0,0 +1,137 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.util.NumberConversions; + +/** + * Stores data for health-regain events + */ +public class EntityRegainHealthEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private double amount; + private final RegainReason regainReason; + + @Deprecated + public EntityRegainHealthEvent(final Entity entity, final int amount, final RegainReason regainReason) { + this(entity, (double) amount, regainReason); + } + + public EntityRegainHealthEvent(final Entity entity, final double amount, final RegainReason regainReason) { + super(entity); + this.amount = amount; + this.regainReason = regainReason; + } + + /** + * Gets the amount of regained health + * + * @return The amount of health regained + */ + public double getAmount() { + return amount; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public int _INVALID_getAmount() { + return NumberConversions.ceil(getAmount()); + } + + /** + * Sets the amount of regained health + * + * @param amount the amount of health the entity will regain + */ + public void setAmount(double amount) { + this.amount = amount; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public void _INVALID_setAmount(int amount) { + setAmount(amount); + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + /** + * Gets the reason for why the entity is regaining health + * + * @return A RegainReason detailing the reason for the entity regaining + * health + */ + public RegainReason getRegainReason() { + return regainReason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the type of health regaining that is occurring + */ + public enum RegainReason { + + /** + * When a player regains health from regenerating due to Peaceful mode + * (difficulty=0) + */ + REGEN, + /** + * When a player regains health from regenerating due to their hunger + * being satisfied + */ + SATIATED, + /** + * When a player regains health from eating consumables + */ + EATING, + /** + * When an ender dragon regains health from an ender crystal + */ + ENDER_CRYSTAL, + /** + * When a player is healed by a potion or spell + */ + MAGIC, + /** + * When a player is healed over time by a potion or spell + */ + MAGIC_REGEN, + /** + * When a wither is filling its health during spawning + */ + WITHER_SPAWN, + /** + * When an entity is damaged by the Wither potion effect + */ + WITHER, + /** + * Any other reason not covered by the reasons above + */ + CUSTOM + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java b/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java new file mode 100644 index 0000000..f8c91a1 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java @@ -0,0 +1,84 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a LivingEntity shoots a bow firing an arrow + */ +public class EntityShootBowEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final ItemStack bow; + private Entity projectile; + private final float force; + private boolean cancelled; + + public EntityShootBowEvent(final LivingEntity shooter, final ItemStack bow, final Projectile projectile, final float force) { + super(shooter); + this.bow = bow; + this.projectile = projectile; + this.force = force; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets the bow ItemStack used to fire the arrow. + * + * @return the bow involved in this event + */ + public ItemStack getBow() { + return bow; + } + + /** + * Gets the projectile which will be launched by this event + * + * @return the launched projectile + */ + public Entity getProjectile() { + return projectile; + } + + /** + * Replaces the projectile which will be launched + * + * @param projectile the new projectile + */ + public void setProjectile(Entity projectile) { + this.projectile = projectile; + } + + /** + * Gets the force the arrow was launched with + * + * @return bow shooting force, up to 1.0 + */ + public float getForce() { + return force; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityTameEvent.java b/src/main/java/org/bukkit/event/entity/EntityTameEvent.java new file mode 100644 index 0000000..f105817 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityTameEvent.java @@ -0,0 +1,51 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a LivingEntity is tamed + */ +public class EntityTameEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final AnimalTamer owner; + + public EntityTameEvent(final LivingEntity entity, final AnimalTamer owner) { + super(entity); + this.owner = owner; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + /** + * Gets the owning AnimalTamer + * + * @return the owning AnimalTamer + */ + public AnimalTamer getOwner() { + return owner; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java b/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java new file mode 100644 index 0000000..1f7af4d --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java @@ -0,0 +1,141 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a creature targets or untargets another entity + */ +public class EntityTargetEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private Entity target; + private final TargetReason reason; + + public EntityTargetEvent(final Entity entity, final Entity target, final TargetReason reason) { + super(entity); + this.target = target; + this.reason = reason; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Returns the reason for the targeting + * + * @return The reason + */ + public TargetReason getReason() { + return reason; + } + + /** + * Get the entity that this is targeting. + *

          + * This will be null in the case that the event is called when the mob + * forgets its target. + * + * @return The entity + */ + public Entity getTarget() { + return target; + } + + /** + * Set the entity that you want the mob to target instead. + *

          + * It is possible to be null, null will cause the entity to be + * target-less. + *

          + * This is different from cancelling the event. Cancelling the event will + * cause the entity to keep an original target, while setting to be null + * will cause the entity to be reset. + * + * @param target The entity to target + */ + public void setTarget(Entity target) { + this.target = target; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the reason for the targeting + */ + public enum TargetReason { + + /** + * When the entity's target has died, and so it no longer targets it + */ + TARGET_DIED, + /** + * When the entity doesn't have a target, so it attacks the nearest + * player + */ + CLOSEST_PLAYER, + /** + * When the target attacks the entity, so entity targets it + */ + TARGET_ATTACKED_ENTITY, + /** + * When the target attacks a fellow pig zombie, so the whole group + * will target him with this reason. + */ + PIG_ZOMBIE_TARGET, + /** + * When the target is forgotten for whatever reason. + *

          + * Currently only occurs in with spiders when there is a high + * brightness. + */ + FORGOT_TARGET, + /** + * When the target attacks the owner of the entity, so the entity + * targets it. + */ + TARGET_ATTACKED_OWNER, + /** + * When the owner of the entity attacks the target attacks, so the + * entity targets it. + */ + OWNER_ATTACKED_TARGET, + /** + * When the entity has no target, so the entity randomly chooses one. + */ + RANDOM_TARGET, + /** + * When an entity selects a target while defending a village. + */ + DEFEND_VILLAGE, + /** + * When the target attacks a nearby entity of the same type, so the entity targets it + */ + TARGET_ATTACKED_NEARBY_ENTITY, + /** + * When a zombie targeting an entity summons reinforcements, so the reinforcements target the same entity + */ + REINFORCEMENT_TARGET, + /** + * When an entity targets another entity after colliding with it. + */ + COLLISION, + /** + * For custom calls to the event. + */ + CUSTOM + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java b/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java new file mode 100644 index 0000000..cd9aea1 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; + +/** + * Called when an Entity targets a {@link LivingEntity} and can only target + * LivingEntity's. + */ +public class EntityTargetLivingEntityEvent extends EntityTargetEvent{ + public EntityTargetLivingEntityEvent(final Entity entity, final LivingEntity target, final TargetReason reason) { + super(entity, target, reason); + } + + public LivingEntity getTarget() { + return (LivingEntity) super.getTarget(); + } + + /** + * Set the Entity that you want the mob to target. + *

          + * It is possible to be null, null will cause the entity to be + * target-less. + *

          + * Must be a LivingEntity, or null. + * + * @param target The entity to target + */ + public void setTarget(Entity target) { + if (target == null || target instanceof LivingEntity) { + super.setTarget(target); + } + } +} diff --git a/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java b/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java new file mode 100644 index 0000000..619f8d4 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java @@ -0,0 +1,77 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a non-player entity (such as an Enderman) tries to teleport + * from one location to another. + */ +public class EntityTeleportEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private Location from; + private Location to; + + public EntityTeleportEvent(Entity what, Location from, Location to) { + super(what); + this.from = from; + this.to = to; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the location that this entity moved from + * + * @return Location this entity moved from + */ + public Location getFrom() { + return from; + } + + /** + * Sets the location that this entity moved from + * + * @param from New location this entity moved from + */ + public void setFrom(Location from) { + this.from = from; + } + + /** + * Gets the location that this entity moved to + * + * @return Location the entity moved to + */ + public Location getTo() { + return to; + } + + /** + * Sets the location that this entity moved to + * + * @param to New Location this entity moved to + */ + public void setTo(Location to) { + this.to = to; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java b/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java new file mode 100644 index 0000000..da7e46c --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java @@ -0,0 +1,52 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; + +/** + * Called immediately prior to an entity being unleashed. + */ +public class EntityUnleashEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + private final UnleashReason reason; + + public EntityUnleashEvent(Entity entity, UnleashReason reason) { + super(entity); + this.reason = reason; + } + + /** + * Returns the reason for the unleashing. + * + * @return The reason + */ + public UnleashReason getReason() { + return reason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public enum UnleashReason { + /** + * When the entity's leashholder has died or logged out, and so is + * unleashed + */ + HOLDER_GONE, + /** + * When the entity's leashholder attempts to unleash it + */ + PLAYER_UNLEASH, + /** + * When the entity's leashholder is more than 10 blocks away + */ + DISTANCE, + UNKNOWN; + } +} diff --git a/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java b/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java new file mode 100644 index 0000000..4f64424 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java @@ -0,0 +1,75 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.ThrownExpBottle; +import org.bukkit.event.HandlerList; + +/** + * Called when a ThrownExpBottle hits and releases experience. + */ +public class ExpBottleEvent extends ProjectileHitEvent { + private static final HandlerList handlers = new HandlerList(); + private int exp; + private boolean showEffect = true; + + public ExpBottleEvent(final ThrownExpBottle bottle, final int exp) { + super(bottle); + this.exp = exp; + } + + @Override + public ThrownExpBottle getEntity() { + return (ThrownExpBottle) entity; + } + + /** + * This method indicates if the particle effect should be shown. + * + * @return true if the effect will be shown, false otherwise + */ + public boolean getShowEffect() { + return this.showEffect; + } + + /** + * This method sets if the particle effect will be shown. + *

          + * This does not change the experience created. + * + * @param showEffect true indicates the effect will be shown, false + * indicates no effect will be shown + */ + public void setShowEffect(final boolean showEffect) { + this.showEffect = showEffect; + } + + /** + * This method retrieves the amount of experience to be created. + *

          + * The number indicates a total amount to be divided into orbs. + * + * @return the total amount of experience to be created + */ + public int getExperience() { + return exp; + } + + /** + * This method sets the amount of experience to be created. + *

          + * The number indicates a total amount to be divided into orbs. + * + * @param exp the total amount of experience to be created + */ + public void setExperience(final int exp) { + this.exp = exp; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java b/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java new file mode 100644 index 0000000..7ca6a55 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java @@ -0,0 +1,80 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Explosive; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity has made a decision to explode. + */ +public class ExplosionPrimeEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private float radius; + private boolean fire; + + public ExplosionPrimeEvent(final Entity what, final float radius, final boolean fire) { + super(what); + this.cancel = false; + this.radius = radius; + this.fire = fire; + } + + public ExplosionPrimeEvent(final Explosive explosive) { + this(explosive, explosive.getYield(), explosive.isIncendiary()); + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the radius of the explosion + * + * @return returns the radius of the explosion + */ + public float getRadius() { + return radius; + } + + /** + * Sets the radius of the explosion + * + * @param radius the radius of the explosion + */ + public void setRadius(float radius) { + this.radius = radius; + } + + /** + * Gets whether this explosion will create fire or not + * + * @return true if this explosion will create fire + */ + public boolean getFire() { + return fire; + } + + /** + * Sets whether this explosion will create fire or not + * + * @param fire true if you want this explosion to create fire + */ + public void setFire(boolean fire) { + this.fire = fire; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java b/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java new file mode 100644 index 0000000..f6e2472 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java @@ -0,0 +1,67 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a human entity's food level changes + */ +public class FoodLevelChangeEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private int level; + + public FoodLevelChangeEvent(final HumanEntity what, final int level) { + super(what); + this.level = level; + } + + @Override + public HumanEntity getEntity() { + return (HumanEntity) entity; + } + + /** + * Gets the resultant food level that the entity involved in this event + * should be set to. + *

          + * Where 20 is a full food bar and 0 is an empty one. + * + * @return The resultant food level + */ + public int getFoodLevel() { + return level; + } + + /** + * Sets the resultant food level that the entity involved in this event + * should be set to + * + * @param level the resultant food level that the entity involved in this + * event should be set to + */ + public void setFoodLevel(int level) { + if (level > 20) level = 20; + else if (level < 0) level = 0; + + this.level = level; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java b/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java new file mode 100644 index 0000000..fad2468 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java @@ -0,0 +1,78 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Horse; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a horse jumps. + */ +public class HorseJumpEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private float power; + + public HorseJumpEvent(final Horse horse, final float power) { + super(horse); + this.power = power; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public Horse getEntity() { + return (Horse) entity; + } + + /** + * Gets the power of the jump. + *

          + * Power is a value that defines how much of the horse's jump strength + * should be used for the jump. Power is effectively multiplied times + * the horse's jump strength to determine how high the jump is; 0 + * represents no jump strength while 1 represents full jump strength. + * Setting power to a value above 1 will use additional jump strength + * that the horse does not usually have. + *

          + * Power does not affect how high the horse is capable of jumping, only + * how much of its jumping capability will be used in this jump. To set + * the horse's overall jump strength, see {@link + * Horse#setJumpStrength(double)}. + * + * @return jump strength + */ + public float getPower() { + return power; + } + + /** + * Sets the power of the jump. + *

          + * Jump power can be set to a value above 1.0 which will increase the + * strength of this jump above the horse's actual jump strength. + *

          + * Setting the jump power to 0 will result in the jump animation still + * playing, but the horse not leaving the ground. Only canceling this + * event will result in no jump animation at all. + * + * @param power power of the jump + */ + public void setPower(float power) { + this.power = power; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java b/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java new file mode 100644 index 0000000..356e4bd --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java @@ -0,0 +1,55 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Item; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * This event is called when a {@link org.bukkit.entity.Item} is removed from + * the world because it has existed for 5 minutes. + *

          + * Cancelling the event results in the item being allowed to exist for 5 more + * minutes. This behavior is not guaranteed and may change in future versions. + */ +public class ItemDespawnEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final Location location; + + public ItemDespawnEvent(final Item despawnee, final Location loc) { + super(despawnee); + location = loc; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + @Override + public Item getEntity() { + return (Item) entity; + } + + /** + * Gets the location at which the item is despawning. + * + * @return The location at which the item is despawning + */ + public Location getLocation() { + return location; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java b/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java new file mode 100644 index 0000000..bafd934 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java @@ -0,0 +1,51 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Item; +import org.bukkit.Location; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when an item is spawned into a world + */ +public class ItemSpawnEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Location location; + private boolean canceled; + + public ItemSpawnEvent(final Item spawnee, final Location loc) { + super(spawnee); + this.location = loc; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + @Override + public Item getEntity() { + return (Item) entity; + } + + /** + * Gets the location at which the item is spawning. + * + * @return The location at which the item is spawning + */ + public Location getLocation() { + return location; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/PigZapEvent.java b/src/main/java/org/bukkit/event/entity/PigZapEvent.java new file mode 100644 index 0000000..aa80ebf --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/PigZapEvent.java @@ -0,0 +1,64 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.LightningStrike; +import org.bukkit.entity.Pig; +import org.bukkit.entity.PigZombie; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Stores data for pigs being zapped + */ +public class PigZapEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final PigZombie pigzombie; + private final LightningStrike bolt; + + public PigZapEvent(final Pig pig, final LightningStrike bolt, final PigZombie pigzombie) { + super(pig); + this.bolt = bolt; + this.pigzombie = pigzombie; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + @Override + public Pig getEntity() { + return (Pig) entity; + } + + /** + * Gets the bolt which is striking the pig. + * + * @return lightning entity + */ + public LightningStrike getLightning() { + return bolt; + } + + /** + * Gets the zombie pig that will replace the pig, provided the event is + * not cancelled first. + * + * @return resulting entity + */ + public PigZombie getPigZombie() { + return pigzombie; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java b/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java new file mode 100644 index 0000000..b773d6e --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java @@ -0,0 +1,138 @@ +package org.bukkit.event.entity; + +import java.util.List; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +/** + * Thrown whenever a {@link Player} dies + */ +public class PlayerDeathEvent extends EntityDeathEvent { + private int newExp = 0; + private String deathMessage = ""; + private int newLevel = 0; + private int newTotalExp = 0; + private boolean keepLevel = false; + + public PlayerDeathEvent(final Player player, final List drops, final int droppedExp, final String deathMessage) { + this(player, drops, droppedExp, 0, deathMessage); + } + + public PlayerDeathEvent(final Player player, final List drops, final int droppedExp, final int newExp, final String deathMessage) { + this(player, drops, droppedExp, newExp, 0, 0, deathMessage); + } + + public PlayerDeathEvent(final Player player, final List drops, final int droppedExp, final int newExp, final int newTotalExp, final int newLevel, final String deathMessage) { + super(player, drops, droppedExp); + this.newExp = newExp; + this.newTotalExp = newTotalExp; + this.newLevel = newLevel; + this.deathMessage = deathMessage; + } + + @Override + public Player getEntity() { + return (Player) entity; + } + + /** + * Set the death message that will appear to everyone on the server. + * + * @param deathMessage Message to appear to other players on the server. + */ + public void setDeathMessage(String deathMessage) { + this.deathMessage = deathMessage; + } + + /** + * Get the death message that will appear to everyone on the server. + * + * @return Message to appear to other players on the server. + */ + public String getDeathMessage() { + return deathMessage; + } + + /** + * Gets how much EXP the Player should have at respawn. + *

          + * This does not indicate how much EXP should be dropped, please see + * {@link #getDroppedExp()} for that. + * + * @return New EXP of the respawned player + */ + public int getNewExp() { + return newExp; + } + + /** + * Sets how much EXP the Player should have at respawn. + *

          + * This does not indicate how much EXP should be dropped, please see + * {@link #setDroppedExp(int)} for that. + * + * @param exp New EXP of the respawned player + */ + public void setNewExp(int exp) { + newExp = exp; + } + + /** + * Gets the Level the Player should have at respawn. + * + * @return New Level of the respawned player + */ + public int getNewLevel() { + return newLevel; + } + + /** + * Sets the Level the Player should have at respawn. + * + * @param level New Level of the respawned player + */ + public void setNewLevel(int level) { + newLevel = level; + } + + /** + * Gets the Total EXP the Player should have at respawn. + * + * @return New Total EXP of the respawned player + */ + public int getNewTotalExp() { + return newTotalExp; + } + + /** + * Sets the Total EXP the Player should have at respawn. + * + * @param totalExp New Total EXP of the respawned player + */ + public void setNewTotalExp(int totalExp) { + newTotalExp = totalExp; + } + + /** + * Gets if the Player should keep all EXP at respawn. + *

          + * This flag overrides other EXP settings + * + * @return True if Player should keep all pre-death exp + */ + public boolean getKeepLevel() { + return keepLevel; + } + + /** + * Sets if the Player should keep all EXP at respawn. + *

          + * This overrides all other EXP settings + * + * @param keepLevel True to keep all current value levels + */ + public void setKeepLevel(boolean keepLevel) { + this.keepLevel = keepLevel; + } +} diff --git a/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java b/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java new file mode 100644 index 0000000..74d458a --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java @@ -0,0 +1,68 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called immediately prior to a creature being leashed by a player. + */ +public class PlayerLeashEntityEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity leashHolder; + private final Entity entity; + private boolean cancelled = false; + private final Player player; + + public PlayerLeashEntityEvent(Entity what, Entity leashHolder, Player leasher) { + this.leashHolder = leashHolder; + this.entity = what; + this.player = leasher; + } + + /** + * Returns the entity that is holding the leash. + * + * @return The leash holder + */ + public Entity getLeashHolder() { + return leashHolder; + } + + /** + * Returns the entity being leashed. + * + * @return The entity + */ + public Entity getEntity() { + return entity; + } + + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final Player getPlayer() { + return player; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} diff --git a/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java b/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java new file mode 100644 index 0000000..b9840de --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java @@ -0,0 +1,94 @@ +package org.bukkit.event.entity; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.ThrownPotion; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a splash potion hits an area + */ +public class PotionSplashEvent extends ProjectileHitEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Map affectedEntities; + + public PotionSplashEvent(final ThrownPotion potion, final Map affectedEntities) { + super(potion); + + this.affectedEntities = affectedEntities; + } + + @Override + public ThrownPotion getEntity() { + return (ThrownPotion) entity; + } + + /** + * Gets the potion which caused this event + * + * @return The thrown potion entity + */ + public ThrownPotion getPotion() { + return (ThrownPotion) getEntity(); + } + + /** + * Retrieves a list of all effected entities + * + * @return A fresh copy of the affected entity list + */ + public Collection getAffectedEntities() { + return new ArrayList(affectedEntities.keySet()); + } + + /** + * Gets the intensity of the potion's effects for given entity; This + * depends on the distance to the impact center + * + * @param entity Which entity to get intensity for + * @return intensity relative to maximum effect; 0.0: not affected; 1.0: + * fully hit by potion effects + */ + public double getIntensity(LivingEntity entity) { + Double intensity = affectedEntities.get(entity); + return intensity != null ? intensity : 0.0; + } + + /** + * Overwrites the intensity for a given entity + * + * @param entity For which entity to define a new intensity + * @param intensity relative to maximum effect + */ + public void setIntensity(LivingEntity entity, double intensity) { + Validate.notNull(entity, "You must specify a valid entity."); + if (intensity <= 0.0) { + affectedEntities.remove(entity); + } else { + affectedEntities.put(entity, Math.min(intensity, 1.0)); + } + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java b/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java new file mode 100644 index 0000000..25ae832 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java @@ -0,0 +1,30 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Projectile; +import org.bukkit.event.HandlerList; + +/** + * Called when a projectile hits an object + */ +public class ProjectileHitEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + + public ProjectileHitEvent(final Projectile projectile) { + super(projectile); + } + + @Override + public Projectile getEntity() { + return (Projectile) entity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java b/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java new file mode 100644 index 0000000..0c9190c --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java @@ -0,0 +1,40 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a projectile is launched. + */ +public class ProjectileLaunchEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + + public ProjectileLaunchEvent(Entity what) { + super(what); + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public Projectile getEntity() { + return (Projectile) entity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java b/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java new file mode 100644 index 0000000..4c17fea --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java @@ -0,0 +1,62 @@ +package org.bukkit.event.entity; + +import org.bukkit.DyeColor; +import org.bukkit.entity.Sheep; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a sheep's wool is dyed + */ +public class SheepDyeWoolEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private DyeColor color; + + public SheepDyeWoolEvent(final Sheep sheep, final DyeColor color) { + super(sheep); + this.cancel = false; + this.color = color; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public Sheep getEntity() { + return (Sheep) entity; + } + + /** + * Gets the DyeColor the sheep is being dyed + * + * @return the DyeColor the sheep is being dyed + */ + public DyeColor getColor() { + return color; + } + + /** + * Sets the DyeColor the sheep is being dyed + * + * @param color the DyeColor the sheep will be dyed + */ + public void setColor(DyeColor color) { + this.color = color; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java b/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java new file mode 100644 index 0000000..e836f7b --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java @@ -0,0 +1,41 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Sheep; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a sheep regrows its wool + */ +public class SheepRegrowWoolEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + + public SheepRegrowWoolEvent(final Sheep sheep) { + super(sheep); + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public Sheep getEntity() { + return (Sheep) entity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java b/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java new file mode 100644 index 0000000..4b99587 --- /dev/null +++ b/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Slime; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a Slime splits into smaller Slimes upon death + */ +public class SlimeSplitEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private int count; + + public SlimeSplitEvent(final Slime slime, final int count) { + super(slime); + this.count = count; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public Slime getEntity() { + return (Slime) entity; + } + + /** + * Gets the amount of smaller slimes to spawn + * + * @return the amount of slimes to spawn + */ + public int getCount() { + return count; + } + + /** + * Sets how many smaller slimes will spawn on the split + * + * @param count the amount of slimes to spawn + */ + public void setCount(int count) { + this.count = count; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java b/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java new file mode 100644 index 0000000..80851ed --- /dev/null +++ b/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java @@ -0,0 +1,25 @@ +package org.bukkit.event.hanging; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Hanging; + +/** + * Triggered when a hanging entity is removed by an entity + */ +public class HangingBreakByEntityEvent extends HangingBreakEvent { + private final Entity remover; + + public HangingBreakByEntityEvent(final Hanging hanging, final Entity remover) { + super(hanging, HangingBreakEvent.RemoveCause.ENTITY); + this.remover = remover; + } + + /** + * Gets the entity that removed the hanging entity + * + * @return the entity that removed the hanging entity + */ + public Entity getRemover() { + return remover; + } +} diff --git a/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java b/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java new file mode 100644 index 0000000..87bbdcb --- /dev/null +++ b/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java @@ -0,0 +1,71 @@ +package org.bukkit.event.hanging; + +import org.bukkit.entity.Hanging; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Triggered when a hanging entity is removed + */ +public class HangingBreakEvent extends HangingEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final HangingBreakEvent.RemoveCause cause; + + public HangingBreakEvent(final Hanging hanging, final HangingBreakEvent.RemoveCause cause) { + super(hanging); + this.cause = cause; + } + + /** + * Gets the cause for the hanging entity's removal + * + * @return the RemoveCause for the hanging entity's removal + */ + public HangingBreakEvent.RemoveCause getCause() { + return cause; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * An enum to specify the cause of the removal + */ + public enum RemoveCause { + /** + * Removed by an entity + */ + ENTITY, + /** + * Removed by an explosion + */ + EXPLOSION, + /** + * Removed by placing a block on it + */ + OBSTRUCTION, + /** + * Removed by destroying the block behind it, etc + */ + PHYSICS, + /** + * Removed by an uncategorised cause + */ + DEFAULT, + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/hanging/HangingEvent.java b/src/main/java/org/bukkit/event/hanging/HangingEvent.java new file mode 100644 index 0000000..b370afe --- /dev/null +++ b/src/main/java/org/bukkit/event/hanging/HangingEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.hanging; + +import org.bukkit.entity.Hanging; +import org.bukkit.event.Event; + +/** + * Represents a hanging entity-related event. + */ +public abstract class HangingEvent extends Event { + protected Hanging hanging; + + protected HangingEvent(final Hanging painting) { + this.hanging = painting; + } + + /** + * Gets the hanging entity involved in this event. + * + * @return the hanging entity + */ + public Hanging getEntity() { + return hanging; + } +} diff --git a/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java b/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java new file mode 100644 index 0000000..b511c55 --- /dev/null +++ b/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java @@ -0,0 +1,70 @@ +package org.bukkit.event.hanging; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Hanging; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Triggered when a hanging entity is created in the world + */ +public class HangingPlaceEvent extends HangingEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Player player; + private final Block block; + private final BlockFace blockFace; + + public HangingPlaceEvent(final Hanging hanging, final Player player, final Block block, final BlockFace blockFace) { + super(hanging); + this.player = player; + this.block = block; + this.blockFace = blockFace; + } + + /** + * Returns the player placing the hanging entity + * + * @return the player placing the hanging entity + */ + public Player getPlayer() { + return player; + } + + /** + * Returns the block that the hanging entity was placed on + * + * @return the block that the hanging entity was placed on + */ + public Block getBlock() { + return block; + } + + /** + * Returns the face of the block that the hanging entity was placed on + * + * @return the face of the block that the hanging entity was placed on + */ + public BlockFace getBlockFace() { + return blockFace; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/BrewEvent.java b/src/main/java/org/bukkit/event/inventory/BrewEvent.java new file mode 100644 index 0000000..2295c2d --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/BrewEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.inventory; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockEvent; +import org.bukkit.inventory.BrewerInventory; + +/** + * Called when the brewing of the contents inside the Brewing Stand is + * complete. + */ +public class BrewEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private BrewerInventory contents; + private boolean cancelled; + + public BrewEvent(Block brewer, BrewerInventory contents) { + super(brewer); + this.contents = contents; + } + + /** + * Gets the contents of the Brewing Stand. + * + * @return the contents + */ + public BrewerInventory getContents() { + return contents; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/ClickType.java b/src/main/java/org/bukkit/event/inventory/ClickType.java new file mode 100644 index 0000000..a7440aa --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/ClickType.java @@ -0,0 +1,115 @@ +package org.bukkit.event.inventory; + +/** + * What the client did to trigger this action (not the result). + */ +public enum ClickType { + + /** + * The left (or primary) mouse button. + */ + LEFT, + /** + * Holding shift while pressing the left mouse button. + */ + SHIFT_LEFT, + /** + * The right mouse button. + */ + RIGHT, + /** + * Holding shift while pressing the right mouse button. + */ + SHIFT_RIGHT, + /** + * Clicking the left mouse button on the grey area around the inventory. + */ + WINDOW_BORDER_LEFT, + /** + * Clicking the right mouse button on the grey area around the inventory. + */ + WINDOW_BORDER_RIGHT, + /** + * The middle mouse button, or a "scrollwheel click". + */ + MIDDLE, + /** + * One of the number keys 1-9, correspond to slots on the hotbar. + */ + NUMBER_KEY, + /** + * Pressing the left mouse button twice in quick succession. + */ + DOUBLE_CLICK, + /** + * The "Drop" key (defaults to Q). + */ + DROP, + /** + * Holding Ctrl while pressing the "Drop" key (defaults to Q). + */ + CONTROL_DROP, + /** + * Any action done with the Creative inventory open. + */ + CREATIVE, + /** + * A type of inventory manipulation not yet recognized by Bukkit. + *

          + * This is only for transitional purposes on a new Minecraft update, and + * should never be relied upon. + *

          + * Any ClickType.UNKNOWN is called on a best-effort basis. + */ + UNKNOWN, + ; + + /** + * Gets whether this ClickType represents the pressing of a key on a + * keyboard. + * + * @return true if this ClickType represents the pressing of a key + */ + public boolean isKeyboardClick() { + return (this == ClickType.NUMBER_KEY) || (this == ClickType.DROP) || (this == ClickType.CONTROL_DROP); + } + + /** + * Gets whether this ClickType represents an action that can only be + * performed by a Player in creative mode. + * + * @return true if this action requires Creative mode + */ + public boolean isCreativeAction() { + // Why use middle click? + return (this == ClickType.MIDDLE) || (this == ClickType.CREATIVE); + } + + /** + * Gets whether this ClickType represents a right click. + * + * @return true if this ClickType represents a right click + */ + public boolean isRightClick() { + return (this == ClickType.RIGHT) || (this == ClickType.SHIFT_RIGHT); + } + + /** + * Gets whether this ClickType represents a left click. + * + * @return true if this ClickType represents a left click + */ + public boolean isLeftClick() { + return (this == ClickType.LEFT) || (this == ClickType.SHIFT_LEFT) || (this == ClickType.DOUBLE_CLICK) || (this == ClickType.CREATIVE); + } + + /** + * Gets whether this ClickType indicates that the shift key was pressed + * down when the click was made. + * + * @return true if the action uses Shift. + */ + public boolean isShiftClick() { + return (this == ClickType.SHIFT_LEFT) || (this == ClickType.SHIFT_RIGHT) || (this == ClickType.CONTROL_DROP); + } +} diff --git a/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java b/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java new file mode 100644 index 0000000..ba3f5e5 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java @@ -0,0 +1,40 @@ +package org.bukkit.event.inventory; + +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.Recipe; + +/** + * Called when the recipe of an Item is completed inside a crafting matrix. + */ +public class CraftItemEvent extends InventoryClickEvent { + private Recipe recipe; + + @Deprecated + public CraftItemEvent(Recipe recipe, InventoryView what, SlotType type, int slot, boolean right, boolean shift) { + this(recipe, what, type, slot, right ? (shift ? ClickType.SHIFT_RIGHT : ClickType.RIGHT) : (shift ? ClickType.SHIFT_LEFT : ClickType.LEFT), InventoryAction.PICKUP_ALL); + } + + public CraftItemEvent(Recipe recipe, InventoryView what, SlotType type, int slot, ClickType click, InventoryAction action) { + super(what, type, slot, click, action); + this.recipe = recipe; + } + + public CraftItemEvent(Recipe recipe, InventoryView what, SlotType type, int slot, ClickType click, InventoryAction action, int key) { + super(what, type, slot, click, action, key); + this.recipe = recipe; + } + + /** + * @return A copy of the current recipe on the crafting matrix. + */ + public Recipe getRecipe() { + return recipe; + } + + @Override + public CraftingInventory getInventory() { + return (CraftingInventory) super.getInventory(); + } +} diff --git a/src/main/java/org/bukkit/event/inventory/DragType.java b/src/main/java/org/bukkit/event/inventory/DragType.java new file mode 100644 index 0000000..72c2bed --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/DragType.java @@ -0,0 +1,17 @@ +package org.bukkit.event.inventory; + +/** + * Represents the effect of a drag that will be applied to an Inventory in an + * InventoryDragEvent. + */ +public enum DragType { + /** + * One item from the cursor is placed in each selected slot. + */ + SINGLE, + /** + * The cursor is split evenly across all selected slots, not to exceed the + * Material's max stack size, with the remainder going to the cursor. + */ + EVEN, +} diff --git a/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java b/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java new file mode 100644 index 0000000..8ca1ff7 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java @@ -0,0 +1,99 @@ +package org.bukkit.event.inventory; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockEvent; +import org.bukkit.inventory.ItemStack; + +/** + * Called when an ItemStack is successfully burned as fuel in a furnace. + */ +public class FurnaceBurnEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final ItemStack fuel; + private int burnTime; + private boolean cancelled; + private boolean burning; + + public FurnaceBurnEvent(final Block furnace, final ItemStack fuel, final int burnTime) { + super(furnace); + this.fuel = fuel; + this.burnTime = burnTime; + this.cancelled = false; + this.burning = true; + } + + /** + * Gets the block for the furnace involved in this event + * + * @return the block of the furnace + * @deprecated In favour of {@link #getBlock()}. + */ + @Deprecated + public Block getFurnace() { + return getBlock(); + } + + /** + * Gets the fuel ItemStack for this event + * + * @return the fuel ItemStack + */ + public ItemStack getFuel() { + return fuel; + } + + /** + * Gets the burn time for this fuel + * + * @return the burn time for this fuel + */ + public int getBurnTime() { + return burnTime; + } + + /** + * Sets the burn time for this fuel + * + * @param burnTime the burn time for this fuel + */ + public void setBurnTime(int burnTime) { + this.burnTime = burnTime; + } + + /** + * Gets whether the furnace's fuel is burning or not. + * + * @return whether the furnace's fuel is burning or not. + */ + public boolean isBurning() { + return this.burning; + } + + /** + * Sets whether the furnace's fuel is burning or not. + * + * @param burning true if the furnace's fuel is burning + */ + public void setBurning(boolean burning) { + this.burning = burning; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java b/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java new file mode 100644 index 0000000..b7381fa --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java @@ -0,0 +1,49 @@ +package org.bukkit.event.inventory; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.block.BlockExpEvent; + +/** + * This event is called when a player takes items out of the furnace + */ +public class FurnaceExtractEvent extends BlockExpEvent { + private final Player player; + private final Material itemType; + private final int itemAmount; + + public FurnaceExtractEvent(Player player, Block block, Material itemType, int itemAmount, int exp) { + super(block, exp); + this.player = player; + this.itemType = itemType; + this.itemAmount = itemAmount; + } + + /** + * Get the player that triggered the event + * + * @return the relevant player + */ + public Player getPlayer() { + return player; + } + + /** + * Get the Material of the item being retrieved + * + * @return the material of the item + */ + public Material getItemType() { + return itemType; + } + + /** + * Get the item count being retrieved + * + * @return the amount of the item + */ + public int getItemAmount() { + return itemAmount; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java b/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java new file mode 100644 index 0000000..e9d1a54 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java @@ -0,0 +1,79 @@ +package org.bukkit.event.inventory; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockEvent; +import org.bukkit.inventory.ItemStack; + +/** + * Called when an ItemStack is successfully smelted in a furnace. + */ +public class FurnaceSmeltEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final ItemStack source; + private ItemStack result; + private boolean cancelled; + + public FurnaceSmeltEvent(final Block furnace, final ItemStack source, final ItemStack result) { + super(furnace); + this.source = source; + this.result = result; + this.cancelled = false; + } + + /** + * Gets the block for the furnace involved in this event + * + * @return the block of the furnace + * @deprecated In favour of {@link #getBlock()}. + */ + @Deprecated + public Block getFurnace() { + return getBlock(); + } + + /** + * Gets the smelted ItemStack for this event + * + * @return smelting source ItemStack + */ + public ItemStack getSource() { + return source; + } + + /** + * Gets the resultant ItemStack for this event + * + * @return smelting result ItemStack + */ + public ItemStack getResult() { + return result; + } + + /** + * Sets the resultant ItemStack for this event + * + * @param result new result ItemStack + */ + public void setResult(ItemStack result) { + this.result = result; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryAction.java b/src/main/java/org/bukkit/event/inventory/InventoryAction.java new file mode 100644 index 0000000..a7bc694 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryAction.java @@ -0,0 +1,91 @@ +package org.bukkit.event.inventory; + +/** + * An estimation of what the result will be. + */ +public enum InventoryAction { + + /** + * Nothing will happen from the click. + *

          + * There may be cases where nothing will happen and this is value is not + * provided, but it is guaranteed that this value is accurate when given. + */ + NOTHING, + /** + * All of the items on the clicked slot are moved to the cursor. + */ + PICKUP_ALL, + /** + * Some of the items on the clicked slot are moved to the cursor. + */ + PICKUP_SOME, + /** + * Half of the items on the clicked slot are moved to the cursor. + */ + PICKUP_HALF, + /** + * One of the items on the clicked slot are moved to the cursor. + */ + PICKUP_ONE, + /** + * All of the items on the cursor are moved to the clicked slot. + */ + PLACE_ALL, + /** + * Some of the items from the cursor are moved to the clicked slot + * (usually up to the max stack size). + */ + PLACE_SOME, + /** + * A single item from the cursor is moved to the clicked slot. + */ + PLACE_ONE, + /** + * The clicked item and the cursor are exchanged. + */ + SWAP_WITH_CURSOR, + /** + * The entire cursor item is dropped. + */ + DROP_ALL_CURSOR, + /** + * One item is dropped from the cursor. + */ + DROP_ONE_CURSOR, + /** + * The entire clicked slot is dropped. + */ + DROP_ALL_SLOT, + /** + * One item is dropped from the clicked slot. + */ + DROP_ONE_SLOT, + /** + * The item is moved to the opposite inventory if a space is found. + */ + MOVE_TO_OTHER_INVENTORY, + /** + * The clicked item is moved to the hotbar, and the item currently there + * is re-added to the player's inventory. + */ + HOTBAR_MOVE_AND_READD, + /** + * The clicked slot and the picked hotbar slot are swapped. + */ + HOTBAR_SWAP, + /** + * A max-size stack of the clicked item is put on the cursor. + */ + CLONE_STACK, + /** + * The inventory is searched for the same material, and they are put on + * the cursor up to {@link org.bukkit.Material#getMaxStackSize()}. + */ + COLLECT_TO_CURSOR, + /** + * An unrecognized ClickType. + */ + UNKNOWN, + ; +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java new file mode 100644 index 0000000..28198b8 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java @@ -0,0 +1,229 @@ +package org.bukkit.event.inventory; + +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.plugin.Plugin; + +/** + * This event is called when a player clicks a slot in an inventory. + *

          + * Because InventoryClickEvent occurs within a modification of the Inventory, + * not all Inventory related methods are safe to use. + *

          + * The following should never be invoked by an EventHandler for + * InventoryClickEvent using the HumanEntity or InventoryView associated with + * this event: + *

            + *
          • {@link HumanEntity#closeInventory()} + *
          • {@link HumanEntity#openInventory(Inventory)} + *
          • {@link HumanEntity#openWorkbench(Location, boolean)} + *
          • {@link HumanEntity#openEnchanting(Location, boolean)} + *
          • {@link InventoryView#close()} + *
          + * To invoke one of these methods, schedule a task using + * {@link BukkitScheduler#runTask(Plugin, Runnable)}, which will run the task + * on the next tick. Also be aware that this is not an exhaustive list, and + * other methods could potentially create issues as well. + *

          + * Assuming the EntityHuman associated with this event is an instance of a + * Player, manipulating the MaxStackSize or contents of an Inventory will + * require an Invocation of {@link Player#updateInventory()}. + *

          + * Modifications to slots that are modified by the results of this + * InventoryClickEvent can be overwritten. To change these slots, this event + * should be cancelled and all desired changes to the inventory applied. + * Alternatively, scheduling a task using {@link BukkitScheduler#runTask( + * Plugin, Runnable)}, which would execute the task on the next tick, would + * work as well. + */ +public class InventoryClickEvent extends InventoryInteractEvent { + private static final HandlerList handlers = new HandlerList(); + private final ClickType click; + private final InventoryAction action; + private SlotType slot_type; + private int whichSlot; + private int rawSlot; + private ItemStack current = null; + private int hotbarKey = -1; + + @Deprecated + public InventoryClickEvent(InventoryView view, SlotType type, int slot, boolean right, boolean shift) { + this(view, type, slot, right ? (shift ? ClickType.SHIFT_RIGHT : ClickType.RIGHT) : (shift ? ClickType.SHIFT_LEFT : ClickType.LEFT), InventoryAction.SWAP_WITH_CURSOR); + } + + public InventoryClickEvent(InventoryView view, SlotType type, int slot, ClickType click, InventoryAction action) { + super(view); + this.slot_type = type; + this.rawSlot = slot; + this.whichSlot = view.convertSlot(slot); + this.click = click; + this.action = action; + } + + public InventoryClickEvent(InventoryView view, SlotType type, int slot, ClickType click, InventoryAction action, int key) { + this(view, type, slot, click, action); + this.hotbarKey = key; + } + + /** + * Gets the type of slot that was clicked. + * + * @return the slot type + */ + public SlotType getSlotType() { + return slot_type; + } + + /** + * Gets the current ItemStack on the cursor. + * + * @return the cursor ItemStack + */ + public ItemStack getCursor() { + return getView().getCursor(); + } + + /** + * Gets the ItemStack currently in the clicked slot. + * + * @return the item in the clicked + */ + public ItemStack getCurrentItem() { + if (slot_type == SlotType.OUTSIDE) { + return current; + } + return getView().getItem(rawSlot); + } + + /** + * Gets whether or not the ClickType for this event represents a right + * click. + * + * @return true if the ClickType uses the right mouse button. + * @see ClickType#isRightClick() + */ + public boolean isRightClick() { + return click.isRightClick(); + } + + /** + * Gets whether or not the ClickType for this event represents a left + * click. + * + * @return true if the ClickType uses the left mouse button. + * @see ClickType#isLeftClick() + */ + public boolean isLeftClick() { + return click.isLeftClick(); + } + + /** + * Gets whether the ClickType for this event indicates that the key was + * pressed down when the click was made. + * + * @return true if the ClickType uses Shift or Ctrl. + * @see ClickType#isShiftClick() + */ + public boolean isShiftClick() { + return click.isShiftClick(); + } + + /** + * Sets the item on the cursor. + * + * @param stack the new cursor item + * @deprecated This changes the ItemStack in their hand before any + * calculations are applied to the Inventory, which has a tendency to + * create inconsistencies between the Player and the server, and to + * make unexpected changes in the behavior of the clicked Inventory. + */ + @Deprecated + public void setCursor(ItemStack stack) { + getView().setCursor(stack); + } + + /** + * Sets the ItemStack currently in the clicked slot. + * + * @param stack the item to be placed in the current slot + */ + public void setCurrentItem(ItemStack stack) { + if (slot_type == SlotType.OUTSIDE) { + current = stack; + } else { + getView().setItem(rawSlot, stack); + } + } + + /** + * The slot number that was clicked, ready for passing to + * {@link Inventory#getItem(int)}. Note that there may be two slots with + * the same slot number, since a view links two different inventories. + * + * @return The slot number. + */ + public int getSlot() { + return whichSlot; + } + + /** + * The raw slot number clicked, ready for passing to {@link InventoryView + * #getItem(int)} This slot number is unique for the view. + * + * @return the slot number + */ + public int getRawSlot() { + return rawSlot; + } + + /** + * If the ClickType is NUMBER_KEY, this method will return the index of + * the pressed key (0-8). + * + * @return the number on the key minus 1 (range 0-8); or -1 if not + * a NUMBER_KEY action + */ + public int getHotbarButton() { + return hotbarKey; + } + + /** + * Gets the InventoryAction that triggered this event. + *

          + * This action cannot be changed, and represents what the normal outcome + * of the event will be. To change the behavior of this + * InventoryClickEvent, changes must be manually applied. + * + * @return the InventoryAction that triggered this event. + */ + public InventoryAction getAction() { + return action; + } + + /** + * Gets the ClickType for this event. + *

          + * This is insulated against changes to the inventory by other plugins. + * + * @return the type of inventory click + */ + public ClickType getClick() { + return click; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java new file mode 100644 index 0000000..19889b2 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java @@ -0,0 +1,35 @@ + +package org.bukkit.event.inventory; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.InventoryView; + +/** + * Represents a player related inventory event + */ +public class InventoryCloseEvent extends InventoryEvent { + private static final HandlerList handlers = new HandlerList(); + + public InventoryCloseEvent(InventoryView transaction) { + super(transaction); + } + + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final HumanEntity getPlayer() { + return transaction.getPlayer(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java new file mode 100644 index 0000000..da7dffc --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java @@ -0,0 +1,27 @@ +package org.bukkit.event.inventory; + +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +/** + * This event is called when a player in creative mode puts down or picks up + * an item in their inventory / hotbar and when they drop items from their + * Inventory while in creative mode. + */ +public class InventoryCreativeEvent extends InventoryClickEvent { + private ItemStack item; + + public InventoryCreativeEvent(InventoryView what, SlotType type, int slot, ItemStack newItem) { + super(what, type, slot, ClickType.CREATIVE, InventoryAction.PLACE_ALL); + this.item = newItem; + } + + public ItemStack getCursor() { + return item; + } + + public void setCursor(ItemStack item) { + this.item = item; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java new file mode 100644 index 0000000..e7e54a7 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java @@ -0,0 +1,164 @@ +package org.bukkit.event.inventory; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.Validate; +import org.bukkit.Location; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitScheduler; + +import com.google.common.collect.ImmutableSet; + +/** + * This event is called when the player drags an item in their cursor across + * the inventory. The ItemStack is distributed across the slots the + * HumanEntity dragged over. The method of distribution is described by the + * DragType returned by {@link #getType()}. + *

          + * Canceling this event will result in none of the changes described in + * {@link #getNewItems()} being applied to the Inventory. + *

          + * Because InventoryDragEvent occurs within a modification of the Inventory, + * not all Inventory related methods are safe to use. + *

          + * The following should never be invoked by an EventHandler for + * InventoryDragEvent using the HumanEntity or InventoryView associated with + * this event. + *

            + *
          • {@link HumanEntity#closeInventory()} + *
          • {@link HumanEntity#openInventory(Inventory)} + *
          • {@link HumanEntity#openWorkbench(Location, boolean)} + *
          • {@link HumanEntity#openEnchanting(Location, boolean)} + *
          • {@link InventoryView#close()} + *
          + * To invoke one of these methods, schedule a task using + * {@link BukkitScheduler#runTask(Plugin, Runnable)}, which will run the task + * on the next tick. Also be aware that this is not an exhaustive list, and + * other methods could potentially create issues as well. + *

          + * Assuming the EntityHuman associated with this event is an instance of a + * Player, manipulating the MaxStackSize or contents of an Inventory will + * require an Invocation of {@link Player#updateInventory()}. + *

          + * Any modifications to slots that are modified by the results of this + * InventoryDragEvent will be overwritten. To change these slots, this event + * should be cancelled and the changes applied. Alternatively, scheduling a + * task using {@link BukkitScheduler#runTask(Plugin, Runnable)}, which would + * execute the task on the next tick, would work as well. + */ +public class InventoryDragEvent extends InventoryInteractEvent { + private static final HandlerList handlers = new HandlerList(); + private final DragType type; + private final Map addedItems; + private final Set containerSlots; + private final ItemStack oldCursor; + private ItemStack newCursor; + + public InventoryDragEvent(InventoryView what, ItemStack newCursor, ItemStack oldCursor, boolean right, Map slots) { + super(what); + + Validate.notNull(oldCursor); + Validate.notNull(slots); + + type = right ? DragType.SINGLE : DragType.EVEN; + this.newCursor = newCursor; + this.oldCursor = oldCursor; + this.addedItems = slots; + ImmutableSet.Builder b = ImmutableSet.builder(); + for (Integer slot : slots.keySet()) { + b.add(what.convertSlot(slot)); + } + this.containerSlots = b.build(); + } + + /** + * Gets all items to be added to the inventory in this drag. + * + * @return map from raw slot id to new ItemStack + */ + public Map getNewItems() { + return Collections.unmodifiableMap(addedItems); + } + + /** + * Gets the raw slot ids to be changed in this drag. + * + * @return list of raw slot ids, suitable for getView().getItem(int) + */ + public Set getRawSlots() { + return addedItems.keySet(); + } + + /** + * Gets the slots to be changed in this drag. + * + * @return list of converted slot ids, suitable for {@link + * org.bukkit.inventory.Inventory#getItem(int)}. + */ + public Set getInventorySlots() { + return containerSlots; + } + + /** + * Gets the result cursor after the drag is done. The returned value is + * mutable. + * + * @return the result cursor + */ + public ItemStack getCursor() { + return newCursor; + } + + /** + * Sets the result cursor after the drag is done. + *

          + * Changing this item stack changes the cursor item. Note that changing + * the affected "dragged" slots does not change this ItemStack, nor does + * changing this ItemStack affect the "dragged" slots. + * + * @param newCursor the new cursor ItemStack + */ + public void setCursor(ItemStack newCursor) { + this.newCursor = newCursor; + } + + /** + * Gets an ItemStack representing the cursor prior to any modifications + * as a result of this drag. + * + * @return the original cursor + */ + public ItemStack getOldCursor() { + return oldCursor.clone(); + } + + /** + * Gets the DragType that describes the behavior of ItemStacks placed + * after this InventoryDragEvent. + *

          + * The ItemStacks and the raw slots that they're being applied to can be + * found using {@link #getNewItems()}. + * + * @return the DragType of this InventoryDragEvent + */ + public DragType getType() { + return type; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryEvent.java new file mode 100644 index 0000000..973c392 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryEvent.java @@ -0,0 +1,59 @@ + +package org.bukkit.event.inventory; + +import java.util.List; + +import org.bukkit.event.HandlerList; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Event; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; + +/** + * Represents a player related inventory event + */ +public class InventoryEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + protected InventoryView transaction; + + public InventoryEvent(InventoryView transaction) { + this.transaction = transaction; + } + + /** + * Gets the primary Inventory involved in this transaction + * + * @return The upper inventory. + */ + public Inventory getInventory() { + return transaction.getTopInventory(); + } + + /** + * Gets the list of players viewing the primary (upper) inventory involved + * in this event + * + * @return A list of people viewing. + */ + public List getViewers() { + return transaction.getTopInventory().getViewers(); + } + + /** + * Gets the view object itself + * + * @return InventoryView + */ + public InventoryView getView() { + return transaction; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java new file mode 100644 index 0000000..8624f8d --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java @@ -0,0 +1,78 @@ +package org.bukkit.event.inventory; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event.Result; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +/** + * An abstract base class for events that describe an interaction between a + * HumanEntity and the contents of an Inventory. + */ +public abstract class InventoryInteractEvent extends InventoryEvent implements Cancellable { + private Result result = Result.DEFAULT; + + public InventoryInteractEvent(InventoryView transaction) { + super(transaction); + } + + /** + * Gets the player who performed the click. + * + * @return The clicking player. + */ + public HumanEntity getWhoClicked() { + return getView().getPlayer(); + } + + /** + * Sets the result of this event. This will change whether or not this + * event is considered cancelled. + * + * @see #isCancelled() + * @param newResult the new {@link Result} for this event + */ + public void setResult(Result newResult) { + result = newResult; + } + + /** + * Gets the {@link Result} of this event. The Result describes the + * behavior that will be applied to the inventory in relation to this + * event. + * + * @return the Result of this event. + */ + public Result getResult() { + return result; + } + + /** + * Gets whether or not this event is cancelled. This is based off of the + * Result value returned by {@link #getResult()}. Result.ALLOW and + * Result.DEFAULT will result in a returned value of false, but + * Result.DENY will result in a returned value of true. + *

          + * {@inheritDoc} + * + * @return whether the event is cancelled + */ + public boolean isCancelled() { + return getResult() == Result.DENY; + } + + /** + * Proxy method to {@link #setResult(Event.Result)} for the Cancellable + * interface. {@link #setResult(Event.Result)} is preferred, as it allows + * you to specify the Result beyond Result.DENY and Result.ALLOW. + *

          + * {@inheritDoc} + * + * @param toCancel result becomes DENY if true, ALLOW if false + */ + public void setCancelled(boolean toCancel) { + setResult(toCancel ? Result.DENY : Result.ALLOW); + } + +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java new file mode 100644 index 0000000..06ec99a --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java @@ -0,0 +1,108 @@ +package org.bukkit.event.inventory; + +import org.apache.commons.lang.Validate; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +/** + * Called when some entity or block (e.g. hopper) tries to move items directly + * from one inventory to another. + *

          + * When this event is called, the initiator may already have removed the item + * from the source inventory and is ready to move it into the destination + * inventory. + *

          + * If this event is cancelled, the items will be returned to the source + * inventory, if needed. + *

          + * If this event is not cancelled, the initiator will try to put the ItemStack + * into the destination inventory. If this is not possible and the ItemStack + * has not been modified, the source inventory slot will be restored to its + * former state. Otherwise any additional items will be discarded. + */ +public class InventoryMoveItemEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Inventory sourceInventory; + private final Inventory destinationInventory; + private ItemStack itemStack; + private final boolean didSourceInitiate; + + public InventoryMoveItemEvent(final Inventory sourceInventory, final ItemStack itemStack, final Inventory destinationInventory, final boolean didSourceInitiate) { + Validate.notNull(itemStack, "ItemStack cannot be null"); + this.sourceInventory = sourceInventory; + this.itemStack = itemStack; + this.destinationInventory = destinationInventory; + this.didSourceInitiate = didSourceInitiate; + } + + /** + * Gets the Inventory that the ItemStack is being taken from + * + * @return Inventory that the ItemStack is being taken from + */ + public Inventory getSource() { + return sourceInventory; + } + + /** + * Gets the ItemStack being moved; if modified, the original item will not + * be removed from the source inventory. + * + * @return ItemStack + */ + public ItemStack getItem() { + return itemStack.clone(); + } + + /** + * Sets the ItemStack being moved; if this is different from the original + * ItemStack, the original item will not be removed from the source + * inventory. + * + * @param itemStack The ItemStack + */ + public void setItem(ItemStack itemStack) { + Validate.notNull(itemStack, "ItemStack cannot be null. Cancel the event if you want nothing to be transferred."); + this.itemStack = itemStack.clone(); + } + + /** + * Gets the Inventory that the ItemStack is being put into + * + * @return Inventory that the ItemStack is being put into + */ + public Inventory getDestination() { + return destinationInventory; + } + + /** + * Gets the Inventory that initiated the transfer. This will always be + * either the destination or source Inventory. + * + * @return Inventory that initiated the transfer + */ + public Inventory getInitiator() { + return didSourceInitiate ? sourceInventory : destinationInventory; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java new file mode 100644 index 0000000..c3570aa --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java @@ -0,0 +1,63 @@ +package org.bukkit.event.inventory; + +import org.bukkit.inventory.InventoryView; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Represents a player related inventory event + */ +public class InventoryOpenEvent extends InventoryEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + + public InventoryOpenEvent(InventoryView transaction) { + super(transaction); + this.cancelled = false; + } + + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final HumanEntity getPlayer() { + return transaction.getPlayer(); + } + + /** + * Gets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins. + *

          + * If an inventory open event is cancelled, the inventory screen will not + * show. + * + * @return true if this event is cancelled + */ + public boolean isCancelled() { + return cancelled; + } + + /** + * Sets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins. + *

          + * If an inventory open event is cancelled, the inventory screen will not + * show. + * + * @param cancel true if you wish to cancel this event + */ + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java b/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java new file mode 100644 index 0000000..af6ad5b --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java @@ -0,0 +1,58 @@ +package org.bukkit.event.inventory; + +import org.bukkit.entity.Item; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.Inventory; + +/** + * Called when a hopper or hopper minecart picks up a dropped item. + */ +public class InventoryPickupItemEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Inventory inventory; + private final Item item; + + public InventoryPickupItemEvent(final Inventory inventory, final Item item) { + super(); + this.inventory = inventory; + this.item = item; + } + + /** + * Gets the Inventory that picked up the item + * + * @return Inventory + */ + public Inventory getInventory() { + return inventory; + } + + /** + * Gets the Item entity that was picked up + * + * @return Item + */ + public Item getItem() { + return item; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/InventoryType.java b/src/main/java/org/bukkit/event/inventory/InventoryType.java new file mode 100644 index 0000000..b83580a --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/InventoryType.java @@ -0,0 +1,124 @@ +package org.bukkit.event.inventory; + +public enum InventoryType { + + /** + * A chest inventory, with 0, 9, 18, 27, 36, 45, or 54 slots of type + * CONTAINER. + */ + CHEST(27,"Chest"), + /** + * A dispenser inventory, with 9 slots of type CONTAINER. + */ + DISPENSER(9,"Dispenser"), + /** + * A dropper inventory, with 9 slots of type CONTAINER. + */ + DROPPER(9, "Dropper"), + /** + * A furnace inventory, with a RESULT slot, a CRAFTING slot, and a FUEL + * slot. + */ + FURNACE(3,"Furnace"), + /** + * A workbench inventory, with 9 CRAFTING slots and a RESULT slot. + */ + WORKBENCH(10,"Crafting"), + /** + * A player's crafting inventory, with 4 CRAFTING slots and a RESULT slot. + * Also implies that the 4 ARMOR slots are accessible. + */ + CRAFTING(5,"Crafting"), + /** + * An enchantment table inventory, with one CRAFTING slot and three + * enchanting buttons. + */ + ENCHANTING(1,"Enchanting"), + /** + * A brewing stand inventory, with one FUEL slot and three CRAFTING slots. + */ + BREWING(4,"Brewing"), + /** + * A player's inventory, with 9 QUICKBAR slots, 27 CONTAINER slots, and 4 + * ARMOR slots. The ARMOUR slots may not be visible to the player, though. + */ + PLAYER(36,"Player"), + /** + * The creative mode inventory, with only 9 QUICKBAR slots and nothing + * else. (The actual creative interface with the items is client-side and + * cannot be altered by the server.) + */ + CREATIVE(9,"Creative"), + /** + * The merchant inventory, with 2 TRADE-IN slots, and 1 RESULT slot. + */ + MERCHANT(3,"Villager"), + /** + * The ender chest inventory, with 27 slots. + */ + ENDER_CHEST(27,"Ender Chest"), + /** + * An anvil inventory, with 2 CRAFTING slots and 1 RESULT slot + */ + ANVIL(3, "Repairing"), + /** + * A beacon inventory, with 1 CRAFTING slot + */ + BEACON(1, "container.beacon"), + /** + * A hopper inventory, with 5 slots of type CONTAINER. + */ + HOPPER(5, "Item Hopper"), + ; + + private final int size; + private final String title; + + private InventoryType(int defaultSize, String defaultTitle) { + size = defaultSize; + title = defaultTitle; + } + + public int getDefaultSize() { + return size; + } + + public String getDefaultTitle() { + return title; + } + + public enum SlotType { + /** + * A result slot in a furnace or crafting inventory. + */ + RESULT, + /** + * A slot in the crafting matrix, or the input slot in a furnace + * inventory, the potion slot in the brewing stand, or the enchanting + * slot. + */ + CRAFTING, + /** + * An armour slot in the player's inventory. + */ + ARMOR, + /** + * A regular slot in the container or the player's inventory; anything + * not covered by the other enum values. + */ + CONTAINER, + /** + * A slot in the bottom row or quickbar. + */ + QUICKBAR, + /** + * A pseudo-slot representing the area outside the inventory window. + */ + OUTSIDE, + /** + * The fuel slot in a furnace inventory, or the ingredient slot in a + * brewing stand inventory. + */ + FUEL; + } +} diff --git a/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java b/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java new file mode 100644 index 0000000..5731190 --- /dev/null +++ b/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java @@ -0,0 +1,56 @@ +package org.bukkit.event.inventory; + +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.Recipe; + +public class PrepareItemCraftEvent extends InventoryEvent { + private static final HandlerList handlers = new HandlerList(); + private boolean repair; + private CraftingInventory matrix; + + public PrepareItemCraftEvent(CraftingInventory what, InventoryView view, boolean isRepair) { + super(view); + this.matrix = what; + this.repair = isRepair; + } + + /** + * Get the recipe that has been formed. If this event was triggered by a + * tool repair, this will be a temporary shapeless recipe representing the + * repair. + * + * @return The recipe being crafted. + */ + public Recipe getRecipe() { + return matrix.getRecipe(); + } + + /** + * @return The crafting inventory on which the recipe was formed. + */ + @Override + public CraftingInventory getInventory() { + return matrix; + } + + /** + * Check if this event was triggered by a tool repair operation rather + * than a crafting recipe. + * + * @return True if this is a repair. + */ + public boolean isRepair() { + return repair; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/painting/PaintingBreakByEntityEvent.java b/src/main/java/org/bukkit/event/painting/PaintingBreakByEntityEvent.java new file mode 100644 index 0000000..1dc4987 --- /dev/null +++ b/src/main/java/org/bukkit/event/painting/PaintingBreakByEntityEvent.java @@ -0,0 +1,31 @@ +package org.bukkit.event.painting; + +import org.bukkit.Warning; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Painting; + +/** + * Triggered when a painting is removed by an entity + * + * @deprecated Use {@link org.bukkit.event.hanging.HangingBreakByEntityEvent} + * instead. + */ +@Deprecated +@Warning(reason="This event has been replaced by HangingBreakByEntityEvent") +public class PaintingBreakByEntityEvent extends PaintingBreakEvent { + private final Entity remover; + + public PaintingBreakByEntityEvent(final Painting painting, final Entity remover) { + super(painting, RemoveCause.ENTITY); + this.remover = remover; + } + + /** + * Gets the entity that removed the painting + * + * @return the entity that removed the painting. + */ + public Entity getRemover() { + return remover; + } +} diff --git a/src/main/java/org/bukkit/event/painting/PaintingBreakEvent.java b/src/main/java/org/bukkit/event/painting/PaintingBreakEvent.java new file mode 100644 index 0000000..3e27c69 --- /dev/null +++ b/src/main/java/org/bukkit/event/painting/PaintingBreakEvent.java @@ -0,0 +1,76 @@ +package org.bukkit.event.painting; + +import org.bukkit.Warning; +import org.bukkit.entity.Painting; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Triggered when a painting is removed + * + * @deprecated Use {@link org.bukkit.event.hanging.HangingBreakEvent} instead. + */ +@Deprecated +@Warning(reason="This event has been replaced by HangingBreakEvent") +public class PaintingBreakEvent extends PaintingEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final RemoveCause cause; + + public PaintingBreakEvent(final Painting painting, final RemoveCause cause) { + super(painting); + this.cause = cause; + } + + /** + * Gets the cause for the painting's removal + * + * @return the RemoveCause for the painting's removal + */ + public RemoveCause getCause() { + return cause; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * An enum to specify the cause of the removal + */ + public enum RemoveCause { + /** + * Removed by an entity + */ + ENTITY, + /** + * Removed by fire + */ + FIRE, + /** + * Removed by placing a block on it + */ + OBSTRUCTION, + /** + * Removed by water flowing over it + */ + WATER, + /** + * Removed by destroying the block behind it, etc + */ + PHYSICS, + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/painting/PaintingEvent.java b/src/main/java/org/bukkit/event/painting/PaintingEvent.java new file mode 100644 index 0000000..3a51348 --- /dev/null +++ b/src/main/java/org/bukkit/event/painting/PaintingEvent.java @@ -0,0 +1,29 @@ +package org.bukkit.event.painting; + +import org.bukkit.Warning; +import org.bukkit.entity.Painting; +import org.bukkit.event.Event; + +/** + * Represents a painting-related event. + * + * @deprecated Use {@link org.bukkit.event.hanging.HangingEvent} instead. + */ +@Deprecated +@Warning(reason="This event has been replaced by HangingEvent") +public abstract class PaintingEvent extends Event { + protected Painting painting; + + protected PaintingEvent(final Painting painting) { + this.painting = painting; + } + + /** + * Gets the painting involved in this event. + * + * @return the painting + */ + public Painting getPainting() { + return painting; + } +} diff --git a/src/main/java/org/bukkit/event/painting/PaintingPlaceEvent.java b/src/main/java/org/bukkit/event/painting/PaintingPlaceEvent.java new file mode 100644 index 0000000..3250b29 --- /dev/null +++ b/src/main/java/org/bukkit/event/painting/PaintingPlaceEvent.java @@ -0,0 +1,76 @@ +package org.bukkit.event.painting; + +import org.bukkit.Warning; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Painting; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Triggered when a painting is created in the world + * + * @deprecated Use {@link org.bukkit.event.hanging.HangingPlaceEvent} instead. + */ +@Deprecated +@Warning(reason="This event has been replaced by HangingPlaceEvent") +public class PaintingPlaceEvent extends PaintingEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Player player; + private final Block block; + private final BlockFace blockFace; + + public PaintingPlaceEvent(final Painting painting, final Player player, final Block block, final BlockFace blockFace) { + super(painting); + this.player = player; + this.block = block; + this.blockFace = blockFace; + } + + /** + * Returns the player placing the painting + * + * @return Entity returns the player placing the painting + */ + public Player getPlayer() { + return player; + } + + /** + * Returns the block that the painting was placed on + * + * @return Block returns the block painting placed on + */ + public Block getBlock() { + return block; + } + + /** + * Returns the face of the block that the painting was placed on + * + * @return BlockFace returns the face of the block the painting was placed + * on + */ + public BlockFace getBlockFace() { + return blockFace; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java b/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java new file mode 100644 index 0000000..a796292 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java @@ -0,0 +1,140 @@ +package org.bukkit.event.player; + +import java.util.IllegalFormatException; +import java.util.Set; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * This event will sometimes fire synchronously, depending on how it was + * triggered. + *

          + * The constructor provides a boolean to indicate if the event was fired + * synchronously or asynchronously. When asynchronous, this event can be + * called from any thread, sans the main thread, and has limited access to the + * API. + *

          + * If a player is the direct cause of this event by an incoming packet, this + * event will be asynchronous. If a plugin triggers this event by compelling a + * player to chat, this event will be synchronous. + *

          + * Care should be taken to check {@link #isAsynchronous()} and treat the event + * appropriately. + */ +public class AsyncPlayerChatEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private String message; + private String format = "<%1$s> %2$s"; + private final Set recipients; + + /** + * + * @param async This changes the event to a synchronous state. + * @param who the chat sender + * @param message the message sent + * @param players the players to receive the message. This may be a lazy + * or unmodifiable collection. + */ + public AsyncPlayerChatEvent(final boolean async, final Player who, final String message, final Set players) { + super(who, async); + this.message = message; + recipients = players; + } + + /** + * Gets the message that the player is attempting to send. This message + * will be used with {@link #getFormat()}. + * + * @return Message the player is attempting to send + */ + public String getMessage() { + return message; + } + + /** + * Sets the message that the player will send. This message will be used + * with {@link #getFormat()}. + * + * @param message New message that the player will send + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Gets the format to use to display this chat message. + *

          + * When this event finishes execution, the first format parameter is the + * {@link Player#getDisplayName()} and the second parameter is {@link + * #getMessage()} + * + * @return {@link String#format(String, Object...)} compatible format + * string + */ + public String getFormat() { + return format; + } + + /** + * Sets the format to use to display this chat message. + *

          + * When this event finishes execution, the first format parameter is the + * {@link Player#getDisplayName()} and the second parameter is {@link + * #getMessage()} + * + * @param format {@link String#format(String, Object...)} compatible + * format string + * @throws IllegalFormatException if the underlying API throws the + * exception + * @throws NullPointerException if format is null + * @see String#format(String, Object...) + */ + public void setFormat(final String format) throws IllegalFormatException, NullPointerException { + // Oh for a better way to do this! + try { + String.format(format, player, message); + } catch (RuntimeException ex) { + ex.fillInStackTrace(); + throw ex; + } + + this.format = format; + } + + /** + * Gets a set of recipients that this chat message will be displayed to. + *

          + * The set returned is not guaranteed to be mutable and may auto-populate + * on access. Any listener accessing the returned set should be aware that + * it may reduce performance for a lazy set implementation. + *

          + * Listeners should be aware that modifying the list may throw {@link + * UnsupportedOperationException} if the event caller provides an + * unmodifiable set. + * + * @return All Players who will see this chat message + */ + public Set getRecipients() { + return recipients; + } + + public boolean isCancelled() { + return cancel ; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java b/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java new file mode 100644 index 0000000..1d57188 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java @@ -0,0 +1,201 @@ +package org.bukkit.event.player; + +import java.net.InetAddress; +import java.util.UUID; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Stores details for players attempting to log in. + *

          + * This event is asynchronous, and not run using main thread. + */ +public class AsyncPlayerPreLoginEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private Result result; + private String message; + private final String name; + private final InetAddress ipAddress; + private final UUID uniqueId; + + @Deprecated + public AsyncPlayerPreLoginEvent(final String name, final InetAddress ipAddress) { + this(name, ipAddress, null); + } + + public AsyncPlayerPreLoginEvent(final String name, final InetAddress ipAddress, final UUID uniqueId) { + super(true); + this.result = Result.ALLOWED; + this.message = ""; + this.name = name; + this.ipAddress = ipAddress; + this.uniqueId = uniqueId; + } + + /** + * Gets the current result of the login, as an enum + * + * @return Current Result of the login + */ + public Result getLoginResult() { + return result; + } + + /** + * Gets the current result of the login, as an enum + * + * @return Current Result of the login + * @deprecated This method uses a deprecated enum from {@link + * PlayerPreLoginEvent} + * @see #getLoginResult() + */ + @Deprecated + public PlayerPreLoginEvent.Result getResult() { + return result == null ? null : result.old(); + } + + /** + * Sets the new result of the login, as an enum + * + * @param result New result to set + */ + public void setLoginResult(final Result result) { + this.result = result; + } + + /** + * Sets the new result of the login, as an enum + * + * @param result New result to set + * @deprecated This method uses a deprecated enum from {@link + * PlayerPreLoginEvent} + * @see #setLoginResult(Result) + */ + @Deprecated + public void setResult(final PlayerPreLoginEvent.Result result) { + this.result = result == null ? null : Result.valueOf(result.name()); + } + + /** + * Gets the current kick message that will be used if getResult() != + * Result.ALLOWED + * + * @return Current kick message + */ + public String getKickMessage() { + return message; + } + + /** + * Sets the kick message to display if getResult() != Result.ALLOWED + * + * @param message New kick message + */ + public void setKickMessage(final String message) { + this.message = message; + } + + /** + * Allows the player to log in + */ + public void allow() { + result = Result.ALLOWED; + message = ""; + } + + /** + * Disallows the player from logging in, with the given reason + * + * @param result New result for disallowing the player + * @param message Kick message to display to the user + */ + public void disallow(final Result result, final String message) { + this.result = result; + this.message = message; + } + + /** + * Disallows the player from logging in, with the given reason + * + * @param result New result for disallowing the player + * @param message Kick message to display to the user + * @deprecated This method uses a deprecated enum from {@link + * PlayerPreLoginEvent} + * @see #disallow(Result, String) + */ + @Deprecated + public void disallow(final PlayerPreLoginEvent.Result result, final String message) { + this.result = result == null ? null : Result.valueOf(result.name()); + this.message = message; + } + + /** + * Gets the player's name. + * + * @return the player's name + */ + public String getName() { + return name; + } + + /** + * Gets the player IP address. + * + * @return The IP address + */ + public InetAddress getAddress() { + return ipAddress; + } + + /** + * Gets the player's unique ID. + * + * @return The unique ID + */ + public UUID getUniqueId() { + return uniqueId; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Basic kick reasons for communicating to plugins + */ + public enum Result { + + /** + * The player is allowed to log in + */ + ALLOWED, + /** + * The player is not allowed to log in, due to the server being full + */ + KICK_FULL, + /** + * The player is not allowed to log in, due to them being banned + */ + KICK_BANNED, + /** + * The player is not allowed to log in, due to them not being on the + * white list + */ + KICK_WHITELIST, + /** + * The player is not allowed to log in, for reasons undefined + */ + KICK_OTHER; + + @Deprecated + private PlayerPreLoginEvent.Result old() { + return PlayerPreLoginEvent.Result.valueOf(name()); + } + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java b/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java new file mode 100644 index 0000000..e33fade --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.Achievement; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player earns an achievement. + */ +public class PlayerAchievementAwardedEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Achievement achievement; + private boolean isCancelled = false; + + public PlayerAchievementAwardedEvent(Player player, Achievement achievement) { + super(player); + this.achievement = achievement; + } + + /** + * Gets the Achievement being awarded. + * + * @return the achievement being awarded + */ + public Achievement getAchievement() { + return achievement; + } + + public boolean isCancelled() { + return isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java b/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java new file mode 100644 index 0000000..cabe77d --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java @@ -0,0 +1,52 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Represents a player animation event + */ +public class PlayerAnimationEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final PlayerAnimationType animationType; + private boolean isCancelled = false; + + /** + * Construct a new PlayerAnimation event + * + * @param player The player instance + */ + public PlayerAnimationEvent(final Player player) { + super(player); + + // Only supported animation type for now: + animationType = PlayerAnimationType.ARM_SWING; + } + + /** + * Get the type of this animation event + * + * @return the animation type + */ + public PlayerAnimationType getAnimationType() { + return animationType; + } + + public boolean isCancelled() { + return this.isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerAnimationType.java b/src/main/java/org/bukkit/event/player/PlayerAnimationType.java new file mode 100644 index 0000000..ea4bf26 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerAnimationType.java @@ -0,0 +1,8 @@ +package org.bukkit.event.player; + +/** + * Different types of player animations + */ +public enum PlayerAnimationType { + ARM_SWING +} diff --git a/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java b/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java new file mode 100644 index 0000000..09f1a66 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * This event is fired when the player is almost about to enter the bed. + */ +public class PlayerBedEnterEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private final Block bed; + + public PlayerBedEnterEvent(final Player who, final Block bed) { + super(who); + this.bed = bed; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Returns the bed block involved in this event. + * + * @return the bed block involved in this event + */ + public Block getBed() { + return bed; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java b/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java new file mode 100644 index 0000000..628ab0b --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.player; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * This event is fired when the player is leaving a bed. + */ +public class PlayerBedLeaveEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final Block bed; + + public PlayerBedLeaveEvent(final Player who, final Block bed) { + super(who); + this.bed = bed; + } + + /** + * Returns the bed block involved in this event. + * + * @return the bed block involved in this event + */ + public Block getBed() { + return bed; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java b/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java new file mode 100644 index 0000000..8fb121a --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a player empties a bucket + */ +public class PlayerBucketEmptyEvent extends PlayerBucketEvent { + private static final HandlerList handlers = new HandlerList(); + + public PlayerBucketEmptyEvent(final Player who, final Block blockClicked, final BlockFace blockFace, final Material bucket, final ItemStack itemInHand) { + super(who, blockClicked, blockFace, bucket, itemInHand); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java b/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java new file mode 100644 index 0000000..d32c55e --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java @@ -0,0 +1,80 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a player interacts with a Bucket + */ +public abstract class PlayerBucketEvent extends PlayerEvent implements Cancellable { + private ItemStack itemStack; + private boolean cancelled = false; + private final Block blockClicked; + private final BlockFace blockFace; + private final Material bucket; + + public PlayerBucketEvent(final Player who, final Block blockClicked, final BlockFace blockFace, final Material bucket, final ItemStack itemInHand) { + super(who); + this.blockClicked = blockClicked; + this.blockFace = blockFace; + this.itemStack = itemInHand; + this.bucket = bucket; + } + + /** + * Returns the bucket used in this event + * + * @return the used bucket + */ + public Material getBucket() { + return bucket; + } + + /** + * Get the resulting item in hand after the bucket event + * + * @return Itemstack hold in hand after the event. + */ + public ItemStack getItemStack() { + return itemStack; + } + + /** + * Set the item in hand after the event + * + * @param itemStack the new held itemstack after the bucket event. + */ + public void setItemStack(ItemStack itemStack) { + this.itemStack = itemStack; + } + + /** + * Return the block clicked + * + * @return the blicked block + */ + public Block getBlockClicked() { + return blockClicked; + } + + /** + * Get the face on the clicked block + * + * @return the clicked face + */ + public BlockFace getBlockFace() { + return blockFace; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java b/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java new file mode 100644 index 0000000..94e042a --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a player fills a bucket + */ +public class PlayerBucketFillEvent extends PlayerBucketEvent { + private static final HandlerList handlers = new HandlerList(); + + public PlayerBucketFillEvent(final Player who, final Block blockClicked, final BlockFace blockFace, final Material bucket, final ItemStack itemInHand) { + super(who, blockClicked, blockFace, bucket, itemInHand); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java b/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java new file mode 100644 index 0000000..76c9c20 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.player; + +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player switches to another world. + */ +public class PlayerChangedWorldEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final World from; + + public PlayerChangedWorldEvent(final Player player, final World from) { + super(player); + this.from = from; + } + + /** + * Gets the world the player is switching from. + * + * @return player's previous world + */ + public World getFrom() { + return from; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java b/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java new file mode 100644 index 0000000..054efbc --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java @@ -0,0 +1,31 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * This event is called after a player registers or unregisters a new plugin + * channel. + */ +public abstract class PlayerChannelEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final String channel; + + public PlayerChannelEvent(final Player player, final String channel) { + super(player); + this.channel = channel; + } + + public final String getChannel() { + return channel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerChatEvent.java b/src/main/java/org/bukkit/event/player/PlayerChatEvent.java new file mode 100644 index 0000000..1fb5cd7 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerChatEvent.java @@ -0,0 +1,125 @@ +package org.bukkit.event.player; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.lang.Validate; +import org.bukkit.Warning; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Holds information for player chat and commands + * + * @deprecated This event will fire from the main thread and allows the use of + * all of the Bukkit API, unlike the {@link AsyncPlayerChatEvent}. + *

          + * Listening to this event forces chat to wait for the main thread which + * causes delays for chat. {@link AsyncPlayerChatEvent} is the encouraged + * alternative for thread safe implementations. + */ +@Deprecated +@Warning(reason="Listening to this event forces chat to wait for the main thread, delaying chat messages.") +public class PlayerChatEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private String message; + private String format; + private final Set recipients; + + public PlayerChatEvent(final Player player, final String message) { + super(player); + this.message = message; + this.format = "<%1$s> %2$s"; + this.recipients = new HashSet(player.getServer().getOnlinePlayers()); + } + + public PlayerChatEvent(final Player player, final String message, final String format, final Set recipients) { + super(player); + this.message = message; + this.format = format; + this.recipients = recipients; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the message that the player is attempting to send + * + * @return Message the player is attempting to send + */ + public String getMessage() { + return message; + } + + /** + * Sets the message that the player will send + * + * @param message New message that the player will send + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Sets the player that this message will display as, or command will be + * executed as + * + * @param player New player which this event will execute as + */ + public void setPlayer(final Player player) { + Validate.notNull(player, "Player cannot be null"); + this.player = player; + } + + /** + * Gets the format to use to display this chat message + * + * @return String.Format compatible format string + */ + public String getFormat() { + return format; + } + + /** + * Sets the format to use to display this chat message + * + * @param format String.Format compatible format string + */ + public void setFormat(final String format) { + // Oh for a better way to do this! + try { + String.format(format, player, message); + } catch (RuntimeException ex) { + ex.fillInStackTrace(); + throw ex; + } + + this.format = format; + } + + /** + * Gets a set of recipients that this chat message will be displayed to + * + * @return All Players who will see this chat message + */ + public Set getRecipients() { + return recipients; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java b/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java new file mode 100644 index 0000000..7241a9b --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java @@ -0,0 +1,70 @@ +package org.bukkit.event.player; + +import java.util.Collection; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player attempts to tab-complete a chat message. + */ +public class PlayerChatTabCompleteEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final String message; + private final String lastToken; + private final Collection completions; + + public PlayerChatTabCompleteEvent(final Player who, final String message, final Collection completions) { + super(who); + Validate.notNull(message, "Message cannot be null"); + Validate.notNull(completions, "Completions cannot be null"); + this.message = message; + int i = message.lastIndexOf(' '); + if (i < 0) { + this.lastToken = message; + } else { + this.lastToken = message.substring(i + 1); + } + this.completions = completions; + } + + /** + * Gets the chat message being tab-completed. + * + * @return the chat message + */ + public String getChatMessage() { + return message; + } + + /** + * Gets the last 'token' of the message being tab-completed. + *

          + * The token is the substring starting with the character after the last + * space in the message. + * + * @return The last token for the chat message + */ + public String getLastToken() { + return lastToken; + } + + /** + * This is the collection of completions for this event. + * + * @return the current completions + */ + public Collection getTabCompletions() { + return completions; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java b/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java new file mode 100644 index 0000000..1ec8173 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java @@ -0,0 +1,172 @@ +package org.bukkit.event.player; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * This event is called whenever a player runs a command (by placing a slash + * at the start of their message). It is called early in the command handling + * process, and modifications in this event (via {@link #setMessage(String)}) + * will be shown in the behavior. + *

          + * Many plugins will have no use for this event, and you should + * attempt to avoid using it if it is not necessary. + *

          + * Some examples of valid uses for this event are: + *

            + *
          • Logging executed commands to a separate file + *
          • Variable substitution. For example, replacing + * ${nearbyPlayer} with the name of the nearest other + * player, or simulating the @a and @p + * decorators used by Command Blocks in plugins that do not handle it. + *
          • Conditionally blocking commands belonging to other plugins. For + * example, blocking the use of the /home command in a + * combat arena. + *
          • Per-sender command aliases. For example, after a player runs the + * command /calias cr gamemode creative, the next time they + * run /cr, it gets replaced into + * /gamemode creative. (Global command aliases should be + * done by registering the alias.) + *
          + *

          + * Examples of incorrect uses are: + *

            + *
          • Using this event to run command logic + *
          + *

          + * If the event is cancelled, processing of the command will halt. + *

          + * The state of whether or not there is a slash (/) at the + * beginning of the message should be preserved. If a slash is added or + * removed, unexpected behavior may result. + */ +public class PlayerCommandPreprocessEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private String message; + private String format = "<%1$s> %2$s"; + private final Set recipients; + + public PlayerCommandPreprocessEvent(final Player player, final String message) { + super(player); + this.recipients = new HashSet(player.getServer().getOnlinePlayers()); + this.message = message; + } + + public PlayerCommandPreprocessEvent(final Player player, final String message, final Set recipients) { + super(player); + this.recipients = recipients; + this.message = message; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the command that the player is attempting to send. + *

          + * All commands begin with a special character; implementations do not + * consider the first character when executing the content. + * + * @return Message the player is attempting to send + */ + public String getMessage() { + return message; + } + + /** + * Sets the command that the player will send. + *

          + * All commands begin with a special character; implementations do not + * consider the first character when executing the content. + * + * @param command New message that the player will send + * @throws IllegalArgumentException if command is null or empty + */ + public void setMessage(String command) throws IllegalArgumentException { + Validate.notNull(command, "Command cannot be null"); + Validate.notEmpty(command, "Command cannot be empty"); + this.message = command; + } + + /** + * Sets the player that this command will be executed as. + * + * @param player New player which this event will execute as + * @throws IllegalArgumentException if the player provided is null + */ + public void setPlayer(final Player player) throws IllegalArgumentException { + Validate.notNull(player, "Player cannot be null"); + this.player = player; + } + + /** + * Gets the format to use to display this chat message + * + * @deprecated This method is provided for backward compatibility with no + * guarantee to the use of the format. + * @return String.Format compatible format string + */ + @Deprecated + public String getFormat() { + return format; + } + + /** + * Sets the format to use to display this chat message + * + * @deprecated This method is provided for backward compatibility with no + * guarantee to the effect of modifying the format. + * @param format String.Format compatible format string + */ + @Deprecated + public void setFormat(final String format) { + // Oh for a better way to do this! + try { + String.format(format, player, message); + } catch (RuntimeException ex) { + ex.fillInStackTrace(); + throw ex; + } + + this.format = format; + } + + /** + * Gets a set of recipients that this chat message will be displayed to. + *

          + * The set returned is not guaranteed to be mutable and may auto-populate + * on access. Any listener accessing the returned set should be aware that + * it may reduce performance for a lazy set implementation. Listeners + * should be aware that modifying the list may throw {@link + * UnsupportedOperationException} if the event caller provides an + * unmodifiable set. + * + * @deprecated This method is provided for backward compatibility with no + * guarantee to the effect of viewing or modifying the set. + * @return All Players who will see this chat message + */ + @Deprecated + public Set getRecipients() { + return recipients; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java b/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java new file mode 100644 index 0000000..5b41b65 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a player drops an item from their inventory + */ +public class PlayerDropItemEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Item drop; + private boolean cancel = false; + + public PlayerDropItemEvent(final Player player, final Item drop) { + super(player); + this.drop = drop; + } + + /** + * Gets the ItemDrop created by the player + * + * @return ItemDrop created by the player + */ + public Item getItemDrop() { + return drop; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java b/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java new file mode 100644 index 0000000..ea7ecef --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java @@ -0,0 +1,124 @@ +package org.bukkit.event.player; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.meta.BookMeta; + +/** + * Called when a player edits or signs a book and quill item. If the event is + * cancelled, no changes are made to the BookMeta + */ +public class PlayerEditBookEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + + private final BookMeta previousBookMeta; + private final int slot; + private BookMeta newBookMeta; + private boolean isSigning; + private boolean cancel; + + public PlayerEditBookEvent(Player who, int slot, BookMeta previousBookMeta, BookMeta newBookMeta, boolean isSigning) { + super(who); + + Validate.isTrue(slot >= 0 && slot <=8, "Slot must be in range 0-8 inclusive"); + Validate.notNull(previousBookMeta, "Previous book meta must not be null"); + Validate.notNull(newBookMeta, "New book meta must not be null"); + + Bukkit.getItemFactory().equals(previousBookMeta, newBookMeta); + + this.previousBookMeta = previousBookMeta; + this.newBookMeta = newBookMeta; + this.slot = slot; + this.isSigning = isSigning; + this.cancel = false; + } + + /** + * Gets the book meta currently on the book. + *

          + * Note: this is a copy of the book meta. You cannot use this object to + * change the existing book meta. + * + * @return the book meta currently on the book + */ + public BookMeta getPreviousBookMeta() { + return previousBookMeta.clone(); + } + + /** + * Gets the book meta that the player is attempting to add to the book. + *

          + * Note: this is a copy of the proposed new book meta. Use {@link + * #setNewBookMeta(BookMeta)} to change what will actually be added to the + * book. + * + * @return the book meta that the player is attempting to add + */ + public BookMeta getNewBookMeta() { + return newBookMeta.clone(); + } + + /** + * Gets the inventory slot number for the book item that triggered this + * event. + *

          + * This is a slot number on the player's hotbar in the range 0-8. + * + * @return the inventory slot number that the book item occupies + */ + public int getSlot() { + return slot; + } + + /** + * Sets the book meta that will actually be added to the book. + * + * @param newBookMeta new book meta + * @throws IllegalArgumentException if the new book meta is null + */ + public void setNewBookMeta(BookMeta newBookMeta) throws IllegalArgumentException { + Validate.notNull(newBookMeta, "New book meta must not be null"); + Bukkit.getItemFactory().equals(newBookMeta, null); + this.newBookMeta = newBookMeta.clone(); + } + + /** + * Gets whether or not the book is being signed. If a book is signed the + * Material changes from BOOK_AND_QUILL to WRITTEN_BOOK. + * + * @return true if the book is being signed + */ + public boolean isSigning() { + return isSigning; + } + + /** + * Sets whether or not the book is being signed. If a book is signed the + * Material changes from BOOK_AND_QUILL to WRITTEN_BOOK. + * + * @param signing whether or not the book is being signed. + */ + public void setSigning(boolean signing) { + isSigning = signing; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java b/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java new file mode 100644 index 0000000..896347e --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java @@ -0,0 +1,137 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.CreatureType; +import org.bukkit.entity.Egg; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player throws an egg and it might hatch + */ +public class PlayerEggThrowEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final Egg egg; + private boolean hatching; + private EntityType hatchType; + private byte numHatches; + + public PlayerEggThrowEvent(final Player player, final Egg egg, final boolean hatching, final byte numHatches, final EntityType hatchingType) { + super(player); + this.egg = egg; + this.hatching = hatching; + this.numHatches = numHatches; + this.hatchType = hatchingType; + } + + @Deprecated + public PlayerEggThrowEvent(Player player, Egg egg, boolean hatching, byte numHatches, CreatureType hatchingType) { + this(player, egg, hatching, numHatches, hatchingType.toEntityType()); + } + + /** + * Gets the egg involved in this event. + * + * @return the egg involved in this event + */ + public Egg getEgg() { + return egg; + } + + /** + * Gets whether the egg is hatching or not. Will be what the server + * would've done without interaction. + * + * @return boolean Whether the egg is going to hatch or not + */ + public boolean isHatching() { + return hatching; + } + + /** + * Sets whether the egg will hatch or not. + * + * @param hatching true if you want the egg to hatch, false if you want it + * not to + */ + public void setHatching(boolean hatching) { + this.hatching = hatching; + } + + /** + * Get the type of the mob being hatched (EntityType.CHICKEN by default) + * + * @return The type of the mob being hatched by the egg + * @deprecated In favour of {@link #getHatchingType()}. + */ + @Deprecated + public CreatureType getHatchType() { + return CreatureType.fromEntityType(hatchType); + } + + /** + * Get the type of the mob being hatched (EntityType.CHICKEN by default) + * + * @return The type of the mob being hatched by the egg + */ + public EntityType getHatchingType() { + return hatchType; + } + + /** + * Change the type of mob being hatched by the egg + * + * @param hatchType The type of the mob being hatched by the egg + * @deprecated In favour of {@link #setHatchingType(EntityType)}. + */ + @Deprecated + public void setHatchType(CreatureType hatchType) { + this.hatchType = hatchType.toEntityType(); + } + + /** + * Change the type of mob being hatched by the egg + * + * @param hatchType The type of the mob being hatched by the egg + */ + public void setHatchingType(EntityType hatchType) { + if(!hatchType.isSpawnable()) throw new IllegalArgumentException("Can't spawn that entity type from an egg!"); + this.hatchType = hatchType; + } + + /** + * Get the number of mob hatches from the egg. By default the number will + * be the number the server would've done + *

            + *
          • 7/8 chance of being 0 + *
          • 31/256 ~= 1/8 chance to be 1 + *
          • 1/256 chance to be 4 + *
          + * + * @return The number of mobs going to be hatched by the egg + */ + public byte getNumHatches() { + return numHatches; + } + + /** + * Change the number of mobs coming out of the hatched egg + *

          + * The boolean hatching will override this number. Ie. If hatching = + * false, this number will not matter + * + * @param numHatches The number of mobs coming out of the egg + */ + public void setNumHatches(byte numHatches) { + this.numHatches = numHatches; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerEvent.java b/src/main/java/org/bukkit/event/player/PlayerEvent.java new file mode 100644 index 0000000..0d4833f --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerEvent.java @@ -0,0 +1,30 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; + +/** + * Represents a player related event + */ +public abstract class PlayerEvent extends Event { + protected Player player; + + public PlayerEvent(final Player who) { + player = who; + } + + PlayerEvent(final Player who, boolean async) { + super(async); + player = who; + + } + + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final Player getPlayer() { + return player; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java b/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java new file mode 100644 index 0000000..f37491d --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java @@ -0,0 +1,44 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a players experience changes naturally + */ +public class PlayerExpChangeEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private int exp; + + public PlayerExpChangeEvent(final Player player, final int expAmount) { + super(player); + exp = expAmount; + } + + /** + * Get the amount of experience the player will receive + * + * @return The amount of experience + */ + public int getAmount() { + return exp; + } + + /** + * Set the amount of experience the player will receive + * + * @param amount The amount of experience to set + */ + public void setAmount(int amount) { + exp = amount; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerFishEvent.java b/src/main/java/org/bukkit/event/player/PlayerFishEvent.java new file mode 100644 index 0000000..e92acdf --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerFishEvent.java @@ -0,0 +1,135 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Fish; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a player is fishing + */ +public class PlayerFishEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private boolean cancel = false; + private int exp; + private final State state; + private final Fish hookEntity; + + /** + * @deprecated replaced by {@link #PlayerFishEvent(Player, Entity, Fish, + * State)} to include the {@link Fish} hook entity. + * @param player + * @param entity + * @param state + */ + @Deprecated + public PlayerFishEvent(final Player player, final Entity entity, final State state) { + this(player, entity, null, state); + } + + public PlayerFishEvent(final Player player, final Entity entity, final Fish hookEntity, final State state) { + super(player); + this.entity = entity; + this.hookEntity = hookEntity; + this.state = state; + } + + /** + * Gets the entity caught by the player + * + * @return Entity caught by the player, null if fishing, bobber has gotten + * stuck in the ground or nothing has been caught + */ + public Entity getCaught() { + return entity; + } + + /** + * Gets the fishing hook. + * + * @return Fish the entity representing the fishing hook/bobber. + */ + public Fish getHook() { + return hookEntity; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the amount of experience received when fishing. + *

          + * Note: This value has no default effect unless the event state is {@link + * State#CAUGHT_FISH}. + * + * @return the amount of experience to drop + */ + public int getExpToDrop() { + return exp; + } + + /** + * Sets the amount of experience received when fishing. + *

          + * Note: This value has no default effect unless the event state is {@link + * State#CAUGHT_FISH}. + * + * @param amount the amount of experience to drop + */ + public void setExpToDrop(int amount) { + exp = amount; + } + + /** + * Gets the state of the fishing + * + * @return A State detailing the state of the fishing + */ + public State getState() { + return state; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the state of the fishing + */ + public enum State { + + /** + * When a player is fishing, ie casting the line out. + */ + FISHING, + /** + * When a player has successfully caught a fish and is reeling it in. + */ + CAUGHT_FISH, + /** + * When a player has successfully caught an entity + */ + CAUGHT_ENTITY, + /** + * When a bobber is stuck in the ground + */ + IN_GROUND, + /** + * When a player fails to catch anything while fishing usually due to + * poor aiming or timing + */ + FAILED_ATTEMPT, + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java b/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java new file mode 100644 index 0000000..8c9afa8 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when the GameMode of the player is changed. + */ +public class PlayerGameModeChangeEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final GameMode newGameMode; + + public PlayerGameModeChangeEvent(final Player player, final GameMode newGameMode) { + super(player); + this.newGameMode = newGameMode; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Gets the GameMode the player is switched to. + * + * @return player's new GameMode + */ + public GameMode getNewGameMode() { + return newGameMode; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java b/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java new file mode 100644 index 0000000..935211d --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Represents an event that is called when a player right clicks an entity. + */ +public class PlayerInteractEntityEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected Entity clickedEntity; + boolean cancelled = false; + + public PlayerInteractEntityEvent(final Player who, final Entity clickedEntity) { + super(who); + this.clickedEntity = clickedEntity; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Gets the entity that was rightclicked by the player. + * + * @return entity right clicked by player + */ + public Entity getRightClicked() { + return this.clickedEntity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java b/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java new file mode 100644 index 0000000..59567d9 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java @@ -0,0 +1,187 @@ +package org.bukkit.event.player; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.block.Action; + +/** + * Called when a player interacts with an object or air. + */ +public class PlayerInteractEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected ItemStack item; + protected Action action; + protected Block blockClicked; + protected BlockFace blockFace; + private Result useClickedBlock; + private Result useItemInHand; + + public PlayerInteractEvent(final Player who, final Action action, final ItemStack item, final Block clickedBlock, final BlockFace clickedFace) { + super(who); + this.action = action; + this.item = item; + this.blockClicked = clickedBlock; + this.blockFace = clickedFace; + + useItemInHand = Result.DEFAULT; + useClickedBlock = clickedBlock == null ? Result.DENY : Result.ALLOW; + } + + /** + * Returns the action type + * + * @return Action returns the type of interaction + */ + public Action getAction() { + return action; + } + + /** + * Gets the cancellation state of this event. Set to true if you want to + * prevent buckets from placing water and so forth + * + * @return boolean cancellation state + */ + public boolean isCancelled() { + return useInteractedBlock() == Result.DENY; + } + + /** + * Sets the cancellation state of this event. A canceled event will not be + * executed in the server, but will still pass to other plugins + *

          + * Canceling this event will prevent use of food (player won't lose the + * food item), prevent bows/snowballs/eggs from firing, etc. (player won't + * lose the ammo) + * + * @param cancel true if you wish to cancel this event + */ + public void setCancelled(boolean cancel) { + setUseInteractedBlock(cancel ? Result.DENY : useInteractedBlock() == Result.DENY ? Result.DEFAULT : useInteractedBlock()); + setUseItemInHand(cancel ? Result.DENY : useItemInHand() == Result.DENY ? Result.DEFAULT : useItemInHand()); + } + + /** + * Returns the item in hand represented by this event + * + * @return ItemStack the item used + */ + public ItemStack getItem() { + return this.item; + } + + /** + * Convenience method. Returns the material of the item represented by + * this event + * + * @return Material the material of the item used + */ + public Material getMaterial() { + if (!hasItem()) { + return Material.AIR; + } + + return item.getType(); + } + + /** + * Check if this event involved a block + * + * @return boolean true if it did + */ + public boolean hasBlock() { + return this.blockClicked != null; + } + + /** + * Check if this event involved an item + * + * @return boolean true if it did + */ + public boolean hasItem() { + return this.item != null; + } + + /** + * Convenience method to inform the user whether this was a block + * placement event. + * + * @return boolean true if the item in hand was a block + */ + public boolean isBlockInHand() { + if (!hasItem()) { + return false; + } + + return item.getType().isBlock(); + } + + /** + * Returns the clicked block + * + * @return Block returns the block clicked with this item. + */ + public Block getClickedBlock() { + return blockClicked; + } + + /** + * Returns the face of the block that was clicked + * + * @return BlockFace returns the face of the block that was clicked + */ + public BlockFace getBlockFace() { + return blockFace; + } + + /** + * This controls the action to take with the block (if any) that was + * clicked on. This event gets processed for all blocks, but most don't + * have a default action + * + * @return the action to take with the interacted block + */ + public Result useInteractedBlock() { + return useClickedBlock; + } + + /** + * @param useInteractedBlock the action to take with the interacted block + */ + public void setUseInteractedBlock(Result useInteractedBlock) { + this.useClickedBlock = useInteractedBlock; + } + + /** + * This controls the action to take with the item the player is holding. + * This includes both blocks and items (such as flint and steel or + * records). When this is set to default, it will be allowed if no action + * is taken on the interacted block. + * + * @return the action to take with the item in hand + */ + public Result useItemInHand() { + return useItemInHand; + } + + /** + * @param useItemInHand the action to take with the item in hand + */ + public void setUseItemInHand(Result useItemInHand) { + this.useItemInHand = useItemInHand; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerInventoryEvent.java b/src/main/java/org/bukkit/event/player/PlayerInventoryEvent.java new file mode 100644 index 0000000..2ec69d7 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerInventoryEvent.java @@ -0,0 +1,44 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.inventory.Inventory; + +/** + * Represents a player related inventory event; note that this event never + * actually did anything + * + * @deprecated Use {@link InventoryClickEvent} or {@link InventoryOpenEvent} + * instead, or one of the other inventory events in {@link + * org.bukkit.event.inventory}. + */ +@Deprecated +public class PlayerInventoryEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + protected Inventory inventory; + + public PlayerInventoryEvent(final Player player, final Inventory inventory) { + super(player); + this.inventory = inventory; + } + + /** + * Gets the Inventory involved in this event + * + * @return Inventory + */ + public Inventory getInventory() { + return inventory; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java b/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java new file mode 100644 index 0000000..176cd91 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java @@ -0,0 +1,39 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Fired when a player's item breaks (such as a shovel or flint and steel). + *

          + * The item that's breaking will exist in the inventory with a stack size of + * 0. After the event, the item's durability will be reset to 0. + */ +public class PlayerItemBreakEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final ItemStack brokenItem; + + public PlayerItemBreakEvent(final Player player, final ItemStack brokenItem) { + super(player); + this.brokenItem = brokenItem; + } + + /** + * Gets the item that broke + * + * @return The broken item + */ + public ItemStack getBrokenItem() { + return brokenItem; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java b/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java new file mode 100644 index 0000000..8ab76b1 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java @@ -0,0 +1,74 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * This event will fire when a player is finishing consuming an item (food, + * potion, milk bucket). + *
          + * If the ItemStack is modified the server will use the effects of the new + * item and not remove the original one from the player's inventory. + *
          + * If the event is cancelled the effect will not be applied and the item will + * not be removed from the player's inventory. + */ +public class PlayerItemConsumeEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean isCancelled = false; + private ItemStack item; + + /** + * @param player the player consuming + * @param item the ItemStack being consumed + */ + public PlayerItemConsumeEvent(final Player player, final ItemStack item) { + super(player); + + this.item = item; + } + + /** + * Gets the item that is being consumed. Modifying the returned item will + * have no effect, you must use {@link + * #setItem(org.bukkit.inventory.ItemStack)} instead. + * + * @return an ItemStack for the item being consumed + */ + public ItemStack getItem() { + return item.clone(); + } + + /** + * Set the item being consumed + * + * @param item the item being consumed + */ + public void setItem(ItemStack item) { + if (item == null) { + this.item = new ItemStack(Material.AIR); + } else { + this.item = item; + } + } + + public boolean isCancelled() { + return this.isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java b/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java new file mode 100644 index 0000000..f0d055a --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java @@ -0,0 +1,56 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Fired when a player changes their currently held item + */ +public class PlayerItemHeldEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private final int previous; + private final int current; + + public PlayerItemHeldEvent(final Player player, final int previous, final int current) { + super(player); + this.previous = previous; + this.current = current; + } + + /** + * Gets the previous held slot index + * + * @return Previous slot index + */ + public int getPreviousSlot() { + return previous; + } + + /** + * Gets the new held slot index + * + * @return New slot index + */ + public int getNewSlot() { + return current; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java b/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java new file mode 100644 index 0000000..e7481f9 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java @@ -0,0 +1,44 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player joins a server + */ +public class PlayerJoinEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private String joinMessage; + + public PlayerJoinEvent(final Player playerJoined, final String joinMessage) { + super(playerJoined); + this.joinMessage = joinMessage; + } + + /** + * Gets the join message to send to all online players + * + * @return string join message + */ + public String getJoinMessage() { + return joinMessage; + } + + /** + * Sets the join message to send to all online players + * + * @param joinMessage join message + */ + public void setJoinMessage(String joinMessage) { + this.joinMessage = joinMessage; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerKickEvent.java b/src/main/java/org/bukkit/event/player/PlayerKickEvent.java new file mode 100644 index 0000000..39e81b6 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerKickEvent.java @@ -0,0 +1,75 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player gets kicked from the server + */ +public class PlayerKickEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private String leaveMessage; + private String kickReason; + private Boolean cancel; + + public PlayerKickEvent(final Player playerKicked, final String kickReason, final String leaveMessage) { + super(playerKicked); + this.kickReason = kickReason; + this.leaveMessage = leaveMessage; + this.cancel = false; + } + + /** + * Gets the reason why the player is getting kicked + * + * @return string kick reason + */ + public String getReason() { + return kickReason; + } + + /** + * Gets the leave message send to all online players + * + * @return string kick reason + */ + public String getLeaveMessage() { + return leaveMessage; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Sets the reason why the player is getting kicked + * + * @param kickReason kick reason + */ + public void setReason(String kickReason) { + this.kickReason = kickReason; + } + + /** + * Sets the leave message send to all online players + * + * @param leaveMessage leave message + */ + public void setLeaveMessage(String leaveMessage) { + this.leaveMessage = leaveMessage; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java b/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java new file mode 100644 index 0000000..730a776 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a players level changes + */ +public class PlayerLevelChangeEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final int oldLevel; + private final int newLevel; + + public PlayerLevelChangeEvent(final Player player, final int oldLevel, final int newLevel) { + super(player); + this.oldLevel = oldLevel; + this.newLevel = newLevel; + } + + /** + * Gets the old level of the player + * + * @return The old level of the player + */ + public int getOldLevel() { + return oldLevel; + } + + /** + * Gets the new level of the player + * + * @return The new (current) level of the player + */ + public int getNewLevel() { + return newLevel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java b/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java new file mode 100644 index 0000000..b74b7b8 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java @@ -0,0 +1,188 @@ +package org.bukkit.event.player; + +import java.net.InetAddress; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Stores details for players attempting to log in + */ +public class PlayerLoginEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final InetAddress address; + private final String hostname; + private Result result = Result.ALLOWED; + private String message = ""; + + /** + * @deprecated Address should be provided in other constructor + */ + @Deprecated + public PlayerLoginEvent(final Player player) { + this(player, "", null); + } + + /** + * @deprecated Address should be provided in other constructor + */ + @Deprecated + public PlayerLoginEvent(final Player player, final String hostname) { + this(player, hostname, null); + } + + /** + * This constructor defaults message to an empty string, and result to + * ALLOWED + * + * @param player The {@link Player} for this event + * @param hostname The hostname that was used to connect to the server + * @param address The address the player used to connect, provided for + * timing issues + */ + public PlayerLoginEvent(final Player player, final String hostname, final InetAddress address) { + super(player); + this.hostname = hostname; + this.address = address; + } + + /** + * @deprecated Address and hostname should be provided in other + * constructor + */ + @Deprecated + public PlayerLoginEvent(final Player player, final Result result, final String message) { + this(player, "", null, result, message); + } + + /** + * This constructor pre-configures the event with a result and message + * + * @param player The {@link Player} for this event + * @param hostname The hostname that was used to connect to the server + * @param address The address the player used to connect, provided for + * timing issues + * @param result The result status for this event + * @param message The message to be displayed if result denies login + */ + public PlayerLoginEvent(final Player player, String hostname, final InetAddress address, final Result result, final String message) { + this(player, hostname, address); + this.result = result; + this.message = message; + } + + /** + * Gets the current result of the login, as an enum + * + * @return Current Result of the login + */ + public Result getResult() { + return result; + } + + /** + * Sets the new result of the login, as an enum + * + * @param result New result to set + */ + public void setResult(final Result result) { + this.result = result; + } + + /** + * Gets the current kick message that will be used if getResult() != + * Result.ALLOWED + * + * @return Current kick message + */ + public String getKickMessage() { + return message; + } + + /** + * Sets the kick message to display if getResult() != Result.ALLOWED + * + * @param message New kick message + */ + public void setKickMessage(final String message) { + this.message = message; + } + + /** + * Gets the hostname that the player used to connect to the server, or + * blank if unknown + * + * @return The hostname + */ + public String getHostname() { + return hostname; + } + + /** + * Allows the player to log in + */ + public void allow() { + result = Result.ALLOWED; + message = ""; + } + + /** + * Disallows the player from logging in, with the given reason + * + * @param result New result for disallowing the player + * @param message Kick message to display to the user + */ + public void disallow(final Result result, final String message) { + this.result = result; + this.message = message; + } + + /** + * Gets the {@link InetAddress} for the Player associated with this event. + * This method is provided as a workaround for player.getAddress() + * returning null during PlayerLoginEvent. + * + * @return The address for this player. For legacy compatibility, this may + * be null. + */ + public InetAddress getAddress() { + return address; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Basic kick reasons for communicating to plugins + */ + public enum Result { + + /** + * The player is allowed to log in + */ + ALLOWED, + /** + * The player is not allowed to log in, due to the server being full + */ + KICK_FULL, + /** + * The player is not allowed to log in, due to them being banned + */ + KICK_BANNED, + /** + * The player is not allowed to log in, due to them not being on the + * white list + */ + KICK_WHITELIST, + /** + * The player is not allowed to log in, for reasons undefined + */ + KICK_OTHER + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java b/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java new file mode 100644 index 0000000..fa3b340 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java @@ -0,0 +1,95 @@ +package org.bukkit.event.player; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Holds information for player movement events + */ +public class PlayerMoveEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private Location from; + private Location to; + + public PlayerMoveEvent(final Player player, final Location from, final Location to) { + super(player); + this.from = from; + this.to = to; + } + + /** + * Gets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins + *

          + * If a move or teleport event is cancelled, the player will be moved or + * teleported back to the Location as defined by getFrom(). This will not + * fire an event + * + * @return true if this event is cancelled + */ + public boolean isCancelled() { + return cancel; + } + + /** + * Sets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins + *

          + * If a move or teleport event is cancelled, the player will be moved or + * teleported back to the Location as defined by getFrom(). This will not + * fire an event + * + * @param cancel true if you wish to cancel this event + */ + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the location this player moved from + * + * @return Location the player moved from + */ + public Location getFrom() { + return from; + } + + /** + * Sets the location to mark as where the player moved from + * + * @param from New location to mark as the players previous location + */ + public void setFrom(Location from) { + this.from = from; + } + + /** + * Gets the location this player moved to + * + * @return Location the player moved to + */ + public Location getTo() { + return to; + } + + /** + * Sets the location that this player will move to + * + * @param to New Location this player will move to + */ + public void setTo(Location to) { + this.to = to; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java b/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java new file mode 100644 index 0000000..dfba816 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java @@ -0,0 +1,57 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a player picks an item up from the ground + */ +public class PlayerPickupItemEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Item item; + private boolean cancel = false; + private final int remaining; + + public PlayerPickupItemEvent(final Player player, final Item item, final int remaining) { + super(player); + this.item = item; + this.remaining = remaining; + } + + /** + * Gets the Item picked up by the player. + * + * @return Item + */ + public Item getItem() { + return item; + } + + /** + * Gets the amount remaining on the ground, if any + * + * @return amount remaining on the ground + */ + public int getRemaining() { + return remaining; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java b/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java new file mode 100644 index 0000000..93752f7 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java @@ -0,0 +1,87 @@ +package org.bukkit.event.player; + +import org.bukkit.Location; +import org.bukkit.TravelAgent; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player is about to teleport because it is in contact with a + * portal. + *

          + * For other entities see {@link org.bukkit.event.entity.EntityPortalEvent} + */ +public class PlayerPortalEvent extends PlayerTeleportEvent { + private static final HandlerList handlers = new HandlerList(); + protected boolean useTravelAgent = true; + protected TravelAgent travelAgent; + + public PlayerPortalEvent(final Player player, final Location from, final Location to, final TravelAgent pta) { + super(player, from, to); + this.travelAgent = pta; + } + + public PlayerPortalEvent(Player player, Location from, Location to, TravelAgent pta, TeleportCause cause) { + super(player, from, to, cause); + this.travelAgent = pta; + } + + /** + * Sets whether or not the Travel Agent will be used. + *

          + * If this is set to true, the TravelAgent will try to find a Portal at + * the {@link #getTo()} Location, and will try to create one if there is + * none. + *

          + * If this is set to false, the {@link #getPlayer()} will only be + * teleported to the {@link #getTo()} Location. + * + * @param useTravelAgent whether to use the Travel Agent + */ + public void useTravelAgent(boolean useTravelAgent) { + this.useTravelAgent = useTravelAgent; + } + + /** + * Gets whether or not the Travel Agent will be used. + *

          + * If this is set to true, the TravelAgent will try to find a Portal at + * the {@link #getTo()} Location, and will try to create one if there is + * none. + *

          + * If this is set to false, the {@link #getPlayer()}} will only be + * teleported to the {@link #getTo()} Location. + * + * @return whether to use the Travel Agent + */ + public boolean useTravelAgent() { + return useTravelAgent && travelAgent != null; + } + + /** + * Gets the Travel Agent used (or not) in this event. + * + * @return the Travel Agent used (or not) in this event + */ + public TravelAgent getPortalTravelAgent() { + return this.travelAgent; + } + + /** + * Sets the Travel Agent used (or not) in this event. + * + * @param travelAgent the Travel Agent used (or not) in this event + */ + public void setPortalTravelAgent(TravelAgent travelAgent) { + this.travelAgent = travelAgent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java b/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java new file mode 100644 index 0000000..e8553f0 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java @@ -0,0 +1,159 @@ +package org.bukkit.event.player; + +import java.net.InetAddress; +import java.util.UUID; + +import org.bukkit.Warning; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Stores details for players attempting to log in + * + * @deprecated This event causes synchronization from the login thread; {@link + * AsyncPlayerPreLoginEvent} is preferred to keep the secondary threads + * asynchronous. + */ +@Deprecated +@Warning(reason="This event causes a login thread to synchronize with the main thread") +public class PlayerPreLoginEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private Result result; + private String message; + private final String name; + private final InetAddress ipAddress; + private final UUID uniqueId; + + @Deprecated + public PlayerPreLoginEvent(final String name, final InetAddress ipAddress) { + this(name, ipAddress, null); + } + + public PlayerPreLoginEvent(final String name, final InetAddress ipAddress, final UUID uniqueId) { + this.result = Result.ALLOWED; + this.message = ""; + this.name = name; + this.ipAddress = ipAddress; + this.uniqueId = uniqueId; + } + + /** + * Gets the current result of the login, as an enum + * + * @return Current Result of the login + */ + public Result getResult() { + return result; + } + + /** + * Sets the new result of the login, as an enum + * + * @param result New result to set + */ + public void setResult(final Result result) { + this.result = result; + } + + /** + * Gets the current kick message that will be used if getResult() != + * Result.ALLOWED + * + * @return Current kick message + */ + public String getKickMessage() { + return message; + } + + /** + * Sets the kick message to display if getResult() != Result.ALLOWED + * + * @param message New kick message + */ + public void setKickMessage(final String message) { + this.message = message; + } + + /** + * Allows the player to log in + */ + public void allow() { + result = Result.ALLOWED; + message = ""; + } + + /** + * Disallows the player from logging in, with the given reason + * + * @param result New result for disallowing the player + * @param message Kick message to display to the user + */ + public void disallow(final Result result, final String message) { + this.result = result; + this.message = message; + } + + /** + * Gets the player's name. + * + * @return the player's name + */ + public String getName() { + return name; + } + + /** + * Gets the player IP address. + * + * @return The IP address + */ + public InetAddress getAddress() { + return ipAddress; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + /** + * Gets the player's unique ID. + * + * @return The unique ID + */ + public UUID getUniqueId() { + return uniqueId; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Basic kick reasons for communicating to plugins + */ + public enum Result { + + /** + * The player is allowed to log in + */ + ALLOWED, + /** + * The player is not allowed to log in, due to the server being full + */ + KICK_FULL, + /** + * The player is not allowed to log in, due to them being banned + */ + KICK_BANNED, + /** + * The player is not allowed to log in, due to them not being on the + * white list + */ + KICK_WHITELIST, + /** + * The player is not allowed to log in, for reasons undefined + */ + KICK_OTHER + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java b/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java new file mode 100644 index 0000000..5c8dc1b --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java @@ -0,0 +1,44 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player leaves a server + */ +public class PlayerQuitEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private String quitMessage; + + public PlayerQuitEvent(final Player who, final String quitMessage) { + super(who); + this.quitMessage = quitMessage; + } + + /** + * Gets the quit message to send to all online players + * + * @return string quit message + */ + public String getQuitMessage() { + return quitMessage; + } + + /** + * Sets the quit message to send to all online players + * + * @param quitMessage quit message + */ + public void setQuitMessage(String quitMessage) { + this.quitMessage = quitMessage; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java b/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java new file mode 100644 index 0000000..442ac7f --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java @@ -0,0 +1,13 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; + +/** + * This is called immediately after a player registers for a plugin channel. + */ +public class PlayerRegisterChannelEvent extends PlayerChannelEvent { + + public PlayerRegisterChannelEvent(final Player player, final String channel) { + super(player, channel); + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java b/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java new file mode 100644 index 0000000..35900dd --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java @@ -0,0 +1,60 @@ +package org.bukkit.event.player; + +import org.apache.commons.lang.Validate; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player respawns. + */ +public class PlayerRespawnEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private Location respawnLocation; + private final boolean isBedSpawn; + + public PlayerRespawnEvent(final Player respawnPlayer, final Location respawnLocation, final boolean isBedSpawn) { + super(respawnPlayer); + this.respawnLocation = respawnLocation; + this.isBedSpawn = isBedSpawn; + } + + /** + * Gets the current respawn location + * + * @return Location current respawn location + */ + public Location getRespawnLocation() { + return this.respawnLocation; + } + + /** + * Sets the new respawn location + * + * @param respawnLocation new location for the respawn + */ + public void setRespawnLocation(Location respawnLocation) { + Validate.notNull(respawnLocation, "Respawn location can not be null"); + Validate.notNull(respawnLocation.getWorld(), "Respawn world can not be null"); + + this.respawnLocation = respawnLocation; + } + + /** + * Gets whether the respawn location is the player's bed. + * + * @return true if the respawn location is the player's bed. + */ + public boolean isBedSpawn() { + return this.isBedSpawn; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java b/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java new file mode 100644 index 0000000..38afb3c --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player shears an entity + */ +public class PlayerShearEntityEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private final Entity what; + + public PlayerShearEntityEvent(final Player who, final Entity what) { + super(who); + this.cancel = false; + this.what = what; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the entity the player is shearing + * + * @return the entity the player is shearing + */ + public Entity getEntity() { + return what; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java b/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java new file mode 100644 index 0000000..3b64d70 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java @@ -0,0 +1,116 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player statistic is incremented. + *

          + * This event is not called for {@link org.bukkit.Statistic#PLAY_ONE_TICK} or + * movement based statistics. + * + */ +public class PlayerStatisticIncrementEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected final Statistic statistic; + private final int initialValue; + private final int newValue; + private boolean isCancelled = false; + private final EntityType entityType; + private final Material material; + + public PlayerStatisticIncrementEvent(Player player, Statistic statistic, int initialValue, int newValue) { + super (player); + this.statistic = statistic; + this.initialValue = initialValue; + this.newValue = newValue; + this.entityType = null; + this.material = null; + } + + public PlayerStatisticIncrementEvent(Player player, Statistic statistic, int initialValue, int newValue, EntityType entityType) { + super (player); + this.statistic = statistic; + this.initialValue = initialValue; + this.newValue = newValue; + this.entityType = entityType; + this.material = null; + } + + public PlayerStatisticIncrementEvent(Player player, Statistic statistic, int initialValue, int newValue, Material material) { + super (player); + this.statistic = statistic; + this.initialValue = initialValue; + this.newValue = newValue; + this.entityType = null; + this.material = material; + } + + /** + * Gets the statistic that is being incremented. + * + * @return the incremented statistic + */ + public Statistic getStatistic() { + return statistic; + } + + /** + * Gets the previous value of the statistic. + * + * @return the previous value of the statistic + */ + public int getPreviousValue() { + return initialValue; + } + + /** + * Gets the new value of the statistic. + * + * @return the new value of the statistic + */ + public int getNewValue() { + return newValue; + } + + /** + * Gets the EntityType if {@link #getStatistic() getStatistic()} is an + * entity statistic otherwise returns null. + * + * @return the EntityType of the statistic + */ + public EntityType getEntityType() { + return entityType; + } + + /** + * Gets the Material if {@link #getStatistic() getStatistic()} is a block + * or item statistic otherwise returns null. + * + * @return the Material of the statistic + */ + public Material getMaterial() { + return material; + } + + public boolean isCancelled() { + return isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java b/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java new file mode 100644 index 0000000..7e2e128 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java @@ -0,0 +1,73 @@ +package org.bukkit.event.player; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Holds information for player teleport events + */ +public class PlayerTeleportEvent extends PlayerMoveEvent { + private static final HandlerList handlers = new HandlerList(); + private TeleportCause cause = TeleportCause.UNKNOWN; + + public PlayerTeleportEvent(final Player player, final Location from, final Location to) { + super(player, from, to); + } + + public PlayerTeleportEvent(final Player player, final Location from, final Location to, final TeleportCause cause) { + this(player, from, to); + + this.cause = cause; + } + + /** + * Gets the cause of this teleportation event + * + * @return Cause of the event + */ + public TeleportCause getCause() { + return cause; + } + + public enum TeleportCause { + /** + * Indicates the teleporation was caused by a player throwing an Ender + * Pearl + */ + ENDER_PEARL, + /** + * Indicates the teleportation was caused by a player executing a + * command + */ + COMMAND, + /** + * Indicates the teleportation was caused by a plugin + */ + PLUGIN, + /** + * Indicates the teleportation was caused by a player entering a + * Nether portal + */ + NETHER_PORTAL, + /** + * Indicates the teleportation was caused by a player entering an End + * portal + */ + END_PORTAL, + /** + * Indicates the teleportation was caused by an event not covered by + * this enum + */ + UNKNOWN; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java b/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java new file mode 100644 index 0000000..1c5ec37 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player toggles their flying state + */ +public class PlayerToggleFlightEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final boolean isFlying; + private boolean cancel = false; + + public PlayerToggleFlightEvent(final Player player, final boolean isFlying) { + super(player); + this.isFlying = isFlying; + } + + /** + * Returns whether the player is trying to start or stop flying. + * + * @return flying state + */ + public boolean isFlying() { + return isFlying; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java b/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java new file mode 100644 index 0000000..667acad --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player toggles their sneaking state + */ +public class PlayerToggleSneakEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final boolean isSneaking; + private boolean cancel = false; + + public PlayerToggleSneakEvent(final Player player, final boolean isSneaking) { + super(player); + this.isSneaking = isSneaking; + } + + /** + * Returns whether the player is now sneaking or not. + * + * @return sneaking state + */ + public boolean isSneaking() { + return isSneaking; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java b/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java new file mode 100644 index 0000000..cf065e1 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player toggles their sprinting state + */ +public class PlayerToggleSprintEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final boolean isSprinting; + private boolean cancel = false; + + public PlayerToggleSprintEvent(final Player player, final boolean isSprinting) { + super(player); + this.isSprinting = isSprinting; + } + + /** + * Gets whether the player is now sprinting or not. + * + * @return sprinting state + */ + public boolean isSprinting() { + return isSprinting; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java b/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java new file mode 100644 index 0000000..f6aebef --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.entity.EntityUnleashEvent; + +/** + * Called prior to an entity being unleashed due to a player's action. + */ +public class PlayerUnleashEntityEvent extends EntityUnleashEvent implements Cancellable { + private final Player player; + private boolean cancelled = false; + + public PlayerUnleashEntityEvent(Entity entity, Player player) { + super(entity, UnleashReason.PLAYER_UNLEASH); + this.player = player; + } + + /** + * Returns the player who is unleashing the entity. + * + * @return The player + */ + public Player getPlayer() { + return player; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java b/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java new file mode 100644 index 0000000..11c77e3 --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java @@ -0,0 +1,13 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; + +/** + * This is called immediately after a player unregisters for a plugin channel. + */ +public class PlayerUnregisterChannelEvent extends PlayerChannelEvent { + + public PlayerUnregisterChannelEvent(final Player player, final String channel) { + super(player, channel); + } +} diff --git a/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java b/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java new file mode 100644 index 0000000..69d2fce --- /dev/null +++ b/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java @@ -0,0 +1,55 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.util.Vector; + +/** + * Called when the velocity of a player changes. + */ +public class PlayerVelocityEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private Vector velocity; + + public PlayerVelocityEvent(final Player player, final Vector velocity) { + super(player); + this.velocity = velocity; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the velocity vector that will be sent to the player + * + * @return Vector the player will get + */ + public Vector getVelocity() { + return velocity; + } + + /** + * Sets the velocity vector that will be sent to the player + * + * @param velocity The velocity vector that will be sent to the player + */ + public void setVelocity(Vector velocity) { + this.velocity = velocity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/server/MapInitializeEvent.java b/src/main/java/org/bukkit/event/server/MapInitializeEvent.java new file mode 100644 index 0000000..8834489 --- /dev/null +++ b/src/main/java/org/bukkit/event/server/MapInitializeEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.map.MapView; + +/** + * Called when a map is initialized. + */ +public class MapInitializeEvent extends ServerEvent { + private static final HandlerList handlers = new HandlerList(); + private final MapView mapView; + + public MapInitializeEvent(final MapView mapView) { + this.mapView = mapView; + } + + /** + * Gets the map initialized in this event. + * + * @return Map for this event + */ + public MapView getMap() { + return mapView; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/server/PluginDisableEvent.java b/src/main/java/org/bukkit/event/server/PluginDisableEvent.java new file mode 100644 index 0000000..932c4fd --- /dev/null +++ b/src/main/java/org/bukkit/event/server/PluginDisableEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.Plugin; + +/** + * Called when a plugin is disabled. + */ +public class PluginDisableEvent extends PluginEvent { + private static final HandlerList handlers = new HandlerList(); + + public PluginDisableEvent(final Plugin plugin) { + super(plugin); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/server/PluginEnableEvent.java b/src/main/java/org/bukkit/event/server/PluginEnableEvent.java new file mode 100644 index 0000000..865316d --- /dev/null +++ b/src/main/java/org/bukkit/event/server/PluginEnableEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.Plugin; + +/** + * Called when a plugin is enabled. + */ +public class PluginEnableEvent extends PluginEvent { + private static final HandlerList handlers = new HandlerList(); + + public PluginEnableEvent(final Plugin plugin) { + super(plugin); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/server/PluginEvent.java b/src/main/java/org/bukkit/event/server/PluginEvent.java new file mode 100644 index 0000000..1ad656d --- /dev/null +++ b/src/main/java/org/bukkit/event/server/PluginEvent.java @@ -0,0 +1,23 @@ +package org.bukkit.event.server; + +import org.bukkit.plugin.Plugin; + +/** + * Used for plugin enable and disable events + */ +public abstract class PluginEvent extends ServerEvent { + private final Plugin plugin; + + public PluginEvent(final Plugin plugin) { + this.plugin = plugin; + } + + /** + * Gets the plugin involved in this event + * + * @return Plugin for this event + */ + public Plugin getPlugin() { + return plugin; + } +} diff --git a/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java b/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java new file mode 100644 index 0000000..2a49237 --- /dev/null +++ b/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java @@ -0,0 +1,25 @@ +package org.bukkit.event.server; + +import org.bukkit.command.CommandSender; +import org.bukkit.event.HandlerList; + +/** + * This event is called when a command is recieved over RCON. See the javadocs + * of {@link ServerCommandEvent} for more information. + */ +public class RemoteServerCommandEvent extends ServerCommandEvent { + private static final HandlerList handlers = new HandlerList(); + + public RemoteServerCommandEvent(final CommandSender sender, final String command) { + super(sender, command); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/server/ServerCommandEvent.java b/src/main/java/org/bukkit/event/server/ServerCommandEvent.java new file mode 100644 index 0000000..8a5972a --- /dev/null +++ b/src/main/java/org/bukkit/event/server/ServerCommandEvent.java @@ -0,0 +1,86 @@ +package org.bukkit.event.server; + +import org.bukkit.command.CommandSender; +import org.bukkit.event.HandlerList; + +/** + * This event is called when a command is run from the server console. It is + * called early in the command handling process, and modifications in this + * event (via {@link #setCommand(String)}) will be shown in the behavior. + *

          + * Many plugins will have no use for this event, and you should + * attempt to avoid using it if it is not necessary. + *

          + * Some examples of valid uses for this event are: + *

            + *
          • Logging executed commands to a separate file + *
          • Variable substitution. For example, replacing ${ip:Steve} + * with the connection IP of the player named Steve, or simulating the + * @a and @p decorators used by Command Blocks + * for plugins that do not handle it. + *
          • Conditionally blocking commands belonging to other plugins. + *
          • Per-sender command aliases. For example, after the console runs the + * command /calias cr gamemode creative, the next time they + * run /cr, it gets replaced into + * /gamemode creative. (Global command aliases should be + * done by registering the alias.) + *
          + *

          + * Examples of incorrect uses are: + *

            + *
          • Using this event to run command logic + *
          + *

          + * If the event is cancelled, processing of the command will halt. + *

          + * The state of whether or not there is a slash (/) at the + * beginning of the message should be preserved. If a slash is added or + * removed, unexpected behavior may result. + */ +public class ServerCommandEvent extends ServerEvent { + private static final HandlerList handlers = new HandlerList(); + private String command; + private final CommandSender sender; + + public ServerCommandEvent(final CommandSender sender, final String command) { + this.command = command; + this.sender = sender; + } + + /** + * Gets the command that the user is attempting to execute from the + * console + * + * @return Command the user is attempting to execute + */ + public String getCommand() { + return command; + } + + /** + * Sets the command that the server will execute + * + * @param message New message that the server will execute + */ + public void setCommand(String message) { + this.command = message; + } + + /** + * Get the command sender. + * + * @return The sender + */ + public CommandSender getSender() { + return sender; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/server/ServerEvent.java b/src/main/java/org/bukkit/event/server/ServerEvent.java new file mode 100644 index 0000000..eb00d6a --- /dev/null +++ b/src/main/java/org/bukkit/event/server/ServerEvent.java @@ -0,0 +1,9 @@ +package org.bukkit.event.server; + +import org.bukkit.event.Event; + +/** + * Miscellaneous server events + */ +public abstract class ServerEvent extends Event { +} diff --git a/src/main/java/org/bukkit/event/server/ServerListPingEvent.java b/src/main/java/org/bukkit/event/server/ServerListPingEvent.java new file mode 100644 index 0000000..c61afdf --- /dev/null +++ b/src/main/java/org/bukkit/event/server/ServerListPingEvent.java @@ -0,0 +1,142 @@ +package org.bukkit.event.server; + +import java.net.InetAddress; +import java.util.Iterator; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.util.CachedServerIcon; + +/** + * Called when a server list ping is coming in. Displayed players can be + * checked and removed by {@link #iterator() iterating} over this event. + */ +public class ServerListPingEvent extends ServerEvent implements Iterable { + private static final int MAGIC_PLAYER_COUNT = Integer.MIN_VALUE; + private static final HandlerList handlers = new HandlerList(); + private final InetAddress address; + private String motd; + private final int numPlayers; + private int maxPlayers; + + public ServerListPingEvent(final InetAddress address, final String motd, final int numPlayers, final int maxPlayers) { + Validate.isTrue(numPlayers >= 0, "Cannot have negative number of players online", numPlayers); + this.address = address; + this.motd = motd; + this.numPlayers = numPlayers; + this.maxPlayers = maxPlayers; + } + + /** + * This constructor is intended for implementations that provide the + * {@link #iterator()} method, thus provided the {@link #getNumPlayers()} + * count. + */ + protected ServerListPingEvent(final InetAddress address, final String motd, final int maxPlayers) { + this.numPlayers = MAGIC_PLAYER_COUNT; + this.address = address; + this.motd = motd; + this.maxPlayers = maxPlayers; + } + + /** + * Get the address the ping is coming from. + * + * @return the address + */ + public InetAddress getAddress() { + return address; + } + + /** + * Get the message of the day message. + * + * @return the message of the day + */ + public String getMotd() { + return motd; + } + + /** + * Change the message of the day message. + * + * @param motd the message of the day + */ + public void setMotd(String motd) { + this.motd = motd; + } + + /** + * Get the number of players sent. + * + * @return the number of players + */ + public int getNumPlayers() { + int numPlayers = this.numPlayers; + if (numPlayers == MAGIC_PLAYER_COUNT) { + numPlayers = 0; + for (@SuppressWarnings("unused") final Player player : this) { + numPlayers++; + } + } + return numPlayers; + } + + /** + * Get the maximum number of players sent. + * + * @return the maximum number of players + */ + public int getMaxPlayers() { + return maxPlayers; + } + + /** + * Set the maximum number of players sent. + * + * @param maxPlayers the maximum number of player + */ + public void setMaxPlayers(int maxPlayers) { + this.maxPlayers = maxPlayers; + } + + /** + * Sets the server-icon sent to the client. + * + * @param icon the icon to send to the client + * @throws IllegalArgumentException if the {@link CachedServerIcon} is not + * created by the caller of this event; null may be accepted for some + * implementations + * @throws UnsupportedOperationException if the caller of this event does + * not support setting the server icon + */ + public void setServerIcon(CachedServerIcon icon) throws IllegalArgumentException, UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * {@inheritDoc} + *

          + * Calling the {@link Iterator#remove()} method will force that particular + * player to not be displayed on the player list, decrease the size + * returned by {@link #getNumPlayers()}, and will not be returned again by + * any new iterator. + * + * @throws UnsupportedOperationException if the caller of this event does + * not support removing players + */ + @Override + public Iterator iterator() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/org/bukkit/event/server/ServiceEvent.java b/src/main/java/org/bukkit/event/server/ServiceEvent.java new file mode 100644 index 0000000..69bf872 --- /dev/null +++ b/src/main/java/org/bukkit/event/server/ServiceEvent.java @@ -0,0 +1,19 @@ +package org.bukkit.event.server; + +import org.bukkit.plugin.RegisteredServiceProvider; + +/** + * An event relating to a registered service. This is called in a {@link + * org.bukkit.plugin.ServicesManager} + */ +public abstract class ServiceEvent extends ServerEvent { + private final RegisteredServiceProvider provider; + + public ServiceEvent(final RegisteredServiceProvider provider) { + this.provider = provider; + } + + public RegisteredServiceProvider getProvider() { + return provider; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java b/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java new file mode 100644 index 0000000..7dfadde --- /dev/null +++ b/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java @@ -0,0 +1,27 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.RegisteredServiceProvider; + +/** + * This event is called when a service is registered. + *

          + * Warning: The order in which register and unregister events are called + * should not be relied upon. + */ +public class ServiceRegisterEvent extends ServiceEvent { + private static final HandlerList handlers = new HandlerList(); + + public ServiceRegisterEvent(RegisteredServiceProvider registeredProvider) { + super(registeredProvider); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java b/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java new file mode 100644 index 0000000..db61d23 --- /dev/null +++ b/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java @@ -0,0 +1,27 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.RegisteredServiceProvider; + +/** + * This event is called when a service is unregistered. + *

          + * Warning: The order in which register and unregister events are called + * should not be relied upon. + */ +public class ServiceUnregisterEvent extends ServiceEvent { + private static final HandlerList handlers = new HandlerList(); + + public ServiceUnregisterEvent(RegisteredServiceProvider serviceProvider) { + super(serviceProvider); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java new file mode 100644 index 0000000..b643b57 --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.block.Block; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle collides with a block. + */ +public class VehicleBlockCollisionEvent extends VehicleCollisionEvent { + private static final HandlerList handlers = new HandlerList(); + private final Block block; + + public VehicleBlockCollisionEvent(final Vehicle vehicle, final Block block) { + super(vehicle); + this.block = block; + } + + /** + * Gets the block the vehicle collided with + * + * @return the block the vehicle collided with + */ + public Block getBlock() { + return block; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java new file mode 100644 index 0000000..9dd0579 --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java @@ -0,0 +1,12 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Vehicle; + +/** + * Raised when a vehicle collides. + */ +public abstract class VehicleCollisionEvent extends VehicleEvent { + public VehicleCollisionEvent(final Vehicle vehicle) { + super(vehicle); + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java new file mode 100644 index 0000000..22eda72 --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Vehicle; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle is created. + */ +public class VehicleCreateEvent extends VehicleEvent { + private static final HandlerList handlers = new HandlerList(); + + public VehicleCreateEvent(final Vehicle vehicle) { + super(vehicle); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java new file mode 100644 index 0000000..304ee2c --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java @@ -0,0 +1,92 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.util.NumberConversions; + +/** + * Raised when a vehicle receives damage. + */ +public class VehicleDamageEvent extends VehicleEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity attacker; + private double damage; + private boolean cancelled; + + @Deprecated + public VehicleDamageEvent(final Vehicle vehicle, final Entity attacker, final int damage) { + this(vehicle, attacker, (double) damage); + } + + public VehicleDamageEvent(final Vehicle vehicle, final Entity attacker, final double damage) { + super(vehicle); + this.attacker = attacker; + this.damage = damage; + } + + /** + * Gets the Entity that is attacking the vehicle + * + * @return the Entity that is attacking the vehicle + */ + public Entity getAttacker() { + return attacker; + } + + /** + * Gets the damage done to the vehicle + * + * @return the damage done to the vehicle + */ + public double getDamage() { + return damage; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public int _INVALID_getDamage() { + return NumberConversions.ceil(getDamage()); + } + + /** + * Sets the damage done to the vehicle + * + * @param damage The damage + */ + public void setDamage(double damage) { + this.damage = damage; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + */ + @Deprecated + public void _INVALID_setDamage(int damage) { + setDamage(damage); + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java new file mode 100644 index 0000000..f1176fd --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle is destroyed, which could be caused by either a + * player or the environment. This is not raised if the boat is simply + * 'removed' due to other means. + */ +public class VehicleDestroyEvent extends VehicleEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity attacker; + private boolean cancelled; + + public VehicleDestroyEvent(final Vehicle vehicle, final Entity attacker) { + super(vehicle); + this.attacker = attacker; + } + + /** + * Gets the Entity that has destroyed the vehicle, potentially null + * + * @return the Entity that has destroyed the vehicle, potentially null + */ + public Entity getAttacker() { + return attacker; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java new file mode 100644 index 0000000..85c9b21 --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Raised when an entity enters a vehicle. + */ +public class VehicleEnterEvent extends VehicleEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Entity entered; + + public VehicleEnterEvent(final Vehicle vehicle, final Entity entered) { + super(vehicle); + this.entered = entered; + } + + /** + * Gets the Entity that entered the vehicle. + * + * @return the Entity that entered the vehicle + */ + public Entity getEntered() { + return entered; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java new file mode 100644 index 0000000..4d4d0e2 --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle collides with an entity. + */ +public class VehicleEntityCollisionEvent extends VehicleCollisionEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private boolean cancelled = false; + private boolean cancelledPickup = false; + private boolean cancelledCollision = false; + + public VehicleEntityCollisionEvent(final Vehicle vehicle, final Entity entity) { + super(vehicle); + this.entity = entity; + } + + public Entity getEntity() { + return entity; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public boolean isPickupCancelled() { + return cancelledPickup; + } + + public void setPickupCancelled(boolean cancel) { + cancelledPickup = cancel; + } + + public boolean isCollisionCancelled() { + return cancelledCollision; + } + + public void setCollisionCancelled(boolean cancel) { + cancelledCollision = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java new file mode 100644 index 0000000..b8255c0 --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Event; + +/** + * Represents a vehicle-related event. + */ +public abstract class VehicleEvent extends Event { + protected Vehicle vehicle; + + public VehicleEvent(final Vehicle vehicle) { + this.vehicle = vehicle; + } + + /** + * Get the vehicle. + * + * @return the vehicle + */ + public final Vehicle getVehicle() { + return vehicle; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java new file mode 100644 index 0000000..364451b --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Raised when a living entity exits a vehicle. + */ +public class VehicleExitEvent extends VehicleEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final LivingEntity exited; + + public VehicleExitEvent(final Vehicle vehicle, final LivingEntity exited) { + super(vehicle); + this.exited = exited; + } + + /** + * Get the living entity that exited the vehicle. + * + * @return The entity. + */ + public LivingEntity getExited() { + return exited; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java new file mode 100644 index 0000000..9a13e29 --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java @@ -0,0 +1,49 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.Location; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle moves. + */ +public class VehicleMoveEvent extends VehicleEvent { + private static final HandlerList handlers = new HandlerList(); + private final Location from; + private final Location to; + + public VehicleMoveEvent(final Vehicle vehicle, final Location from, final Location to) { + super(vehicle); + + this.from = from; + this.to = to; + } + + /** + * Get the previous position. + * + * @return Old position. + */ + public Location getFrom() { + return from; + } + + /** + * Get the next position. + * + * @return New position. + */ + public Location getTo() { + return to; + } + + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java new file mode 100644 index 0000000..eebfdb1 --- /dev/null +++ b/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Vehicle; +import org.bukkit.event.HandlerList; + +/** + * Called when a vehicle updates + */ +public class VehicleUpdateEvent extends VehicleEvent { + private static final HandlerList handlers = new HandlerList(); + + public VehicleUpdateEvent(final Vehicle vehicle) { + super(vehicle); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java b/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java new file mode 100644 index 0000000..66fd763 --- /dev/null +++ b/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.weather; + +import org.bukkit.World; +import org.bukkit.entity.LightningStrike; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Stores data for lightning striking + */ +public class LightningStrikeEvent extends WeatherEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final LightningStrike bolt; + + public LightningStrikeEvent(final World world, final LightningStrike bolt) { + super(world); + this.bolt = bolt; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + /** + * Gets the bolt which is striking the earth. + * + * @return lightning entity + */ + public LightningStrike getLightning() { + return bolt; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java b/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java new file mode 100644 index 0000000..5e3716e --- /dev/null +++ b/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.weather; + +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Stores data for thunder state changing in a world + */ +public class ThunderChangeEvent extends WeatherEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final boolean to; + + public ThunderChangeEvent(final World world, final boolean to) { + super(world); + this.to = to; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + /** + * Gets the state of thunder that the world is being set to + * + * @return true if the weather is being set to thundering, false otherwise + */ + public boolean toThunderState() { + return to; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java b/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java new file mode 100644 index 0000000..5d1234e --- /dev/null +++ b/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.weather; + +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Stores data for weather changing in a world + */ +public class WeatherChangeEvent extends WeatherEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final boolean to; + + public WeatherChangeEvent(final World world, final boolean to) { + super(world); + this.to = to; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + /** + * Gets the state of weather that the world is being set to + * + * @return true if the weather is being set to raining, false otherwise + */ + public boolean toWeatherState() { + return to; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/weather/WeatherEvent.java b/src/main/java/org/bukkit/event/weather/WeatherEvent.java new file mode 100644 index 0000000..0cae9bc --- /dev/null +++ b/src/main/java/org/bukkit/event/weather/WeatherEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.weather; + +import org.bukkit.World; +import org.bukkit.event.Event; + +/** + * Represents a Weather-related event + */ +public abstract class WeatherEvent extends Event { + protected World world; + + public WeatherEvent(final World where) { + world = where; + } + + /** + * Returns the World where this event is occurring + * + * @return World this event is occurring in + */ + public final World getWorld() { + return world; + } +} diff --git a/src/main/java/org/bukkit/event/world/ChunkEvent.java b/src/main/java/org/bukkit/event/world/ChunkEvent.java new file mode 100644 index 0000000..4710d40 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/ChunkEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.Chunk; + +/** + * Represents a Chunk related event + */ +public abstract class ChunkEvent extends WorldEvent { + protected Chunk chunk; + + protected ChunkEvent(final Chunk chunk) { + super(chunk.getWorld()); + this.chunk = chunk; + } + + /** + * Gets the chunk being loaded/unloaded + * + * @return Chunk that triggered this event + */ + public Chunk getChunk() { + return chunk; + } +} diff --git a/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java b/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java new file mode 100644 index 0000000..a45b1cd --- /dev/null +++ b/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java @@ -0,0 +1,37 @@ +package org.bukkit.event.world; + +import org.bukkit.Chunk; +import org.bukkit.event.HandlerList; + +/** + * Called when a chunk is loaded + */ +public class ChunkLoadEvent extends ChunkEvent { + private static final HandlerList handlers = new HandlerList(); + private final boolean newChunk; + + public ChunkLoadEvent(final Chunk chunk, final boolean newChunk) { + super(chunk); + this.newChunk = newChunk; + } + + /** + * Gets if this chunk was newly created or not. + *

          + * Note that if this chunk is new, it will not be populated at this time. + * + * @return true if the chunk is new, otherwise false + */ + public boolean isNewChunk() { + return newChunk; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java b/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java new file mode 100644 index 0000000..705d955 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.world; + +import org.bukkit.Chunk; +import org.bukkit.event.HandlerList; +import org.bukkit.generator.BlockPopulator; + +/** + * Thrown when a new chunk has finished being populated. + *

          + * If your intent is to populate the chunk using this event, please see {@link + * BlockPopulator} + */ +public class ChunkPopulateEvent extends ChunkEvent { + private static final HandlerList handlers = new HandlerList(); + + public ChunkPopulateEvent(final Chunk chunk) { + super(chunk); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java b/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java new file mode 100644 index 0000000..f59d091 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.world; + +import org.bukkit.Chunk; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a chunk is unloaded + */ +public class ChunkUnloadEvent extends ChunkEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + + public ChunkUnloadEvent(final Chunk chunk) { + super(chunk); + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/world/PortalCreateEvent.java b/src/main/java/org/bukkit/event/world/PortalCreateEvent.java new file mode 100644 index 0000000..d83d7a9 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/PortalCreateEvent.java @@ -0,0 +1,77 @@ +package org.bukkit.event.world; + +import org.bukkit.block.Block; +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * Called when a portal is created + */ +public class PortalCreateEvent extends WorldEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private final ArrayList blocks = new ArrayList(); + private CreateReason reason = CreateReason.FIRE; + + public PortalCreateEvent(final Collection blocks, final World world, CreateReason reason) { + super(world); + + this.blocks.addAll(blocks); + this.reason = reason; + } + + /** + * Gets an array list of all the blocks associated with the created portal + * + * @return array list of all the blocks associated with the created portal + */ + public ArrayList getBlocks() { + return this.blocks; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the reason for the portal's creation + * + * @return CreateReason for the portal's creation + */ + public CreateReason getReason() { + return reason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the various reasons for a portal's creation + */ + public enum CreateReason { + /** + * When a portal is created 'traditionally' due to a portal frame + * being set on fire. + */ + FIRE, + /** + * When a portal is created as a destination for an existing portal + * when using the custom PortalTravelAgent + */ + OBC_DESTINATION + } +} diff --git a/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java b/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java new file mode 100644 index 0000000..e99c3c0 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java @@ -0,0 +1,37 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.Location; +import org.bukkit.event.HandlerList; + +/** + * An event that is called when a world's spawn changes. The world's previous + * spawn location is included. + */ +public class SpawnChangeEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + private final Location previousLocation; + + public SpawnChangeEvent(final World world, final Location previousLocation) { + super(world); + this.previousLocation = previousLocation; + } + + /** + * Gets the previous spawn location + * + * @return Location that used to be spawn + */ + public Location getPreviousLocation() { + return previousLocation; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/world/StructureGrowEvent.java b/src/main/java/org/bukkit/event/world/StructureGrowEvent.java new file mode 100644 index 0000000..d1c9822 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/StructureGrowEvent.java @@ -0,0 +1,96 @@ +package org.bukkit.event.world; + +import java.util.List; +import org.bukkit.Location; +import org.bukkit.TreeType; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Event that is called when an organic structure attempts to grow (Sapling -> + * Tree), (Mushroom -> Huge Mushroom), naturally or using bonemeal. + */ +public class StructureGrowEvent extends WorldEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled = false; + private final Location location; + private final TreeType species; + private final boolean bonemeal; + private final Player player; + private final List blocks; + + public StructureGrowEvent(final Location location, final TreeType species, final boolean bonemeal, final Player player, final List blocks) { + super(location.getWorld()); + this.location = location; + this.species = species; + this.bonemeal = bonemeal; + this.player = player; + this.blocks = blocks; + } + + /** + * Gets the location of the structure. + * + * @return Location of the structure + */ + public Location getLocation() { + return location; + } + + /** + * Gets the species type (birch, normal, pine, red mushroom, brown + * mushroom) + * + * @return Structure species + */ + public TreeType getSpecies() { + return species; + } + + /** + * Checks if structure was grown using bonemeal. + * + * @return True if the structure was grown using bonemeal. + */ + public boolean isFromBonemeal() { + return bonemeal; + } + + /** + * Gets the player that created the structure. + * + * @return Player that created the structure, null if was not created + * manually + */ + public Player getPlayer() { + return player; + } + + /** + * Gets an ArrayList of all blocks associated with the structure. + * + * @return ArrayList of all blocks associated with the structure. + */ + public List getBlocks() { + return blocks; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/world/WorldEvent.java b/src/main/java/org/bukkit/event/world/WorldEvent.java new file mode 100644 index 0000000..bd89b81 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/WorldEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.Event; + +/** + * Represents events within a world + */ +public abstract class WorldEvent extends Event { + private final World world; + + public WorldEvent(final World world) { + this.world = world; + } + + /** + * Gets the world primarily involved with this event + * + * @return World which caused this event + */ + public World getWorld() { + return world; + } +} diff --git a/src/main/java/org/bukkit/event/world/WorldInitEvent.java b/src/main/java/org/bukkit/event/world/WorldInitEvent.java new file mode 100644 index 0000000..6bf13e0 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/WorldInitEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.HandlerList; + +/** + * Called when a World is initializing + */ +public class WorldInitEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + + public WorldInitEvent(final World world) { + super(world); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/world/WorldLoadEvent.java b/src/main/java/org/bukkit/event/world/WorldLoadEvent.java new file mode 100644 index 0000000..c5545aa --- /dev/null +++ b/src/main/java/org/bukkit/event/world/WorldLoadEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.HandlerList; + +/** + * Called when a World is loaded + */ +public class WorldLoadEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + + public WorldLoadEvent(final World world) { + super(world); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/world/WorldSaveEvent.java b/src/main/java/org/bukkit/event/world/WorldSaveEvent.java new file mode 100644 index 0000000..d46b413 --- /dev/null +++ b/src/main/java/org/bukkit/event/world/WorldSaveEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.HandlerList; + +/** + * Called when a World is saved. + */ +public class WorldSaveEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + + public WorldSaveEvent(final World world) { + super(world); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java b/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java new file mode 100644 index 0000000..110544b --- /dev/null +++ b/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a World is unloaded + */ +public class WorldUnloadEvent extends WorldEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean isCancelled; + + public WorldUnloadEvent(final World world) { + super(world); + } + + public boolean isCancelled() { + return this.isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/main/java/org/bukkit/generator/BlockPopulator.java b/src/main/java/org/bukkit/generator/BlockPopulator.java new file mode 100644 index 0000000..6a70bdb --- /dev/null +++ b/src/main/java/org/bukkit/generator/BlockPopulator.java @@ -0,0 +1,29 @@ +package org.bukkit.generator; + +import java.util.Random; +import org.bukkit.Chunk; +import org.bukkit.World; + +/** + * A block populator is responsible for generating a small area of blocks. + *

          + * For example, generating glowstone inside the nether or generating dungeons + * full of treasure + */ +public abstract class BlockPopulator { + + /** + * Populates an area of blocks at or around the given chunk. + *

          + * The chunks on each side of the specified chunk must already exist; that + * is, there must be one north, east, south and west of the specified + * chunk. The "corner" chunks may not exist, in which scenario the + * populator should record any changes required for those chunks and + * perform the changes when they are ready. + * + * @param world The world to generate in + * @param random The random generator to use + * @param source The chunk to generate for + */ + public abstract void populate(World world, Random random, Chunk source); +} diff --git a/src/main/java/org/bukkit/generator/ChunkGenerator.java b/src/main/java/org/bukkit/generator/ChunkGenerator.java new file mode 100644 index 0000000..8e08bdc --- /dev/null +++ b/src/main/java/org/bukkit/generator/ChunkGenerator.java @@ -0,0 +1,268 @@ +package org.bukkit.generator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; + +/** + * A chunk generator is responsible for the initial shaping of an entire + * chunk. For example, the nether chunk generator should shape netherrack and + * soulsand + */ +public abstract class ChunkGenerator { + + /** + * Interface to biome data for chunk to be generated: initialized with + * default values for world type and seed. + *

          + * Custom generator is free to access and tailor values during + * generateBlockSections() or generateExtBlockSections(). + */ + public interface BiomeGrid { + + /** + * Get biome at x, z within chunk being generated + * + * @param x - 0-15 + * @param z - 0-15 + * @return Biome value + */ + Biome getBiome(int x, int z); + + /** + * Set biome at x, z within chunk being generated + * + * @param x - 0-15 + * @param z - 0-15 + * @param bio - Biome value + */ + void setBiome(int x, int z, Biome bio); + } + @Deprecated + /** + * Shapes the chunk for the given coordinates. + *

          + * This method should return a byte[32768] in the following format: + *

          +     * for (int x = 0; x < 16; x++) {
          +     *     for (int z = 0; z < 16; z++) {
          +     *         for (int y = 0; y < 128; y++) {
          +     *             // result[(x * 16 + z) * 128 + y] = ??;
          +     *         }
          +     *     }
          +     * }
          +     * 
          + *

          + * Note that this method should never attempt to get the Chunk at + * the passed coordinates, as doing so may cause an infinite loop + *

          + * Note this deprecated method will only be called when both + * generateExtBlockSections() and generateBlockSections() are + * unimplemented and return null. + * + * @param world The world this chunk will be used for + * @param random The random generator to use + * @param x The X-coordinate of the chunk + * @param z The Z-coordinate of the chunk + * @return byte[] containing the types for each block created by this + * generator + */ + public byte[] generate(World world, Random random, int x, int z) { + throw new UnsupportedOperationException("Custom generator is missing required methods: generate(), generateBlockSections() and generateExtBlockSections()"); + } + + /** + * Shapes the chunk for the given coordinates, with extended block IDs + * supported (0-4095). + *

          + * As of 1.2, chunks are represented by a vertical array of chunk + * sections, each of which is 16 x 16 x 16 blocks. If a section is empty + * (all zero), the section does not need to be supplied, reducing memory + * usage. + *

          + * This method must return a short[][] array in the following format: + *

          +     *     short[][] result = new short[world-height / 16][];
          +     * 
          + * Each section (sectionID = (Y>>4)) that has blocks needs to be allocated + * space for the 4096 blocks in that section: + *
          +     *     result[sectionID] = new short[4096];
          +     * 
          + * while sections that are not populated can be left null. + *

          + * Setting a block at X, Y, Z within the chunk can be done with the + * following mapping function: + *

          +     *    void setBlock(short[][] result, int x, int y, int z, short blkid) {
          +     *        if (result[y >> 4] == null) {
          +     *            result[y >> 4] = new short[4096];
          +     *        }
          +     *        result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid;
          +     *    }
          +     * 
          + * while reading a block ID can be done with the following mapping + * function: + *
          +     *    short getBlock(short[][] result, int x, int y, int z) {
          +     *        if (result[y >> 4] == null) {
          +     *            return (short)0;
          +     *        }
          +     *        return result[y >> 4][((y & 0xF) << 8) | (z << 4) | x];
          +     *    }
          +     * 
          + * while sections that are not populated can be left null. + *

          + * Setting a block at X, Y, Z within the chunk can be done with the + * following mapping function: + *

          +     *    void setBlock(short[][] result, int x, int y, int z, short blkid) {
          +     *        if (result[y >> 4) == null) {
          +     *            result[y >> 4] = new short[4096];
          +     *        }
          +     *        result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid;
          +     *    }
          +     * 
          + * while reading a block ID can be done with the following mapping + * function: + *
          +     *    short getBlock(short[][] result, int x, int y, int z) {
          +     *        if (result[y >> 4) == null) {
          +     *            return (short)0;
          +     *        }
          +     *        return result[y >> 4][((y & 0xF) << 8) | (z << 4) | x];
          +     *    }
          +     * 
          + *

          + * Note that this method should never attempt to get the Chunk at + * the passed coordinates, as doing so may cause an infinite loop + *

          + * Note generators that do not return block IDs above 255 should not + * implement this method, or should have it return null (which will result + * in the generateBlockSections() method being called). + * + * @param world The world this chunk will be used for + * @param random The random generator to use + * @param x The X-coordinate of the chunk + * @param z The Z-coordinate of the chunk + * @param biomes Proposed biome values for chunk - can be updated by + * generator + * @return short[][] containing the types for each block created by this + * generator + * @deprecated Magic value + */ + @Deprecated + public short[][] generateExtBlockSections(World world, Random random, int x, int z, BiomeGrid biomes) { + return null; // Default - returns null, which drives call to generateBlockSections() + } + + /** + * Shapes the chunk for the given coordinates. + *

          + * As of 1.2, chunks are represented by a vertical array of chunk + * sections, each of which is 16 x 16 x 16 blocks. If a section is empty + * (all zero), the section does not need to be supplied, reducing memory + * usage. + *

          + * This method must return a byte[][] array in the following format: + *

          +     *     byte[][] result = new byte[world-height / 16][];
          +     * 
          + * Each section (sectionID = (Y>>4)) that has blocks needs to be allocated + * space for the 4096 blocks in that section: + *
          +     *     result[sectionID] = new byte[4096];
          +     * 
          + * while sections that are not populated can be left null. + *

          + * Setting a block at X, Y, Z within the chunk can be done with the + * following mapping function: + *

          +     *    void setBlock(byte[][] result, int x, int y, int z, byte blkid) {
          +     *        if (result[y >> 4) == null) {
          +     *            result[y >> 4] = new byte[4096];
          +     *        }
          +     *        result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid;
          +     *    }
          +     * 
          + * while reading a block ID can be done with the following mapping + * function: + *
          +     *    byte getBlock(byte[][] result, int x, int y, int z) {
          +     *        if (result[y >> 4) == null) {
          +     *            return (byte)0;
          +     *        }
          +     *        return result[y >> 4][((y & 0xF) << 8) | (z << 4) | x];
          +     *    }
          +     * 
          + * + * Note that this method should never attempt to get the Chunk at + * the passed coordinates, as doing so may cause an infinite loop + * + * @param world The world this chunk will be used for + * @param random The random generator to use + * @param x The X-coordinate of the chunk + * @param z The Z-coordinate of the chunk + * @param biomes Proposed biome values for chunk - can be updated by + * generator + * @return short[][] containing the types for each block created by this + * generator + * @deprecated Magic value + */ + @Deprecated + public byte[][] generateBlockSections(World world, Random random, int x, int z, BiomeGrid biomes) { + return null; // Default - returns null, which drives call to generate() + } + + /** + * Tests if the specified location is valid for a natural spawn position + * + * @param world The world we're testing on + * @param x X-coordinate of the block to test + * @param z Z-coordinate of the block to test + * @return true if the location is valid, otherwise false + */ + public boolean canSpawn(World world, int x, int z) { + Block highest = world.getBlockAt(x, world.getHighestBlockYAt(x, z), z); + + switch (world.getEnvironment()) { + case NETHER: + return true; + case THE_END: + return highest.getType() != Material.AIR && highest.getType() != Material.WATER && highest.getType() != Material.LAVA; + case NORMAL: + default: + return highest.getType() == Material.SAND || highest.getType() == Material.GRAVEL; + } + } + + /** + * Gets a list of default {@link BlockPopulator}s to apply to a given + * world + * + * @param world World to apply to + * @return List containing any amount of BlockPopulators + */ + public List getDefaultPopulators(World world) { + return new ArrayList(); + } + + /** + * Gets a fixed spawn location to use for a given world. + *

          + * A null value is returned if a world should not use a fixed spawn point, + * and will instead attempt to find one randomly. + * + * @param world The world to locate a spawn point for + * @param random Random generator to use in the calculation + * @return Location containing a new spawn point, otherwise null + */ + public Location getFixedSpawnLocation(World world, Random random) { + return null; + } +} diff --git a/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java b/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java new file mode 100644 index 0000000..3e85e77 --- /dev/null +++ b/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java @@ -0,0 +1,80 @@ +package org.bukkit.help; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.apache.commons.lang.StringUtils; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.command.defaults.VanillaCommand; +import org.bukkit.help.HelpTopic; + +/** + * Lacking an alternative, the help system will create instances of + * GenericCommandHelpTopic for each command in the server's CommandMap. You + * can use this class as a base class for custom help topics, or as an example + * for how to write your own. + */ +public class GenericCommandHelpTopic extends HelpTopic { + + protected Command command; + + public GenericCommandHelpTopic(Command command) { + this.command = command; + + if (command.getLabel().startsWith("/")) { + name = command.getLabel(); + } else { + name = "/" + command.getLabel(); + } + + // The short text is the first line of the description + int i = command.getDescription().indexOf("\n"); + if (i > 1) { + shortText = command.getDescription().substring(0, i - 1); + } else { + shortText = command.getDescription(); + } + + // Build full text + StringBuffer sb = new StringBuffer(); + + sb.append(ChatColor.GOLD); + sb.append("Description: "); + sb.append(ChatColor.WHITE); + sb.append(command.getDescription()); + + sb.append("\n"); + + sb.append(ChatColor.GOLD); + sb.append("Usage: "); + sb.append(ChatColor.WHITE); + sb.append(command.getUsage().replace("", name.substring(1))); + + if (command.getAliases().size() > 0) { + sb.append("\n"); + sb.append(ChatColor.GOLD); + sb.append("Aliases: "); + sb.append(ChatColor.WHITE); + sb.append(ChatColor.WHITE + StringUtils.join(command.getAliases(), ", ")); + } + fullText = sb.toString(); + } + + public boolean canSee(CommandSender sender) { + if (!command.isRegistered() && !(command instanceof VanillaCommand)) { + // Unregistered commands should not show up in the help (ignore VanillaCommands) + return false; + } + + if (sender instanceof ConsoleCommandSender) { + return true; + } + + if (amendedPermission != null) { + return sender.hasPermission(amendedPermission); + } else { + return command.testPermissionSilent(sender); + } + } +} diff --git a/src/main/java/org/bukkit/help/HelpMap.java b/src/main/java/org/bukkit/help/HelpMap.java new file mode 100644 index 0000000..9c1b51b --- /dev/null +++ b/src/main/java/org/bukkit/help/HelpMap.java @@ -0,0 +1,79 @@ +package org.bukkit.help; + +import java.util.Collection; +import java.util.List; + +/** + * The HelpMap tracks all help topics registered in a Bukkit server. When the + * server starts up or is reloaded, help is processed and topics are added in + * the following order: + *

          + *

            + *
          1. General topics are loaded from the help.yml + *
          2. Plugins load and optionally call {@code addTopic()} + *
          3. Registered plugin commands are processed by {@link HelpTopicFactory} + * objects to create topics + *
          4. Topic contents are amended as directed in help.yml + *
          + */ +public interface HelpMap { + /** + * Returns a help topic for a given topic name. + * + * @param topicName The help topic name to look up. + * @return A {@link HelpTopic} object matching the topic name or null if + * none can be found. + */ + public HelpTopic getHelpTopic(String topicName); + + /** + * Returns a collection of all the registered help topics. + * + * @return All the registered help topics. + */ + public Collection getHelpTopics(); + + /** + * Adds a topic to the server's help index. + * + * @param topic The new help topic to add. + */ + public void addTopic(HelpTopic topic); + + /** + * Clears out the contents of the help index. Normally called during + * server reload. + */ + public void clear(); + + /** + * Associates a {@link HelpTopicFactory} object with given command base + * class. Plugins typically call this method during {@code onLoad()}. Once + * registered, the custom HelpTopicFactory will be used to create a custom + * {@link HelpTopic} for all commands deriving from the {@code + * commandClass} base class, or all commands deriving from {@link + * org.bukkit.command.PluginCommand} who's executor derives from {@code + * commandClass} base class. + * + * @param commandClass The class for which the custom HelpTopicFactory + * applies. Must derive from either {@link org.bukkit.command.Command} + * or {@link org.bukkit.command.CommandExecutor}. + * @param factory The {@link HelpTopicFactory} implementation to associate + * with the {@code commandClass}. + * @throws IllegalArgumentException Thrown if {@code commandClass} does + * not derive from a legal base class. + */ + public void registerHelpTopicFactory(Class commandClass, HelpTopicFactory factory); + + /** + * Gets the list of plugins the server administrator has chosen to exclude + * from the help index. Plugin authors who choose to directly extend + * {@link org.bukkit.command.Command} instead of {@link + * org.bukkit.command.PluginCommand} will need to check this collection in + * their {@link HelpTopicFactory} implementations to ensure they meet the + * server administrator's expectations. + * + * @return A list of plugins that should be excluded from the help index. + */ + public List getIgnoredPlugins(); +} diff --git a/src/main/java/org/bukkit/help/HelpTopic.java b/src/main/java/org/bukkit/help/HelpTopic.java new file mode 100644 index 0000000..a2ba5f5 --- /dev/null +++ b/src/main/java/org/bukkit/help/HelpTopic.java @@ -0,0 +1,121 @@ +package org.bukkit.help; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +/** + * HelpTopic implementations are displayed to the user when the user uses the + * /help command. + *

          + * Custom implementations of this class can work at two levels. A simple + * implementation only needs to set the value of {@code name}, {@code + * shortText}, and {@code fullText} in the constructor. This base class will + * take care of the rest. + *

          + * Complex implementations can be created by overriding the behavior of all + * the methods in this class. + */ +public abstract class HelpTopic { + protected String name; + protected String shortText; + protected String fullText; + protected String amendedPermission; + + /** + * Determines if a {@link Player} is allowed to see this help topic. + *

          + * HelpTopic implementations should take server administrator wishes into + * account as set by the {@link HelpTopic#amendCanSee(String)} function. + * + * @param player The Player in question. + * @return True of the Player can see this help topic, false otherwise. + */ + public abstract boolean canSee(CommandSender player); + + /** + * Allows the server administrator to override the permission required to + * see a help topic. + *

          + * HelpTopic implementations should take this into account when + * determining topic visibility on the {@link + * HelpTopic#canSee(org.bukkit.command.CommandSender)} function. + * + * @param amendedPermission The permission node the server administrator + * wishes to apply to this topic. + */ + public void amendCanSee(String amendedPermission) { + this.amendedPermission = amendedPermission; + } + + /** + * Returns the name of this help topic. + * + * @return The topic name. + */ + public String getName() { + return name; + } + + /** + * Returns a brief description that will be displayed in the topic index. + * + * @return A brief topic description. + */ + public String getShortText() { + return shortText; + } + + /** + * Returns the full description of this help topic that is displayed when + * the user requests this topic's details. + *

          + * The result will be paginated to properly fit the user's client. + * + * @param forWho The player or console requesting the full text. Useful + * for further security trimming the command's full text based on + * sub-permissions in custom implementations. + * + * @return A full topic description. + */ + public String getFullText(CommandSender forWho) { + return fullText; + } + + /** + * Allows the server admin (or another plugin) to add or replace the + * contents of a help topic. + *

          + * A null in either parameter will leave that part of the topic unchanged. + * In either amending parameter, the string {@literal } is replaced + * with the existing contents in the help topic. Use this to append or + * prepend additional content into an automatically generated help topic. + * + * @param amendedShortText The new topic short text to use, or null to + * leave alone. + * @param amendedFullText The new topic full text to use, or null to leave + * alone. + */ + public void amendTopic(String amendedShortText, String amendedFullText) { + shortText = applyAmendment(shortText, amendedShortText); + fullText = applyAmendment(fullText, amendedFullText); + } + + /** + * Developers implementing their own custom HelpTopic implementations can + * use this utility method to ensure their implementations comply with the + * expected behavior of the {@link HelpTopic#amendTopic(String, String)} + * method. + * + * @param baseText The existing text of the help topic. + * @param amendment The amending text from the amendTopic() method. + * @return The application of the amending text to the existing text, + * according to the expected rules of amendTopic(). + */ + protected String applyAmendment(String baseText, String amendment) { + if (amendment == null) { + return baseText; + } else { + return amendment.replaceAll("", baseText); + } + } +} diff --git a/src/main/java/org/bukkit/help/HelpTopicComparator.java b/src/main/java/org/bukkit/help/HelpTopicComparator.java new file mode 100644 index 0000000..3e43eb3 --- /dev/null +++ b/src/main/java/org/bukkit/help/HelpTopicComparator.java @@ -0,0 +1,48 @@ +package org.bukkit.help; + +import org.bukkit.help.HelpTopic; + +import java.util.Comparator; + +/** + * Used to impose a custom total ordering on help topics. + *

          + * All topics are listed in alphabetic order, but topics that start with a + * slash come after topics that don't. + */ +public class HelpTopicComparator implements Comparator { + + // Singleton implementations + private static final TopicNameComparator tnc = new TopicNameComparator(); + public static TopicNameComparator topicNameComparatorInstance() { + return tnc; + } + + private static final HelpTopicComparator htc = new HelpTopicComparator(); + public static HelpTopicComparator helpTopicComparatorInstance() { + return htc; + } + + private HelpTopicComparator() {} + + public int compare(HelpTopic lhs, HelpTopic rhs) { + return tnc.compare(lhs.getName(), rhs.getName()); + } + + public static class TopicNameComparator implements Comparator { + private TopicNameComparator(){} + + public int compare(String lhs, String rhs) { + boolean lhsStartSlash = lhs.startsWith("/"); + boolean rhsStartSlash = rhs.startsWith("/"); + + if (lhsStartSlash && !rhsStartSlash) { + return 1; + } else if (!lhsStartSlash && rhsStartSlash) { + return -1; + } else { + return lhs.compareToIgnoreCase(rhs); + } + } + } +} diff --git a/src/main/java/org/bukkit/help/HelpTopicFactory.java b/src/main/java/org/bukkit/help/HelpTopicFactory.java new file mode 100644 index 0000000..87d3697 --- /dev/null +++ b/src/main/java/org/bukkit/help/HelpTopicFactory.java @@ -0,0 +1,42 @@ +package org.bukkit.help; + +import org.bukkit.command.Command; + +/** + * A HelpTopicFactory is used to create custom {@link HelpTopic} objects from + * commands that inherit from a common base class or have executors that + * inherit from a common base class. You can use a custom HelpTopic to change + * the way all the commands in your plugin display in the help. If your plugin + * implements a complex permissions system, a custom help topic may also be + * appropriate. + *

          + * To automatically bind your plugin's commands to your custom HelpTopic + * implementation, first make sure all your commands or executors derive from + * a custom base class (it doesn't have to do anything). Next implement a + * custom HelpTopicFactory that accepts your custom command base class and + * instantiates an instance of your custom HelpTopic from it. Finally, + * register your HelpTopicFactory against your command base class using the + * {@link HelpMap#registerHelpTopicFactory(Class, HelpTopicFactory)} method. + *

          + * As the help system iterates over all registered commands to make help + * topics, it first checks to see if there is a HelpTopicFactory registered + * for the command's base class. If so, the factory is used to make a help + * topic rather than a generic help topic. If no factory is found for the + * command's base class and the command derives from {@link + * org.bukkit.command.PluginCommand}, then the type of the command's executor + * is inspected looking for a registered HelpTopicFactory. Finally, if no + * factory is found, a generic help topic is created for the command. + * + * @param The base class for your custom commands. + */ +public interface HelpTopicFactory { + /** + * This method accepts a command deriving from a custom command base class + * and constructs a custom HelpTopic for it. + * + * @param command The custom command to build a help topic for. + * @return A new custom help topic or {@code null} to intentionally NOT + * create a topic. + */ + public HelpTopic createTopic(TCommand command); +} diff --git a/src/main/java/org/bukkit/help/IndexHelpTopic.java b/src/main/java/org/bukkit/help/IndexHelpTopic.java new file mode 100644 index 0000000..c474031 --- /dev/null +++ b/src/main/java/org/bukkit/help/IndexHelpTopic.java @@ -0,0 +1,112 @@ +package org.bukkit.help; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.ChatPaginator; + +import java.util.Collection; + +/** + * This help topic generates a list of other help topics. This class is useful + * for adding your own index help topics. To enforce a particular order, use a + * sorted collection. + *

          + * If a preamble is provided to the constructor, that text will be displayed + * before the first item in the index. + */ +public class IndexHelpTopic extends HelpTopic { + + protected String permission; + protected String preamble; + protected Collection allTopics; + + public IndexHelpTopic(String name, String shortText, String permission, Collection topics) { + this(name, shortText, permission, topics, null); + } + + public IndexHelpTopic(String name, String shortText, String permission, Collection topics, String preamble) { + this.name = name; + this.shortText = shortText; + this.permission = permission; + this.preamble = preamble; + setTopicsCollection(topics); + } + + /** + * Sets the contents of the internal allTopics collection. + * + * @param topics The topics to set. + */ + protected void setTopicsCollection(Collection topics) { + this.allTopics = topics; + } + + public boolean canSee(CommandSender sender) { + if (sender instanceof ConsoleCommandSender) { + return true; + } + if (permission == null) { + return true; + } + return sender.hasPermission(permission); + } + + @Override + public void amendCanSee(String amendedPermission) { + permission = amendedPermission; + } + + public String getFullText(CommandSender sender) { + StringBuilder sb = new StringBuilder(); + + if (preamble != null) { + sb.append(buildPreamble(sender)); + sb.append("\n"); + } + + for (HelpTopic topic : allTopics) { + if (topic.canSee(sender)) { + String lineStr = buildIndexLine(sender, topic).replace("\n", ". "); + if (sender instanceof Player && lineStr.length() > ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH) { + sb.append(lineStr.substring(0, ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH - 3)); + sb.append("..."); + } else { + sb.append(lineStr); + } + sb.append("\n"); + } + } + return sb.toString(); + } + + /** + * Builds the topic preamble. Override this method to change how the index + * preamble looks. + * + * @param sender The command sender requesting the preamble. + * @return The topic preamble. + */ + protected String buildPreamble(CommandSender sender) { + return ChatColor.GRAY + preamble; + } + + /** + * Builds individual lines in the index topic. Override this method to + * change how index lines are rendered. + * + * @param sender The command sender requesting the index line. + * @param topic The topic to render into an index line. + * @return The rendered index line. + */ + protected String buildIndexLine(CommandSender sender, HelpTopic topic) { + StringBuilder line = new StringBuilder(); + line.append(ChatColor.GOLD); + line.append(topic.getName()); + line.append(": "); + line.append(ChatColor.WHITE); + line.append(topic.getShortText()); + return line.toString(); + } +} diff --git a/src/main/java/org/bukkit/inventory/AnvilInventory.java b/src/main/java/org/bukkit/inventory/AnvilInventory.java new file mode 100644 index 0000000..70fae71 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/AnvilInventory.java @@ -0,0 +1,7 @@ +package org.bukkit.inventory; + +/** + * Interface to the inventory of an Anvil. + */ +public interface AnvilInventory extends Inventory { +} diff --git a/src/main/java/org/bukkit/inventory/BeaconInventory.java b/src/main/java/org/bukkit/inventory/BeaconInventory.java new file mode 100644 index 0000000..2f8769e --- /dev/null +++ b/src/main/java/org/bukkit/inventory/BeaconInventory.java @@ -0,0 +1,21 @@ +package org.bukkit.inventory; + +/** + * Interface to the inventory of a Beacon. + */ +public interface BeaconInventory extends Inventory { + + /** + * Set the item powering the beacon. + * + * @param item The new item + */ + void setItem(ItemStack item); + + /** + * Get the item powering the beacon. + * + * @return The current item. + */ + ItemStack getItem(); +} diff --git a/src/main/java/org/bukkit/inventory/BrewerInventory.java b/src/main/java/org/bukkit/inventory/BrewerInventory.java new file mode 100644 index 0000000..9cc31c9 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/BrewerInventory.java @@ -0,0 +1,25 @@ +package org.bukkit.inventory; + +import org.bukkit.block.BrewingStand; + +/** + * Interface to the inventory of a Brewing Stand. + */ +public interface BrewerInventory extends Inventory { + + /** + * Get the current ingredient for brewing. + * + * @return The ingredient. + */ + ItemStack getIngredient(); + + /** + * Set the current ingredient for brewing. + * + * @param ingredient The ingredient + */ + void setIngredient(ItemStack ingredient); + + BrewingStand getHolder(); +} diff --git a/src/main/java/org/bukkit/inventory/CraftingInventory.java b/src/main/java/org/bukkit/inventory/CraftingInventory.java new file mode 100644 index 0000000..f71533c --- /dev/null +++ b/src/main/java/org/bukkit/inventory/CraftingInventory.java @@ -0,0 +1,45 @@ +package org.bukkit.inventory; + +/** + * Interface to the crafting inventories + */ +public interface CraftingInventory extends Inventory { + + /** + * Check what item is in the result slot of this crafting inventory. + * + * @return The result item. + */ + ItemStack getResult(); + + /** + * Get the contents of the crafting matrix. + * + * @return The contents. + */ + ItemStack[] getMatrix(); + + /** + * Set the item in the result slot of the crafting inventory. + * + * @param newResult The new result item. + */ + void setResult(ItemStack newResult); + + /** + * Replace the contents of the crafting matrix + * + * @param contents The new contents. + * @throws IllegalArgumentException if the length of contents is greater + * than the size of the crafting matrix. + */ + void setMatrix(ItemStack[] contents); + + /** + * Get the current recipe formed on the crafting inventory, if any. + * + * @return The recipe, or null if the current contents don't match any + * recipe. + */ + Recipe getRecipe(); +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/inventory/DoubleChestInventory.java b/src/main/java/org/bukkit/inventory/DoubleChestInventory.java new file mode 100644 index 0000000..c03ad53 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/DoubleChestInventory.java @@ -0,0 +1,25 @@ +package org.bukkit.inventory; + +import org.bukkit.block.DoubleChest; + +/** + * Interface to the inventory of a Double Chest. + */ +public interface DoubleChestInventory extends Inventory { + + /** + * Get the left half of this double chest. + * + * @return The left side inventory + */ + Inventory getLeftSide(); + + /** + * Get the right side of this double chest. + * + * @return The right side inventory + */ + Inventory getRightSide(); + + DoubleChest getHolder(); +} diff --git a/src/main/java/org/bukkit/inventory/EnchantingInventory.java b/src/main/java/org/bukkit/inventory/EnchantingInventory.java new file mode 100644 index 0000000..74a863e --- /dev/null +++ b/src/main/java/org/bukkit/inventory/EnchantingInventory.java @@ -0,0 +1,21 @@ +package org.bukkit.inventory; + +/** + * Interface to the inventory of an Enchantment Table. + */ +public interface EnchantingInventory extends Inventory { + + /** + * Set the item being enchanted. + * + * @param item The new item + */ + void setItem(ItemStack item); + + /** + * Get the item being enchanted. + * + * @return The current item. + */ + ItemStack getItem(); +} diff --git a/src/main/java/org/bukkit/inventory/EntityEquipment.java b/src/main/java/org/bukkit/inventory/EntityEquipment.java new file mode 100644 index 0000000..9e71235 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/EntityEquipment.java @@ -0,0 +1,236 @@ +package org.bukkit.inventory; + +import org.bukkit.entity.Entity; + +/** + * An interface to a creatures inventory + */ +public interface EntityEquipment { + + /** + * Gets a copy of the item the entity is currently holding + * + * @return the currently held item + */ + ItemStack getItemInHand(); + + /** + * Sets the item the entity is holding + * + * @param stack The item to put into the entities hand + */ + void setItemInHand(ItemStack stack); + + /** + * Gets a copy of the helmet currently being worn by the entity + * + * @return The helmet being worn + */ + ItemStack getHelmet(); + + /** + * Sets the helmet worn by the entity + * + * @param helmet The helmet to put on the entity + */ + void setHelmet(ItemStack helmet); + + /** + * Gets a copy of the chest plate currently being worn by the entity + * + * @return The chest plate being worn + */ + ItemStack getChestplate(); + + /** + * Sets the chest plate worn by the entity + * + * @param chestplate The chest plate to put on the entity + */ + void setChestplate(ItemStack chestplate); + + /** + * Gets a copy of the leggings currently being worn by the entity + * + * @return The leggings being worn + */ + ItemStack getLeggings(); + + /** + * Sets the leggings worn by the entity + * + * @param leggings The leggings to put on the entity + */ + void setLeggings(ItemStack leggings); + + /** + * Gets a copy of the boots currently being worn by the entity + * + * @return The boots being worn + */ + ItemStack getBoots(); + + /** + * Sets the boots worn by the entity + * + * @param boots The boots to put on the entity + */ + void setBoots(ItemStack boots); + + /** + * Gets a copy of all worn armor + * + * @return The array of worn armor + */ + ItemStack[] getArmorContents(); + + /** + * Sets the entities armor to the provided array of ItemStacks + * + * @param items The items to set the armor as + */ + void setArmorContents(ItemStack[] items); + + /** + * Clears the entity of all armor and held items + */ + void clear(); + + /** + * Gets the chance of the currently held item being dropped upon this + * creature's death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @return chance of the currently held item being dropped (1 for players) + */ + float getItemInHandDropChance(); + + /** + * Sets the chance of the item this creature is currently holding being + * dropped upon this creature's death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @param chance the chance of the currently held item being dropped + * @throws UnsupportedOperationException when called on players + */ + void setItemInHandDropChance(float chance); + + /** + * Gets the chance of the helmet being dropped upon this creature's death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @return the chance of the helmet being dropped (1 for players) + */ + float getHelmetDropChance(); + + /** + * Sets the chance of the helmet being dropped upon this creature's death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @param chance of the helmet being dropped + * @throws UnsupportedOperationException when called on players + */ + void setHelmetDropChance(float chance); + + /** + * Gets the chance of the chest plate being dropped upon this creature's + * death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @return the chance of the chest plate being dropped (1 for players) + */ + float getChestplateDropChance(); + + /** + * Sets the chance of the chest plate being dropped upon this creature's + * death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @param chance of the chest plate being dropped + * @throws UnsupportedOperationException when called on players + */ + void setChestplateDropChance(float chance); + + /** + * Gets the chance of the leggings being dropped upon this creature's + * death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @return the chance of the leggings being dropped (1 for players) + */ + float getLeggingsDropChance(); + + /** + * Sets the chance of the leggings being dropped upon this creature's + * death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @param chance chance of the leggings being dropped + * @throws UnsupportedOperationException when called on players + */ + void setLeggingsDropChance(float chance); + + /** + * Gets the chance of the boots being dropped upon this creature's death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @return the chance of the boots being dropped (1 for players) + */ + float getBootsDropChance(); + + /** + * Sets the chance of the boots being dropped upon this creature's death + *

          + *

            + *
          • A drop chance of 0F will never drop + *
          • A drop chance of 1F will always drop + *
          + * + * @param chance of the boots being dropped + * @throws UnsupportedOperationException when called on players + */ + void setBootsDropChance(float chance); + + /** + * Get the entity this EntityEquipment belongs to + * + * @return the entity this EntityEquipment belongs to + */ + Entity getHolder(); +} diff --git a/src/main/java/org/bukkit/inventory/FurnaceInventory.java b/src/main/java/org/bukkit/inventory/FurnaceInventory.java new file mode 100644 index 0000000..93b41d3 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/FurnaceInventory.java @@ -0,0 +1,53 @@ +package org.bukkit.inventory; + +import org.bukkit.block.Furnace; + +/** + * Interface to the inventory of a Furnace. + */ +public interface FurnaceInventory extends Inventory { + + /** + * Get the current item in the result slot. + * + * @return The item + */ + ItemStack getResult(); + + /** + * Get the current fuel. + * + * @return The item + */ + ItemStack getFuel(); + + /** + * Get the item currently smelting. + * + * @return The item + */ + ItemStack getSmelting(); + + /** + * Set the current fuel. + * + * @param stack The item + */ + void setFuel(ItemStack stack); + + /** + * Set the current item in the result slot. + * + * @param stack The item + */ + void setResult(ItemStack stack); + + /** + * Set the item currently smelting. + * + * @param stack The item + */ + void setSmelting(ItemStack stack); + + Furnace getHolder(); +} diff --git a/src/main/java/org/bukkit/inventory/FurnaceRecipe.java b/src/main/java/org/bukkit/inventory/FurnaceRecipe.java new file mode 100644 index 0000000..8075323 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/FurnaceRecipe.java @@ -0,0 +1,100 @@ +package org.bukkit.inventory; + +import org.bukkit.Material; +import org.bukkit.material.MaterialData; + +/** + * Represents a smelting recipe. + */ +public class FurnaceRecipe implements Recipe { + private ItemStack output; + private ItemStack ingredient; + + /** + * Create a furnace recipe to craft the specified ItemStack. + * + * @param result The item you want the recipe to create. + * @param source The input material. + */ + public FurnaceRecipe(ItemStack result, Material source) { + this(result, source, 0); + } + + /** + * Create a furnace recipe to craft the specified ItemStack. + * + * @param result The item you want the recipe to create. + * @param source The input material. + */ + public FurnaceRecipe(ItemStack result, MaterialData source) { + this(result, source.getItemType(), source.getData()); + } + + /** + * Create a furnace recipe to craft the specified ItemStack. + * + * @param result The item you want the recipe to create. + * @param source The input material. + * @param data The data value. (Note: This is currently ignored by the + * CraftBukkit server.) + * @deprecated Magic value + */ + @Deprecated + public FurnaceRecipe(ItemStack result, Material source, int data) { + this.output = new ItemStack(result); + this.ingredient = new ItemStack(source, 1, (short) data); + } + + /** + * Sets the input of this furnace recipe. + * + * @param input The input material. + * @return The changed recipe, so you can chain calls. + */ + public FurnaceRecipe setInput(MaterialData input) { + return setInput(input.getItemType(), input.getData()); + } + + /** + * Sets the input of this furnace recipe. + * + * @param input The input material. + * @return The changed recipe, so you can chain calls. + */ + public FurnaceRecipe setInput(Material input) { + return setInput(input, 0); + } + + /** + * Sets the input of this furnace recipe. + * + * @param input The input material. + * @param data The data value. (Note: This is currently ignored by the + * CraftBukkit server.) + * @return The changed recipe, so you can chain calls. + * @deprecated Magic value + */ + @Deprecated + public FurnaceRecipe setInput(Material input, int data) { + this.ingredient = new ItemStack(input, 1, (short) data); + return this; + } + + /** + * Get the input material. + * + * @return The input material. + */ + public ItemStack getInput() { + return this.ingredient.clone(); + } + + /** + * Get the result of this recipe. + * + * @return The resulting stack. + */ + public ItemStack getResult() { + return output.clone(); + } +} diff --git a/src/main/java/org/bukkit/inventory/HorseInventory.java b/src/main/java/org/bukkit/inventory/HorseInventory.java new file mode 100644 index 0000000..a71efb8 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/HorseInventory.java @@ -0,0 +1,35 @@ +package org.bukkit.inventory; + +/** + * An interface to the inventory of a Horse. + */ +public interface HorseInventory extends Inventory { + + /** + * Gets the item in the horse's saddle slot. + * + * @return the saddle item + */ + ItemStack getSaddle(); + + /** + * Gets the item in the horse's armor slot. + * + * @return the armor item + */ + ItemStack getArmor(); + + /** + * Sets the item in the horse's saddle slot. + * + * @param stack the new item + */ + void setSaddle(ItemStack stack); + + /** + * Sets the item in the horse's armor slot. + * + * @param stack the new item + */ + void setArmor(ItemStack stack); +} diff --git a/src/main/java/org/bukkit/inventory/Inventory.java b/src/main/java/org/bukkit/inventory/Inventory.java new file mode 100644 index 0000000..da5d83e --- /dev/null +++ b/src/main/java/org/bukkit/inventory/Inventory.java @@ -0,0 +1,381 @@ +package org.bukkit.inventory; + +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; + +import org.bukkit.Material; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; + +/** + * Interface to the various inventories. Behavior relating to {@link + * Material#AIR} is unspecified. + */ +public interface Inventory extends Iterable { + + /** + * Returns the size of the inventory + * + * @return The size of the inventory + */ + public int getSize(); + + /** + * Returns the maximum stack size for an ItemStack in this inventory. + * + * @return The maximum size for an ItemStack in this inventory. + */ + public int getMaxStackSize(); + + /** + * This method allows you to change the maximum stack size for an + * inventory. + *

          + * Caveats: + *

            + *
          • Not all inventories respect this value. + *
          • Stacks larger than 127 may be clipped when the world is saved. + *
          • This value is not guaranteed to be preserved; be sure to set it + * before every time you want to set a slot over the max stack size. + *
          • Stacks larger than the default max size for this type of inventory + * may not display correctly in the client. + *
          + * + * @param size The new maximum stack size for items in this inventory. + */ + public void setMaxStackSize(int size); + + /** + * Returns the name of the inventory + * + * @return The String with the name of the inventory + */ + public String getName(); + + /** + * Returns the ItemStack found in the slot at the given index + * + * @param index The index of the Slot's ItemStack to return + * @return The ItemStack in the slot + */ + public ItemStack getItem(int index); + + /** + * Stores the ItemStack at the given index of the inventory. + * + * @param index The index where to put the ItemStack + * @param item The ItemStack to set + */ + public void setItem(int index, ItemStack item); + + /** + * Stores the given ItemStacks in the inventory. This will try to fill + * existing stacks and empty slots as well as it can. + *

          + * The returned HashMap contains what it couldn't store, where the key is + * the index of the parameter, and the value is the ItemStack at that + * index of the varargs parameter. If all items are stored, it will return + * an empty HashMap. + *

          + * If you pass in ItemStacks which exceed the maximum stack size for the + * Material, first they will be added to partial stacks where + * Material.getMaxStackSize() is not exceeded, up to + * Material.getMaxStackSize(). When there are no partial stacks left + * stacks will be split on Inventory.getMaxStackSize() allowing you to + * exceed the maximum stack size for that material. + * + * @param items The ItemStacks to add + * @return A HashMap containing items that didn't fit. + * @throws IllegalArgumentException if items or any element in it is null + */ + public HashMap addItem(ItemStack... items) throws IllegalArgumentException; + + /** + * Removes the given ItemStacks from the inventory. + *

          + * It will try to remove 'as much as possible' from the types and amounts + * you give as arguments. + *

          + * The returned HashMap contains what it couldn't remove, where the key is + * the index of the parameter, and the value is the ItemStack at that + * index of the varargs parameter. If all the given ItemStacks are + * removed, it will return an empty HashMap. + * + * @param items The ItemStacks to remove + * @return A HashMap containing items that couldn't be removed. + * @throws IllegalArgumentException if items is null + */ + public HashMap removeItem(ItemStack... items) throws IllegalArgumentException; + + /** + * Returns all ItemStacks from the inventory + * + * @return An array of ItemStacks from the inventory. + */ + public ItemStack[] getContents(); + + /** + * Completely replaces the inventory's contents. Removes all existing + * contents and replaces it with the ItemStacks given in the array. + * + * @param items A complete replacement for the contents; the length must + * be less than or equal to {@link #getSize()}. + * @throws IllegalArgumentException If the array has more items than the + * inventory. + */ + public void setContents(ItemStack[] items) throws IllegalArgumentException; + + /** + * Checks if the inventory contains any ItemStacks with the given + * materialId + * + * @param materialId The materialId to check for + * @return true if an ItemStack in this inventory contains the materialId + * @deprecated Magic value + */ + @Deprecated + public boolean contains(int materialId); + + /** + * Checks if the inventory contains any ItemStacks with the given + * material. + * + * @param material The material to check for + * @return true if an ItemStack is found with the given Material + * @throws IllegalArgumentException if material is null + */ + public boolean contains(Material material) throws IllegalArgumentException; + + /** + * Checks if the inventory contains any ItemStacks matching the given + * ItemStack. + *

          + * This will only return true if both the type and the amount of the stack + * match. + * + * @param item The ItemStack to match against + * @return false if item is null, true if any exactly matching ItemStacks + * were found + */ + public boolean contains(ItemStack item); + + /** + * Checks if the inventory contains any ItemStacks with the given + * materialId, adding to at least the minimum amount specified. + * + * @param materialId The materialId to check for + * @param amount The minimum amount to look for + * @return true if this contains any matching ItemStack with the given + * materialId and amount + * @deprecated Magic value + */ + @Deprecated + public boolean contains(int materialId, int amount); + + /** + * Checks if the inventory contains any ItemStacks with the given + * material, adding to at least the minimum amount specified. + * + * @param material The material to check for + * @param amount The minimum amount + * @return true if amount is less than 1, true if enough ItemStacks were + * found to add to the given amount + * @throws IllegalArgumentException if material is null + */ + public boolean contains(Material material, int amount) throws IllegalArgumentException; + + /** + * Checks if the inventory contains at least the minimum amount specified + * of exactly matching ItemStacks. + *

          + * An ItemStack only counts if both the type and the amount of the stack + * match. + * + * @param item the ItemStack to match against + * @param amount how many identical stacks to check for + * @return false if item is null, true if amount less than 1, true if + * amount of exactly matching ItemStacks were found + * @see #containsAtLeast(ItemStack, int) + */ + public boolean contains(ItemStack item, int amount); + + /** + * Checks if the inventory contains ItemStacks matching the given + * ItemStack whose amounts sum to at least the minimum amount specified. + * + * @param item the ItemStack to match against + * @param amount the minimum amount + * @return false if item is null, true if amount less than 1, true if + * enough ItemStacks were found to add to the given amount + */ + public boolean containsAtLeast(ItemStack item, int amount); + + /** + * Returns a HashMap with all slots and ItemStacks in the inventory with + * given materialId. + *

          + * The HashMap contains entries where, the key is the slot index, and the + * value is the ItemStack in that slot. If no matching ItemStack with the + * given materialId is found, an empty map is returned. + * + * @param materialId The materialId to look for + * @return A HashMap containing the slot index, ItemStack pairs + * @deprecated Magic value + */ + @Deprecated + public HashMap all(int materialId); + + /** + * Returns a HashMap with all slots and ItemStacks in the inventory with + * the given Material. + *

          + * The HashMap contains entries where, the key is the slot index, and the + * value is the ItemStack in that slot. If no matching ItemStack with the + * given Material is found, an empty map is returned. + * + * @param material The material to look for + * @return A HashMap containing the slot index, ItemStack pairs + * @throws IllegalArgumentException if material is null + */ + public HashMap all(Material material) throws IllegalArgumentException; + + /** + * Finds all slots in the inventory containing any ItemStacks with the + * given ItemStack. This will only match slots if both the type and the + * amount of the stack match + *

          + * The HashMap contains entries where, the key is the slot index, and the + * value is the ItemStack in that slot. If no matching ItemStack with the + * given Material is found, an empty map is returned. + * + * @param item The ItemStack to match against + * @return A map from slot indexes to item at index + */ + public HashMap all(ItemStack item); + + /** + * Finds the first slot in the inventory containing an ItemStack with the + * given materialId. + * + * @param materialId The materialId to look for + * @return The slot index of the given materialId or -1 if not found + * @deprecated Magic value + */ + @Deprecated + public int first(int materialId); + + /** + * Finds the first slot in the inventory containing an ItemStack with the + * given material + * + * @param material The material to look for + * @return The slot index of the given Material or -1 if not found + * @throws IllegalArgumentException if material is null + */ + public int first(Material material) throws IllegalArgumentException; + + /** + * Returns the first slot in the inventory containing an ItemStack with + * the given stack. This will only match a slot if both the type and the + * amount of the stack match + * + * @param item The ItemStack to match against + * @return The slot index of the given ItemStack or -1 if not found + */ + public int first(ItemStack item); + + /** + * Returns the first empty Slot. + * + * @return The first empty Slot found, or -1 if no empty slots. + */ + public int firstEmpty(); + + /** + * Removes all stacks in the inventory matching the given materialId. + * + * @param materialId The material to remove + * @deprecated Magic value + */ + @Deprecated + public void remove(int materialId); + + /** + * Removes all stacks in the inventory matching the given material. + * + * @param material The material to remove + * @throws IllegalArgumentException if material is null + */ + public void remove(Material material) throws IllegalArgumentException; + + /** + * Removes all stacks in the inventory matching the given stack. + *

          + * This will only match a slot if both the type and the amount of the + * stack match + * + * @param item The ItemStack to match against + */ + public void remove(ItemStack item); + + /** + * Clears out a particular slot in the index. + * + * @param index The index to empty. + */ + public void clear(int index); + + /** + * Clears out the whole Inventory. + */ + public void clear(); + + /** + * Gets a list of players viewing the inventory. Note that a player is + * considered to be viewing their own inventory and internal crafting + * screen even when said inventory is not open. They will normally be + * considered to be viewing their inventory even when they have a + * different inventory screen open, but it's possible for customized + * inventory screens to exclude the viewer's inventory, so this should + * never be assumed to be non-empty. + * + * @return A list of HumanEntities who are viewing this Inventory. + */ + public List getViewers(); + + /** + * Returns the title of this inventory. + * + * @return A String with the title. + */ + public String getTitle(); + + /** + * Returns what type of inventory this is. + * + * @return The InventoryType representing the type of inventory. + */ + public InventoryType getType(); + + /** + * Gets the block or entity belonging to the open inventory + * + * @return The holder of the inventory; null if it has no holder. + */ + public InventoryHolder getHolder(); + + @Override + public ListIterator iterator(); + + /** + * Returns an iterator starting at the given index. If the index is + * positive, then the first call to next() will return the item at that + * index; if it is negative, the first call to previous will return the + * item at index (getSize() + index). + * + * @param index The index. + * @return An iterator. + */ + public ListIterator iterator(int index); +} diff --git a/src/main/java/org/bukkit/inventory/InventoryHolder.java b/src/main/java/org/bukkit/inventory/InventoryHolder.java new file mode 100644 index 0000000..9c06a3d --- /dev/null +++ b/src/main/java/org/bukkit/inventory/InventoryHolder.java @@ -0,0 +1,11 @@ +package org.bukkit.inventory; + +public interface InventoryHolder { + + /** + * Get the object's inventory. + * + * @return The inventory. + */ + public Inventory getInventory(); +} diff --git a/src/main/java/org/bukkit/inventory/InventoryView.java b/src/main/java/org/bukkit/inventory/InventoryView.java new file mode 100644 index 0000000..7e98d52 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/InventoryView.java @@ -0,0 +1,231 @@ +package org.bukkit.inventory; + +import org.bukkit.GameMode; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; + +/** + * Represents a view linking two inventories and a single player (whose + * inventory may or may not be one of the two). + *

          + * Note: If you implement this interface but fail to satisfy the expected + * contracts of certain methods, there's no guarantee that the game will work + * as it should. + */ +public abstract class InventoryView { + public final static int OUTSIDE = -999; + /** + * Represents various extra properties of certain inventory windows. + */ + public enum Property { + /** + * The progress of the down-pointing arrow in a brewing inventory. + */ + BREW_TIME(0, InventoryType.BREWING), + /** + * The progress of the right-pointing arrow in a furnace inventory. + */ + COOK_TIME(0, InventoryType.FURNACE), + /** + * The progress of the flame in a furnace inventory. + */ + BURN_TIME(1, InventoryType.FURNACE), + /** + * How many total ticks the current fuel should last. + */ + TICKS_FOR_CURRENT_FUEL(2, InventoryType.FURNACE), + /** + * In an enchanting inventory, the top button's experience level + * value. + */ + ENCHANT_BUTTON1(0, InventoryType.ENCHANTING), + /** + * In an enchanting inventory, the middle button's experience level + * value. + */ + ENCHANT_BUTTON2(1, InventoryType.ENCHANTING), + /** + * In an enchanting inventory, the bottom button's experience level + * value. + */ + ENCHANT_BUTTON3(2, InventoryType.ENCHANTING); + int id; + InventoryType style; + private Property(int id, InventoryType appliesTo) { + this.id = id; + style = appliesTo; + } + + public InventoryType getType() { + return style; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + } + /** + * Get the upper inventory involved in this transaction. + * + * @return the inventory + */ + public abstract Inventory getTopInventory(); + + /** + * Get the lower inventory involved in this transaction. + * + * @return the inventory + */ + public abstract Inventory getBottomInventory(); + + /** + * Get the player viewing. + * + * @return the player + */ + public abstract HumanEntity getPlayer(); + + /** + * Determine the type of inventory involved in the transaction. This + * indicates the window style being shown. It will never return PLAYER, + * since that is common to all windows. + * + * @return the inventory type + */ + public abstract InventoryType getType(); + + /** + * Sets one item in this inventory view by its raw slot ID. + *

          + * Note: If slot ID -999 is chosen, it may be expected that the item is + * dropped on the ground. This is not required behaviour, however. + * + * @param slot The ID as returned by InventoryClickEvent.getRawSlot() + * @param item The new item to put in the slot, or null to clear it. + */ + public void setItem(int slot, ItemStack item) { + if (slot != OUTSIDE) { + if (slot < getTopInventory().getSize()) { + getTopInventory().setItem(convertSlot(slot),item); + } else { + getBottomInventory().setItem(convertSlot(slot),item); + } + } else { + getPlayer().getWorld().dropItemNaturally(getPlayer().getLocation(), item); + } + } + + /** + * Gets one item in this inventory view by its raw slot ID. + * + * @param slot The ID as returned by InventoryClickEvent.getRawSlot() + * @return The item currently in the slot. + */ + public ItemStack getItem(int slot) { + if (slot == OUTSIDE) { + return null; + } + if (slot < getTopInventory().getSize()) { + return getTopInventory().getItem(convertSlot(slot)); + } else { + return getBottomInventory().getItem(convertSlot(slot)); + } + } + + /** + * Sets the item on the cursor of one of the viewing players. + * + * @param item The item to put on the cursor, or null to remove the item + * on their cursor. + */ + public final void setCursor(ItemStack item) { + getPlayer().setItemOnCursor(item); + } + + /** + * Get the item on the cursor of one of the viewing players. + * + * @return The item on the player's cursor, or null if they aren't holding + * one. + */ + public final ItemStack getCursor() { + return getPlayer().getItemOnCursor(); + } + + /** + * Converts a raw slot ID into its local slot ID into whichever of the two + * inventories the slot points to. + *

          + * If the raw slot refers to the upper inventory, it will be returned + * unchanged and thus be suitable for getTopInventory().getItem(); if it + * refers to the lower inventory, the output will differ from the input + * and be suitable for getBottomInventory().getItem(). + * + * @param rawSlot The raw slot ID. + * @return The converted slot ID. + */ + public final int convertSlot(int rawSlot) { + int numInTop = getTopInventory().getSize(); + if (rawSlot < numInTop) { + return rawSlot; + } + int slot = rawSlot - numInTop; + if (getPlayer().getGameMode() == GameMode.CREATIVE && getType() == InventoryType.PLAYER) { + return slot; + } + if (getType() == InventoryType.CRAFTING) { + if(slot < 4) return 39 - slot; + else slot -= 4; + } + if (slot >= 27) slot -= 27; + else slot += 9; + return slot; + } + + /** + * Closes the inventory view. + */ + public final void close() { + getPlayer().closeInventory(); + } + + /** + * Check the total number of slots in this view, combining the upper and + * lower inventories. + *

          + * Note though that it's possible for this to be greater than the sum of + * the two inventories if for example some slots are not being used. + * + * @return The total size + */ + public final int countSlots() { + return getTopInventory().getSize() + getBottomInventory().getSize(); + } + + /** + * Sets an extra property of this inventory if supported by that + * inventory, for example the state of a progress bar. + * + * @param prop the window property to update + * @param value the new value for the window property + * @return true if the property was updated successfully, false if the + * property is not supported by that inventory + */ + public final boolean setProperty(Property prop, int value) { + return getPlayer().setWindowProperty(prop, value); + } + + /** + * Get the title of this inventory window. + * + * @return The title. + */ + public final String getTitle() { + return getTopInventory().getTitle(); + } +} diff --git a/src/main/java/org/bukkit/inventory/ItemFactory.java b/src/main/java/org/bukkit/inventory/ItemFactory.java new file mode 100644 index 0000000..52a8d4d --- /dev/null +++ b/src/main/java/org/bukkit/inventory/ItemFactory.java @@ -0,0 +1,124 @@ +package org.bukkit.inventory; + +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +/** + * An instance of the ItemFactory can be obtained with {@link + * Server#getItemFactory()}. + *

          + * The ItemFactory is solely responsible for creating item meta containers to + * apply on item stacks. + */ +public interface ItemFactory { + + /** + * This creates a new item meta for the material. + * + * @param material The material to consider as base for the meta + * @return a new ItemMeta that could be applied to an item stack of the + * specified material + */ + ItemMeta getItemMeta(final Material material); + + /** + * This method checks the item meta to confirm that it is applicable (no + * data lost if applied) to the specified ItemStack. + *

          + * A {@link SkullMeta} would not be valid for a sword, but a normal {@link + * ItemMeta} from an enchanted dirt block would. + * + * @param meta Meta to check + * @param stack Item that meta will be applied to + * @return true if the meta can be applied without losing data, false + * otherwise + * @throws IllegalArgumentException if the meta was not created by this + * factory + */ + boolean isApplicable(final ItemMeta meta, final ItemStack stack) throws IllegalArgumentException; + + /** + * This method checks the item meta to confirm that it is applicable (no + * data lost if applied) to the specified Material. + *

          + * A {@link SkullMeta} would not be valid for a sword, but a normal {@link + * ItemMeta} from an enchanted dirt block would. + * + * @param meta Meta to check + * @param material Material that meta will be applied to + * @return true if the meta can be applied without losing data, false + * otherwise + * @throws IllegalArgumentException if the meta was not created by this + * factory + */ + boolean isApplicable(final ItemMeta meta, final Material material) throws IllegalArgumentException; + + /** + * This method is used to compare two item meta data objects. + * + * @param meta1 First meta to compare, and may be null to indicate no data + * @param meta2 Second meta to compare, and may be null to indicate no + * data + * @return false if one of the meta has data the other does not, otherwise + * true + * @throws IllegalArgumentException if either meta was not created by this + * factory + */ + boolean equals(final ItemMeta meta1, final ItemMeta meta2) throws IllegalArgumentException; + + /** + * Returns an appropriate item meta for the specified stack. + *

          + * The item meta returned will always be a valid meta for a given + * ItemStack of the specified material. It may be a more or less specific + * meta, and could also be the same meta or meta type as the parameter. + * The item meta returned will also always be the most appropriate meta. + *

          + * Example, if a {@link SkullMeta} is being applied to a book, this method + * would return a {@link BookMeta} containing all information in the + * specified meta that is applicable to an {@link ItemMeta}, the highest + * common interface. + * + * @param meta the meta to convert + * @param stack the stack to convert the meta for + * @return An appropriate item meta for the specified item stack. No + * guarantees are made as to if a copy is returned. This will be null + * for a stack of air. + * @throws IllegalArgumentException if the specified meta was not created + * by this factory + */ + ItemMeta asMetaFor(final ItemMeta meta, final ItemStack stack) throws IllegalArgumentException; + + /** + * Returns an appropriate item meta for the specified material. + *

          + * The item meta returned will always be a valid meta for a given + * ItemStack of the specified material. It may be a more or less specific + * meta, and could also be the same meta or meta type as the parameter. + * The item meta returned will also always be the most appropriate meta. + *

          + * Example, if a {@link SkullMeta} is being applied to a book, this method + * would return a {@link BookMeta} containing all information in the + * specified meta that is applicable to an {@link ItemMeta}, the highest + * common interface. + * + * @param meta the meta to convert + * @param material the material to convert the meta for + * @return An appropriate item meta for the specified item material. No + * guarantees are made as to if a copy is returned. This will be null for air. + * @throws IllegalArgumentException if the specified meta was not created + * by this factory + */ + ItemMeta asMetaFor(final ItemMeta meta, final Material material) throws IllegalArgumentException; + + /** + * Returns the default color for all leather armor. + * + * @return the default color for leather armor + */ + Color getDefaultLeatherColor(); +} diff --git a/src/main/java/org/bukkit/inventory/ItemStack.java b/src/main/java/org/bukkit/inventory/ItemStack.java new file mode 100644 index 0000000..6137c99 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/ItemStack.java @@ -0,0 +1,603 @@ +package org.bukkit.inventory; + +import com.google.common.collect.ImmutableMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Utility; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.material.MaterialData; + +/** + * Represents a stack of items + */ +public class ItemStack implements Cloneable, ConfigurationSerializable { + private int type = 0; + private int amount = 0; + private MaterialData data = null; + private short durability = 0; + private ItemMeta meta; + + @Utility + protected ItemStack() {} + + /** + * Defaults stack size to 1, with no extra data + * + * @param type item material id + * @deprecated Magic value + */ + @Deprecated + public ItemStack(final int type) { + this(type, 1); + } + + /** + * Defaults stack size to 1, with no extra data + * + * @param type item material + */ + public ItemStack(final Material type) { + this(type, 1); + } + + /** + * An item stack with no extra data + * + * @param type item material id + * @param amount stack size + * @deprecated Magic value + */ + @Deprecated + public ItemStack(final int type, final int amount) { + this(type, amount, (short) 0); + } + + /** + * An item stack with no extra data + * + * @param type item material + * @param amount stack size + */ + public ItemStack(final Material type, final int amount) { + this(type.getId(), amount); + } + + /** + * An item stack with the specified damage / durability + * + * @param type item material id + * @param amount stack size + * @param damage durability / damage + * @deprecated Magic value + */ + @Deprecated + public ItemStack(final int type, final int amount, final short damage) { + this.type = type; + this.amount = amount; + this.durability = damage; + } + + /** + * An item stack with the specified damage / durabiltiy + * + * @param type item material + * @param amount stack size + * @param damage durability / damage + */ + public ItemStack(final Material type, final int amount, final short damage) { + this(type.getId(), amount, damage); + } + + /** + * @deprecated this method uses an ambiguous data byte object + */ + @Deprecated + public ItemStack(final int type, final int amount, final short damage, final Byte data) { + this.type = type; + this.amount = amount; + this.durability = damage; + if (data != null) { + createData(data); + this.durability = data; + } + } + + /** + * @deprecated this method uses an ambiguous data byte object + */ + @Deprecated + public ItemStack(final Material type, final int amount, final short damage, final Byte data) { + this(type.getId(), amount, damage, data); + } + + /** + * Creates a new item stack derived from the specified stack + * + * @param stack the stack to copy + * @throws IllegalArgumentException if the specified stack is null or + * returns an item meta not created by the item factory + */ + public ItemStack(final ItemStack stack) throws IllegalArgumentException { + Validate.notNull(stack, "Cannot copy null stack"); + this.type = stack.getTypeId(); + this.amount = stack.getAmount(); + this.durability = stack.getDurability(); + this.data = stack.getData(); + if (stack.hasItemMeta()) { + setItemMeta0(stack.getItemMeta(), getType0()); + } + } + + /** + * Gets the type of this item + * + * @return Type of the items in this stack + */ + @Utility + public Material getType() { + return getType0(getTypeId()); + } + + private Material getType0() { + return getType0(this.type); + } + + private static Material getType0(int id) { + Material material = Material.getMaterial(id); + return material == null ? Material.AIR : material; + } + + /** + * Sets the type of this item + *

          + * Note that in doing so you will reset the MaterialData for this stack + * + * @param type New type to set the items in this stack to + */ + @Utility + public void setType(Material type) { + Validate.notNull(type, "Material cannot be null"); + setTypeId(type.getId()); + } + + /** + * Gets the type id of this item + * + * @return Type Id of the items in this stack + * @deprecated Magic value + */ + @Deprecated + public int getTypeId() { + return type; + } + + /** + * Sets the type id of this item + *

          + * Note that in doing so you will reset the MaterialData for this stack + * + * @param type New type id to set the items in this stack to + * @deprecated Magic value + */ + @Deprecated + public void setTypeId(int type) { + this.type = type; + if (this.meta != null) { + this.meta = Bukkit.getItemFactory().asMetaFor(meta, getType0()); + } + createData((byte) 0); + } + + /** + * Gets the amount of items in this stack + * + * @return Amount of items in this stick + */ + public int getAmount() { + return amount; + } + + /** + * Sets the amount of items in this stack + * + * @param amount New amount of items in this stack + */ + public void setAmount(int amount) { + this.amount = amount; + } + + /** + * Gets the MaterialData for this stack of items + * + * @return MaterialData for this item + */ + public MaterialData getData() { + Material mat = getType(); + if (data == null && mat != null && mat.getData() != null) { + data = mat.getNewData((byte) this.getDurability()); + } + + return data; + } + + /** + * Sets the MaterialData for this stack of items + * + * @param data New MaterialData for this item + */ + public void setData(MaterialData data) { + Material mat = getType(); + + if (data == null || mat == null || mat.getData() == null) { + this.data = data; + } else { + if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) { + this.data = data; + } else { + throw new IllegalArgumentException("Provided data is not of type " + mat.getData().getName() + ", found " + data.getClass().getName()); + } + } + } + + /** + * Sets the durability of this item + * + * @param durability Durability of this item + */ + public void setDurability(final short durability) { + this.durability = durability; + } + + /** + * Gets the durability of this item + * + * @return Durability of this item + */ + public short getDurability() { + return durability; + } + + /** + * Get the maximum stacksize for the material hold in this ItemStack. + * (Returns -1 if it has no idea) + * + * @return The maximum you can stack this material to. + */ + @Utility + public int getMaxStackSize() { + Material material = getType(); + if (material != null) { + return material.getMaxStackSize(); + } + return -1; + } + + private void createData(final byte data) { + Material mat = Material.getMaterial(type); + + if (mat == null) { + this.data = new MaterialData(type, data); + } else { + this.data = mat.getNewData(data); + } + } + + @Override + @Utility + public String toString() { + StringBuilder toString = new StringBuilder("ItemStack{").append(getType().name()).append(" x ").append(getAmount()); + if (hasItemMeta()) { + toString.append(", ").append(getItemMeta()); + } + return toString.append('}').toString(); + } + + @Override + @Utility + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof ItemStack)) { + return false; + } + + ItemStack stack = (ItemStack) obj; + return getAmount() == stack.getAmount() && isSimilar(stack); + } + + /** + * This method is the same as equals, but does not consider stack size + * (amount). + * + * @param stack the item stack to compare to + * @return true if the two stacks are equal, ignoring the amount + */ + @Utility + public boolean isSimilar(ItemStack stack) { + if (stack == null) { + return false; + } + if (stack == this) { + return true; + } + return getTypeId() == stack.getTypeId() && getDurability() == stack.getDurability() && hasItemMeta() == stack.hasItemMeta() && (hasItemMeta() ? Bukkit.getItemFactory().equals(getItemMeta(), stack.getItemMeta()) : true); + } + + @Override + public ItemStack clone() { + try { + ItemStack itemStack = (ItemStack) super.clone(); + + if (this.meta != null) { + itemStack.meta = this.meta.clone(); + } + + if (this.data != null) { + itemStack.data = this.data.clone(); + } + + return itemStack; + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } + + @Override + @Utility + public final int hashCode() { + int hash = 1; + + hash = hash * 31 + getTypeId(); + hash = hash * 31 + getAmount(); + hash = hash * 31 + (getDurability() & 0xffff); + hash = hash * 31 + (hasItemMeta() ? (meta == null ? getItemMeta().hashCode() : meta.hashCode()) : 0); + + return hash; + } + + /** + * Checks if this ItemStack contains the given {@link Enchantment} + * + * @param ench Enchantment to test + * @return True if this has the given enchantment + */ + public boolean containsEnchantment(Enchantment ench) { + return meta == null ? false : meta.hasEnchant(ench); + } + + /** + * Gets the level of the specified enchantment on this item stack + * + * @param ench Enchantment to check + * @return Level of the enchantment, or 0 + */ + public int getEnchantmentLevel(Enchantment ench) { + return meta == null ? 0 : meta.getEnchantLevel(ench); + } + + /** + * Gets a map containing all enchantments and their levels on this item. + * + * @return Map of enchantments. + */ + public Map getEnchantments() { + return meta == null ? ImmutableMap.of() : meta.getEnchants(); + } + + /** + * Adds the specified enchantments to this item stack. + *

          + * This method is the same as calling {@link + * #addEnchantment(org.bukkit.enchantments.Enchantment, int)} for each + * element of the map. + * + * @param enchantments Enchantments to add + * @throws IllegalArgumentException if the specified enchantments is null + * @throws IllegalArgumentException if any specific enchantment or level + * is null. Warning: Some enchantments may be added before this + * exception is thrown. + */ + @Utility + public void addEnchantments(Map enchantments) { + Validate.notNull(enchantments, "Enchantments cannot be null"); + for (Map.Entry entry : enchantments.entrySet()) { + addEnchantment(entry.getKey(), entry.getValue()); + } + } + + /** + * Adds the specified {@link Enchantment} to this item stack. + *

          + * If this item stack already contained the given enchantment (at any + * level), it will be replaced. + * + * @param ench Enchantment to add + * @param level Level of the enchantment + * @throws IllegalArgumentException if enchantment null, or enchantment is + * not applicable + */ + @Utility + public void addEnchantment(Enchantment ench, int level) { + Validate.notNull(ench, "Enchantment cannot be null"); + if ((level < ench.getStartLevel()) || (level > ench.getMaxLevel())) { + throw new IllegalArgumentException("Enchantment level is either too low or too high (given " + level + ", bounds are " + ench.getStartLevel() + " to " + ench.getMaxLevel() + ")"); + } else if (!ench.canEnchantItem(this)) { + throw new IllegalArgumentException("Specified enchantment cannot be applied to this itemstack"); + } + + addUnsafeEnchantment(ench, level); + } + + /** + * Adds the specified enchantments to this item stack in an unsafe manner. + *

          + * This method is the same as calling {@link + * #addUnsafeEnchantment(org.bukkit.enchantments.Enchantment, int)} for + * each element of the map. + * + * @param enchantments Enchantments to add + */ + @Utility + public void addUnsafeEnchantments(Map enchantments) { + for (Map.Entry entry : enchantments.entrySet()) { + addUnsafeEnchantment(entry.getKey(), entry.getValue()); + } + } + + /** + * Adds the specified {@link Enchantment} to this item stack. + *

          + * If this item stack already contained the given enchantment (at any + * level), it will be replaced. + *

          + * This method is unsafe and will ignore level restrictions or item type. + * Use at your own discretion. + * + * @param ench Enchantment to add + * @param level Level of the enchantment + */ + public void addUnsafeEnchantment(Enchantment ench, int level) { + (meta == null ? meta = Bukkit.getItemFactory().getItemMeta(getType0()) : meta).addEnchant(ench, level, true); + } + + /** + * Removes the specified {@link Enchantment} if it exists on this + * ItemStack + * + * @param ench Enchantment to remove + * @return Previous level, or 0 + */ + public int removeEnchantment(Enchantment ench) { + int level = getEnchantmentLevel(ench); + if (level == 0 || meta == null) { + return level; + } + meta.removeEnchant(ench); + return level; + } + + @Utility + public Map serialize() { + Map result = new LinkedHashMap(); + + result.put("type", getType().name()); + + if (getDurability() != 0) { + result.put("damage", getDurability()); + } + + if (getAmount() != 1) { + result.put("amount", getAmount()); + } + + ItemMeta meta = getItemMeta(); + if (!Bukkit.getItemFactory().equals(meta, null)) { + result.put("meta", meta); + } + + return result; + } + + /** + * Required method for configuration serialization + * + * @param args map to deserialize + * @return deserialized item stack + * @see ConfigurationSerializable + */ + public static ItemStack deserialize(Map args) { + Material type = Material.getMaterial((String) args.get("type")); + short damage = 0; + int amount = 1; + + if (args.containsKey("damage")) { + damage = ((Number) args.get("damage")).shortValue(); + } + + if (args.containsKey("amount")) { + amount = (Integer) args.get("amount"); + } + + ItemStack result = new ItemStack(type, amount, damage); + + if (args.containsKey("enchantments")) { // Backward compatiblity, @deprecated + Object raw = args.get("enchantments"); + + if (raw instanceof Map) { + Map map = (Map) raw; + + for (Map.Entry entry : map.entrySet()) { + Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); + + if ((enchantment != null) && (entry.getValue() instanceof Integer)) { + result.addUnsafeEnchantment(enchantment, (Integer) entry.getValue()); + } + } + } + } else if (args.containsKey("meta")) { // We cannot and will not have meta when enchantments (pre-ItemMeta) exist + Object raw = args.get("meta"); + if (raw instanceof ItemMeta) { + result.setItemMeta((ItemMeta) raw); + } + } + + return result; + } + + /** + * Get a copy of this ItemStack's {@link ItemMeta}. + * + * @return a copy of the current ItemStack's ItemData + */ + public ItemMeta getItemMeta() { + return this.meta == null ? Bukkit.getItemFactory().getItemMeta(getType0()) : this.meta.clone(); + } + + /** + * Checks to see if any meta data has been defined. + * + * @return Returns true if some meta data has been set for this item + */ + public boolean hasItemMeta() { + return !Bukkit.getItemFactory().equals(meta, null); + } + + /** + * Set the ItemMeta of this ItemStack. + * + * @param itemMeta new ItemMeta, or null to indicate meta data be cleared. + * @return True if successfully applied ItemMeta, see {@link + * ItemFactory#isApplicable(ItemMeta, ItemStack)} + * @throws IllegalArgumentException if the item meta was not created by + * the {@link ItemFactory} + */ + public boolean setItemMeta(ItemMeta itemMeta) { + return setItemMeta0(itemMeta, getType0()); + } + + /* + * Cannot be overridden, so it's safe for constructor call + */ + private boolean setItemMeta0(ItemMeta itemMeta, Material material) { + if (itemMeta == null) { + this.meta = null; + return true; + } + if (!Bukkit.getItemFactory().isApplicable(itemMeta, material)) { + return false; + } + this.meta = Bukkit.getItemFactory().asMetaFor(itemMeta, material); + if (this.meta == itemMeta) { + this.meta = itemMeta.clone(); + } + + return true; + } +} diff --git a/src/main/java/org/bukkit/inventory/MerchantInventory.java b/src/main/java/org/bukkit/inventory/MerchantInventory.java new file mode 100644 index 0000000..163f459 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/MerchantInventory.java @@ -0,0 +1,4 @@ +package org.bukkit.inventory; + +public interface MerchantInventory extends Inventory { +} diff --git a/src/main/java/org/bukkit/inventory/PlayerInventory.java b/src/main/java/org/bukkit/inventory/PlayerInventory.java new file mode 100644 index 0000000..d18c9f4 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/PlayerInventory.java @@ -0,0 +1,130 @@ +package org.bukkit.inventory; + +import org.bukkit.entity.HumanEntity; + +/** + * Interface to the inventory of a Player, including the four armor slots. + */ +public interface PlayerInventory extends Inventory { + + /** + * Get all ItemStacks from the armor slots + * + * @return All the ItemStacks from the armor slots + */ + public ItemStack[] getArmorContents(); + + /** + * Return the ItemStack from the helmet slot + * + * @return The ItemStack in the helmet slot + */ + public ItemStack getHelmet(); + + /** + * Return the ItemStack from the chestplate slot + * + * @return The ItemStack in the chestplate slot + */ + public ItemStack getChestplate(); + + /** + * Return the ItemStack from the leg slot + * + * @return The ItemStack in the leg slot + */ + public ItemStack getLeggings(); + + /** + * Return the ItemStack from the boots slot + * + * @return The ItemStack in the boots slot + */ + public ItemStack getBoots(); + + /** + * Put the given ItemStacks into the armor slots + * + * @param items The ItemStacks to use as armour + */ + public void setArmorContents(ItemStack[] items); + + /** + * Put the given ItemStack into the helmet slot. This does not check if + * the ItemStack is a helmet + * + * @param helmet The ItemStack to use as helmet + */ + public void setHelmet(ItemStack helmet); + + /** + * Put the given ItemStack into the chestplate slot. This does not check + * if the ItemStack is a chestplate + * + * @param chestplate The ItemStack to use as chestplate + */ + public void setChestplate(ItemStack chestplate); + + /** + * Put the given ItemStack into the leg slot. This does not check if the + * ItemStack is a pair of leggings + * + * @param leggings The ItemStack to use as leggings + */ + public void setLeggings(ItemStack leggings); + + /** + * Put the given ItemStack into the boots slot. This does not check if the + * ItemStack is a boots + * + * @param boots The ItemStack to use as boots + */ + public void setBoots(ItemStack boots); + + /** + * Returns the ItemStack currently hold + * + * @return The currently held ItemStack + */ + public ItemStack getItemInHand(); + + /** + * Sets the item in hand + * + * @param stack Stack to set + */ + public void setItemInHand(ItemStack stack); + + /** + * Get the slot number of the currently held item + * + * @return Held item slot number + */ + public int getHeldItemSlot(); + + /** + * Set the slot number of the currently held item. + *

          + * This validates whether the slot is between 0 and 8 inclusive. + * + * @param slot The new slot number + * @throws IllegalArgumentException Thrown if slot is not between 0 and 8 + * inclusive + */ + public void setHeldItemSlot(int slot); + + /** + * Clears all matching items from the inventory. Setting either value to + * -1 will skip it's check, while setting both to -1 will clear all items + * in your inventory unconditionally. + * + * @param id the id of the item you want to clear from the inventory + * @param data the data of the item you want to clear from the inventory + * @return The number of items cleared + * @deprecated Magic value + */ + @Deprecated + public int clear(int id, int data); + + public HumanEntity getHolder(); +} diff --git a/src/main/java/org/bukkit/inventory/Recipe.java b/src/main/java/org/bukkit/inventory/Recipe.java new file mode 100644 index 0000000..7977ce2 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/Recipe.java @@ -0,0 +1,14 @@ +package org.bukkit.inventory; + +/** + * Represents some type of crafting recipe. + */ +public interface Recipe { + + /** + * Get the result of this recipe. + * + * @return The result stack + */ + ItemStack getResult(); +} diff --git a/src/main/java/org/bukkit/inventory/ShapedRecipe.java b/src/main/java/org/bukkit/inventory/ShapedRecipe.java new file mode 100644 index 0000000..2796473 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/ShapedRecipe.java @@ -0,0 +1,148 @@ +package org.bukkit.inventory; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.Validate; + +import org.bukkit.Material; +import org.bukkit.material.MaterialData; + +/** + * Represents a shaped (ie normal) crafting recipe. + */ +public class ShapedRecipe implements Recipe { + private ItemStack output; + private String[] rows; + private Map ingredients = new HashMap(); + + /** + * Create a shaped recipe to craft the specified ItemStack. The + * constructor merely determines the result and type; to set the actual + * recipe, you'll need to call the appropriate methods. + * + * @param result The item you want the recipe to create. + * @see ShapedRecipe#shape(String...) + * @see ShapedRecipe#setIngredient(char, Material) + * @see ShapedRecipe#setIngredient(char, Material, int) + * @see ShapedRecipe#setIngredient(char, MaterialData) + */ + public ShapedRecipe(ItemStack result) { + this.output = new ItemStack(result); + } + + /** + * Set the shape of this recipe to the specified rows. Each character + * represents a different ingredient; exactly what each character + * represents is set separately. The first row supplied corresponds with + * the upper most part of the recipe on the workbench e.g. if all three + * rows are supplies the first string represents the top row on the + * workbench. + * + * @param shape The rows of the recipe (up to 3 rows). + * @return The changed recipe, so you can chain calls. + */ + public ShapedRecipe shape(final String... shape) { + Validate.notNull(shape, "Must provide a shape"); + Validate.isTrue(shape.length > 0 && shape.length < 4, "Crafting recipes should be 1, 2, 3 rows, not ", shape.length); + + for (String row : shape) { + Validate.notNull(row, "Shape cannot have null rows"); + Validate.isTrue(row.length() > 0 && row.length() < 4, "Crafting rows should be 1, 2, or 3 characters, not ", row.length()); + } + this.rows = new String[shape.length]; + for (int i = 0; i < shape.length; i++) { + this.rows[i] = shape[i]; + } + + // Remove character mappings for characters that no longer exist in the shape + HashMap newIngredients = new HashMap(); + for (String row : shape) { + for (Character c : row.toCharArray()) { + newIngredients.put(c, ingredients.get(c)); + } + } + this.ingredients = newIngredients; + + return this; + } + + /** + * Sets the material that a character in the recipe shape refers to. + * + * @param key The character that represents the ingredient in the shape. + * @param ingredient The ingredient. + * @return The changed recipe, so you can chain calls. + */ + public ShapedRecipe setIngredient(char key, MaterialData ingredient) { + return setIngredient(key, ingredient.getItemType(), ingredient.getData()); + } + + /** + * Sets the material that a character in the recipe shape refers to. + * + * @param key The character that represents the ingredient in the shape. + * @param ingredient The ingredient. + * @return The changed recipe, so you can chain calls. + */ + public ShapedRecipe setIngredient(char key, Material ingredient) { + return setIngredient(key, ingredient, 0); + } + + /** + * Sets the material that a character in the recipe shape refers to. + * + * @param key The character that represents the ingredient in the shape. + * @param ingredient The ingredient. + * @param raw The raw material data as an integer. + * @return The changed recipe, so you can chain calls. + * @deprecated Magic value + */ + @Deprecated + public ShapedRecipe setIngredient(char key, Material ingredient, int raw) { + Validate.isTrue(ingredients.containsKey(key), "Symbol does not appear in the shape:", key); + + // -1 is the old wildcard, map to Short.MAX_VALUE as the new one + if (raw == -1) { + raw = Short.MAX_VALUE; + } + + ingredients.put(key, new ItemStack(ingredient, 1, (short) raw)); + return this; + } + + /** + * Get a copy of the ingredients map. + * + * @return The mapping of character to ingredients. + */ + public Map getIngredientMap() { + HashMap result = new HashMap(); + for (Map.Entry ingredient : ingredients.entrySet()) { + if (ingredient.getValue() == null) { + result.put(ingredient.getKey(), null); + } else { + result.put(ingredient.getKey(), ingredient.getValue().clone()); + } + } + return result; + } + + /** + * Get the shape. + * + * @return The recipe's shape. + */ + public String[] getShape() { + return rows.clone(); + } + + /** + * Get the result. + * + * @return The result stack. + */ + public ItemStack getResult() { + return output.clone(); + } +} diff --git a/src/main/java/org/bukkit/inventory/ShapelessRecipe.java b/src/main/java/org/bukkit/inventory/ShapelessRecipe.java new file mode 100644 index 0000000..a718086 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/ShapelessRecipe.java @@ -0,0 +1,226 @@ +package org.bukkit.inventory; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang.Validate; + +import org.bukkit.Material; +import org.bukkit.material.MaterialData; + +/** + * Represents a shapeless recipe, where the arrangement of the ingredients on + * the crafting grid does not matter. + */ +public class ShapelessRecipe implements Recipe { + private ItemStack output; + private List ingredients = new ArrayList(); + + /** + * Create a shapeless recipe to craft the specified ItemStack. The + * constructor merely determines the result and type; to set the actual + * recipe, you'll need to call the appropriate methods. + * + * @param result The item you want the recipe to create. + * @see ShapelessRecipe#addIngredient(Material) + * @see ShapelessRecipe#addIngredient(MaterialData) + * @see ShapelessRecipe#addIngredient(Material,int) + * @see ShapelessRecipe#addIngredient(int,Material) + * @see ShapelessRecipe#addIngredient(int,MaterialData) + * @see ShapelessRecipe#addIngredient(int,Material,int) + */ + public ShapelessRecipe(ItemStack result) { + this.output = new ItemStack(result); + } + + /** + * Adds the specified ingredient. + * + * @param ingredient The ingredient to add. + * @return The changed recipe, so you can chain calls. + */ + public ShapelessRecipe addIngredient(MaterialData ingredient) { + return addIngredient(1, ingredient); + } + + /** + * Adds the specified ingredient. + * + * @param ingredient The ingredient to add. + * @return The changed recipe, so you can chain calls. + */ + public ShapelessRecipe addIngredient(Material ingredient) { + return addIngredient(1, ingredient, 0); + } + + /** + * Adds the specified ingredient. + * + * @param ingredient The ingredient to add. + * @param rawdata The data value, or -1 to allow any data value. + * @return The changed recipe, so you can chain calls. + * @deprecated Magic value + */ + @Deprecated + public ShapelessRecipe addIngredient(Material ingredient, int rawdata) { + return addIngredient(1, ingredient, rawdata); + } + + /** + * Adds multiples of the specified ingredient. + * + * @param count How many to add (can't be more than 9!) + * @param ingredient The ingredient to add. + * @return The changed recipe, so you can chain calls. + */ + public ShapelessRecipe addIngredient(int count, MaterialData ingredient) { + return addIngredient(count, ingredient.getItemType(), ingredient.getData()); + } + + /** + * Adds multiples of the specified ingredient. + * + * @param count How many to add (can't be more than 9!) + * @param ingredient The ingredient to add. + * @return The changed recipe, so you can chain calls. + */ + public ShapelessRecipe addIngredient(int count, Material ingredient) { + return addIngredient(count, ingredient, 0); + } + + /** + * Adds multiples of the specified ingredient. + * + * @param count How many to add (can't be more than 9!) + * @param ingredient The ingredient to add. + * @param rawdata The data value, or -1 to allow any data value. + * @return The changed recipe, so you can chain calls. + * @deprecated Magic value + */ + @Deprecated + public ShapelessRecipe addIngredient(int count, Material ingredient, int rawdata) { + Validate.isTrue(ingredients.size() + count <= 9, "Shapeless recipes cannot have more than 9 ingredients"); + + // -1 is the old wildcard, map to Short.MAX_VALUE as the new one + if (rawdata == -1) { + rawdata = Short.MAX_VALUE; + } + + while (count-- > 0) { + ingredients.add(new ItemStack(ingredient, 1, (short) rawdata)); + } + return this; + } + + /** + * Removes an ingredient from the list. If the ingredient occurs multiple + * times, only one instance of it is removed. Only removes exact matches, + * with a data value of 0. + * + * @param ingredient The ingredient to remove + * @return The changed recipe. + */ + public ShapelessRecipe removeIngredient(Material ingredient) { + return removeIngredient(ingredient, 0); + } + + /** + * Removes an ingredient from the list. If the ingredient occurs multiple + * times, only one instance of it is removed. If the data value is -1, + * only ingredients with a -1 data value will be removed. + * + * @param ingredient The ingredient to remove + * @return The changed recipe. + */ + public ShapelessRecipe removeIngredient(MaterialData ingredient) { + return removeIngredient(ingredient.getItemType(), ingredient.getData()); + } + + /** + * Removes multiple instances of an ingredient from the list. If there are + * less instances then specified, all will be removed. Only removes exact + * matches, with a data value of 0. + * + * @param count The number of copies to remove. + * @param ingredient The ingredient to remove + * @return The changed recipe. + */ + public ShapelessRecipe removeIngredient(int count, Material ingredient) { + return removeIngredient(count, ingredient, 0); + } + + /** + * Removes multiple instances of an ingredient from the list. If there are + * less instances then specified, all will be removed. If the data value + * is -1, only ingredients with a -1 data value will be removed. + * + * @param count The number of copies to remove. + * @param ingredient The ingredient to remove. + * @return The changed recipe. + */ + public ShapelessRecipe removeIngredient(int count, MaterialData ingredient) { + return removeIngredient(count, ingredient.getItemType(), ingredient.getData()); + } + + /** + * Removes an ingredient from the list. If the ingredient occurs multiple + * times, only one instance of it is removed. If the data value is -1, + * only ingredients with a -1 data value will be removed. + * + * @param ingredient The ingredient to remove + * @param rawdata The data value; + * @return The changed recipe. + * @deprecated Magic value + */ + @Deprecated + public ShapelessRecipe removeIngredient(Material ingredient, int rawdata) { + return removeIngredient(1, ingredient, rawdata); + } + + /** + * Removes multiple instances of an ingredient from the list. If there are + * less instances then specified, all will be removed. If the data value + * is -1, only ingredients with a -1 data value will be removed. + * + * @param count The number of copies to remove. + * @param ingredient The ingredient to remove. + * @param rawdata The data value. + * @return The changed recipe. + * @deprecated Magic value + */ + @Deprecated + public ShapelessRecipe removeIngredient(int count, Material ingredient, int rawdata) { + Iterator iterator = ingredients.iterator(); + while (count > 0 && iterator.hasNext()) { + ItemStack stack = iterator.next(); + if (stack.getType() == ingredient && stack.getDurability() == rawdata) { + iterator.remove(); + count--; + } + } + return this; + } + + /** + * Get the result of this recipe. + * + * @return The result stack. + */ + public ItemStack getResult() { + return output.clone(); + } + + /** + * Get the list of ingredients used for this recipe. + * + * @return The input list + */ + public List getIngredientList() { + ArrayList result = new ArrayList(ingredients.size()); + for (ItemStack ingredient : ingredients) { + result.add(ingredient.clone()); + } + return result; + } +} diff --git a/src/main/java/org/bukkit/inventory/meta/BookMeta.java b/src/main/java/org/bukkit/inventory/meta/BookMeta.java new file mode 100644 index 0000000..0017596 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/BookMeta.java @@ -0,0 +1,130 @@ +package org.bukkit.inventory.meta; + +import java.util.List; + +import org.bukkit.Material; + +/** + * Represents a book ({@link Material#BOOK_AND_QUILL} or {@link + * Material#WRITTEN_BOOK}) that can have a title, an author, and pages. + */ +public interface BookMeta extends ItemMeta { + + /** + * Checks for the existence of a title in the book. + * + * @return true if the book has a title + */ + boolean hasTitle(); + + /** + * Gets the title of the book. + *

          + * Plugins should check that hasTitle() returns true before calling this + * method. + * + * @return the title of the book + */ + String getTitle(); + + /** + * Sets the title of the book. + *

          + * Limited to 16 characters. Removes title when given null. + * + * @param title the title to set + * @return true if the title was successfully set + */ + boolean setTitle(String title); + + /** + * Checks for the existence of an author in the book. + * + * @return the author of the book + */ + boolean hasAuthor(); + + /** + * Gets the author of the book. + *

          + * Plugins should check that hasAuthor() returns true before calling this + * method. + * + * @return the author of the book + */ + String getAuthor(); + + /** + * Sets the author of the book. Removes author when given null. + * + * @param author the author of the book + */ + void setAuthor(String author); + + /** + * Checks for the existence of pages in the book. + * + * @return true if the book has pages + */ + boolean hasPages(); + + /** + * Gets the specified page in the book. The given page must exist. + * + * @param page the page number to get + * @return the page from the book + */ + String getPage(int page); + + /** + * Sets the specified page in the book. Pages of the book must be + * contiguous. + *

          + * The data can be up to 256 characters in length, additional characters + * are truncated. + * + * @param page the page number to set + * @param data the data to set for that page + */ + void setPage(int page, String data); + + /** + * Gets all the pages in the book. + * + * @return list of all the pages in the book + */ + List getPages(); + + /** + * Clears the existing book pages, and sets the book to use the provided + * pages. Maximum 50 pages with 256 characters per page. + * + * @param pages A list of pages to set the book to use + */ + void setPages(List pages); + + /** + * Clears the existing book pages, and sets the book to use the provided + * pages. Maximum 50 pages with 256 characters per page. + * + * @param pages A list of strings, each being a page + */ + void setPages(String... pages); + + /** + * Adds new pages to the end of the book. Up to a maximum of 50 pages with + * 256 characters per page. + * + * @param pages A list of strings, each being a page + */ + void addPage(String... pages); + + /** + * Gets the number of pages in the book. + * + * @return the number of pages in the book + */ + int getPageCount(); + + BookMeta clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java b/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java new file mode 100644 index 0000000..fb93d03 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java @@ -0,0 +1,79 @@ +package org.bukkit.inventory.meta; + +import java.util.Map; + +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +/** + * EnchantmentMeta is specific to items that can store enchantments, as + * opposed to being enchanted. {@link Material#ENCHANTED_BOOK} is an example + * of an item with enchantment storage. + */ +public interface EnchantmentStorageMeta extends ItemMeta { + + /** + * Checks for the existence of any stored enchantments. + * + * @return true if an enchantment exists on this meta + */ + boolean hasStoredEnchants(); + + /** + * Checks for storage of the specified enchantment. + * + * @param ench enchantment to check + * @return true if this enchantment is stored in this meta + */ + boolean hasStoredEnchant(Enchantment ench); + + /** + * Checks for the level of the stored enchantment. + * + * @param ench enchantment to check + * @return The level that the specified stored enchantment has, or 0 if + * none + */ + int getStoredEnchantLevel(Enchantment ench); + + /** + * Gets a copy the stored enchantments in this ItemMeta. + * + * @return An immutable copy of the stored enchantments + */ + Map getStoredEnchants(); + + /** + * Stores the specified enchantment in this item meta. + * + * @param ench Enchantment to store + * @param level Level for the enchantment + * @param ignoreLevelRestriction this indicates the enchantment should be + * applied, ignoring the level limit + * @return true if the item meta changed as a result of this call, false + * otherwise + * @throws IllegalArgumentException if enchantment is null + */ + boolean addStoredEnchant(Enchantment ench, int level, boolean ignoreLevelRestriction); + + /** + * Remove the specified stored enchantment from this item meta. + * + * @param ench Enchantment to remove + * @return true if the item meta changed as a result of this call, false + * otherwise + * @throws IllegalArgumentException if enchantment is null + */ + boolean removeStoredEnchant(Enchantment ench) throws IllegalArgumentException; + + /** + * Checks if the specified enchantment conflicts with any enchantments in + * this ItemMeta. + * + * @param ench enchantment to test + * @return true if the enchantment conflicts, false otherwise + */ + boolean hasConflictingStoredEnchant(Enchantment ench); + + EnchantmentStorageMeta clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java b/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java new file mode 100644 index 0000000..47046f1 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java @@ -0,0 +1,34 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.FireworkEffect; +import org.bukkit.Material; + +/** + * Represents a meta that can store a single FireworkEffect. An example + * includes {@link Material#FIREWORK_CHARGE}. + */ +public interface FireworkEffectMeta extends ItemMeta { + + /** + * Sets the firework effect for this meta. + * + * @param effect the effect to set, or null to indicate none. + */ + void setEffect(FireworkEffect effect); + + /** + * Checks if this meta has an effect. + * + * @return true if this meta has an effect, false otherwise + */ + boolean hasEffect(); + + /** + * Gets the firework effect for this meta. + * + * @return the current effect, or null if none + */ + FireworkEffect getEffect(); + + FireworkEffectMeta clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java b/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java new file mode 100644 index 0000000..3e06ee0 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java @@ -0,0 +1,94 @@ +package org.bukkit.inventory.meta; + +import java.util.List; + +import org.bukkit.FireworkEffect; +import org.bukkit.Material; + +/** + * Represents a {@link Material#FIREWORK} and its effects. + */ +public interface FireworkMeta extends ItemMeta { + + /** + * Add another effect to this firework. + * + * @param effect The firework effect to add + * @throws IllegalArgumentException If effect is null + */ + void addEffect(FireworkEffect effect) throws IllegalArgumentException; + + /** + * Add several effects to this firework. + * + * @param effects The firework effects to add + * @throws IllegalArgumentException If effects is null + * @throws IllegalArgumentException If any effect is null (may be thrown + * after changes have occurred) + */ + void addEffects(FireworkEffect...effects) throws IllegalArgumentException; + + /** + * Add several firework effects to this firework. + * + * @param effects An iterable object whose iterator yields the desired + * firework effects + * @throws IllegalArgumentException If effects is null + * @throws IllegalArgumentException If any effect is null (may be thrown + * after changes have occurred) + */ + void addEffects(Iterable effects) throws IllegalArgumentException; + + /** + * Get the effects in this firework. + * + * @return An immutable list of the firework effects + */ + List getEffects(); + + /** + * Get the number of effects in this firework. + * + * @return The number of effects + */ + int getEffectsSize(); + + /** + * Remove an effect from this firework. + * + * @param index The index of the effect to remove + * @throws IndexOutOfBoundsException If index < 0 or index > {@link + * #getEffectsSize()} + */ + void removeEffect(int index) throws IndexOutOfBoundsException; + + /** + * Remove all effects from this firework. + */ + void clearEffects(); + + /** + * Get whether this firework has any effects. + * + * @return true if it has effects, false if there are no effects + */ + boolean hasEffects(); + + /** + * Gets the approximate height the firework will fly. + * + * @return approximate flight height of the firework. + */ + int getPower(); + + /** + * Sets the approximate power of the firework. Each level of power is half + * a second of flight time. + * + * @param power the power of the firework, from 0-128 + * @throws IllegalArgumentException if height<0 or height>128 + */ + void setPower(int power) throws IllegalArgumentException; + + FireworkMeta clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/ItemMeta.java b/src/main/java/org/bukkit/inventory/meta/ItemMeta.java new file mode 100644 index 0000000..397ba11 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/ItemMeta.java @@ -0,0 +1,129 @@ +package org.bukkit.inventory.meta; + +import java.util.List; +import java.util.Map; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.enchantments.Enchantment; + +/** + * This type represents the storage mechanism for auxiliary item data. + *

          + * An implementation will handle the creation and application for ItemMeta. + * This class should not be implemented by a plugin in a live environment. + */ +public interface ItemMeta extends Cloneable, ConfigurationSerializable { + + /** + * Checks for existence of a display name. + * + * @return true if this has a display name + */ + boolean hasDisplayName(); + + /** + * Gets the display name that is set. + *

          + * Plugins should check that hasDisplayName() returns true + * before calling this method. + * + * @return the display name that is set + */ + String getDisplayName(); + + /** + * Sets the display name. + * + * @param name the name to set + */ + void setDisplayName(String name); + + /** + * Checks for existence of lore. + * + * @return true if this has lore + */ + boolean hasLore(); + + /** + * Gets the lore that is set. + *

          + * Plugins should check if hasLore() returns true before + * calling this method. + * + * @return a list of lore that is set + */ + List getLore(); + + /** + * Sets the lore for this item. + * Removes lore when given null. + * + * @param lore the lore that will be set + */ + void setLore(List lore); + + /** + * Checks for the existence of any enchantments. + * + * @return true if an enchantment exists on this meta + */ + boolean hasEnchants(); + + /** + * Checks for existence of the specified enchantment. + * + * @param ench enchantment to check + * @return true if this enchantment exists for this meta + */ + boolean hasEnchant(Enchantment ench); + + /** + * Checks for the level of the specified enchantment. + * + * @param ench enchantment to check + * @return The level that the specified enchantment has, or 0 if none + */ + int getEnchantLevel(Enchantment ench); + + /** + * Returns a copy the enchantments in this ItemMeta.
          + * Returns an empty map if none. + * + * @return An immutable copy of the enchantments + */ + Map getEnchants(); + + /** + * Adds the specified enchantment to this item meta. + * + * @param ench Enchantment to add + * @param level Level for the enchantment + * @param ignoreLevelRestriction this indicates the enchantment should be + * applied, ignoring the level limit + * @return true if the item meta changed as a result of this call, false + * otherwise + */ + boolean addEnchant(Enchantment ench, int level, boolean ignoreLevelRestriction); + + /** + * Removes the specified enchantment from this item meta. + * + * @param ench Enchantment to remove + * @return true if the item meta changed as a result of this call, false + * otherwise + */ + boolean removeEnchant(Enchantment ench); + + /** + * Checks if the specified enchantment conflicts with any enchantments in + * this ItemMeta. + * + * @param ench enchantment to test + * @return true if the enchantment conflicts, false otherwise + */ + boolean hasConflictingEnchant(Enchantment ench); + + @SuppressWarnings("javadoc") + ItemMeta clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java b/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java new file mode 100644 index 0000000..2dc2420 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java @@ -0,0 +1,31 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFactory; + +/** + * Represents leather armor ({@link Material#LEATHER_BOOTS}, {@link + * Material#LEATHER_CHESTPLATE}, {@link Material#LEATHER_HELMET}, or {@link + * Material#LEATHER_LEGGINGS}) that can be colored. + */ +public interface LeatherArmorMeta extends ItemMeta { + + /** + * Gets the color of the armor. If it has not been set otherwise, it will + * be {@link ItemFactory#getDefaultLeatherColor()}. + * + * @return the color of the armor, never null + */ + Color getColor(); + + /** + * Sets the color of the armor. + * + * @param color the color to set. Setting it to null is equivalent to + * setting it to {@link ItemFactory#getDefaultLeatherColor()}. + */ + void setColor(Color color); + + LeatherArmorMeta clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/MapMeta.java b/src/main/java/org/bukkit/inventory/meta/MapMeta.java new file mode 100644 index 0000000..fb5c297 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/MapMeta.java @@ -0,0 +1,23 @@ +package org.bukkit.inventory.meta; + +/** + * Represents a map that can be scalable. + */ +public interface MapMeta extends ItemMeta { + + /** + * Checks to see if this map is scaling. + * + * @return true if this map is scaling + */ + boolean isScaling(); + + /** + * Sets if this map is scaling or not. + * + * @param value true to scale + */ + void setScaling(boolean value); + + MapMeta clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/PotionMeta.java b/src/main/java/org/bukkit/inventory/meta/PotionMeta.java new file mode 100644 index 0000000..8dca983 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/PotionMeta.java @@ -0,0 +1,77 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.Material; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.List; + +/** + * Represents a potion ({@link Material#POTION}) that can have custom effects. + */ +public interface PotionMeta extends ItemMeta { + + /** + * Checks for the presence of custom potion effects. + * + * @return true if custom potion effects are applied + */ + boolean hasCustomEffects(); + + /** + * Gets an immutable list containing all custom potion effects applied to + * this potion. + *

          + * Plugins should check that hasCustomEffects() returns true before + * calling this method. + * + * @return the immutable list of custom potion effects + */ + List getCustomEffects(); + + /** + * Adds a custom potion effect to this potion. + * + * @param effect the potion effect to add + * @param overwrite true if any existing effect of the same type should be + * overwritten + * @return true if the potion meta changed as a result of this call + */ + boolean addCustomEffect(PotionEffect effect, boolean overwrite); + + /** + * Removes a custom potion effect from this potion. + * + * @param type the potion effect type to remove + * @return true if the potion meta changed as a result of this call + */ + boolean removeCustomEffect(PotionEffectType type); + + /** + * Checks for a specific custom potion effect type on this potion. + * + * @param type the potion effect type to check for + * @return true if the potion has this effect + */ + boolean hasCustomEffect(PotionEffectType type); + + /** + * Moves a potion effect to the top of the potion effect list. + *

          + * This causes the client to display the potion effect in the potion's + * name. + * + * @param type the potion effect type to move + * @return true if the potion meta changed as a result of this call + */ + boolean setMainEffect(PotionEffectType type); + + /** + * Removes all custom potion effects from this potion. + * + * @return true if the potion meta changed as a result of this call + */ + boolean clearCustomEffects(); + + PotionMeta clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/Repairable.java b/src/main/java/org/bukkit/inventory/meta/Repairable.java new file mode 100644 index 0000000..c49844e --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/Repairable.java @@ -0,0 +1,31 @@ +package org.bukkit.inventory.meta; + +/** + * Represents an item that can be repaired at an anvil. + */ +public interface Repairable { + + /** + * Checks to see if this has a repair penalty + * + * @return true if this has a repair penalty + */ + boolean hasRepairCost(); + + /** + * Gets the repair penalty + * + * @return the repair penalty + */ + int getRepairCost(); + + /** + * Sets the repair penalty + * + * @param cost repair penalty + */ + void setRepairCost(int cost); + + @SuppressWarnings("javadoc") + Repairable clone(); +} diff --git a/src/main/java/org/bukkit/inventory/meta/SkullMeta.java b/src/main/java/org/bukkit/inventory/meta/SkullMeta.java new file mode 100644 index 0000000..fab3119 --- /dev/null +++ b/src/main/java/org/bukkit/inventory/meta/SkullMeta.java @@ -0,0 +1,36 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.Material; + +/** + * Represents a skull ({@link Material#SKULL_ITEM}) that can have an owner. + */ +public interface SkullMeta extends ItemMeta { + + /** + * Gets the owner of the skull. + * + * @return the owner if the skull + */ + String getOwner(); + + /** + * Checks to see if the skull has an owner. + * + * @return true if the skull has an owner + */ + boolean hasOwner(); + + /** + * Sets the owner of the skull. + *

          + * Plugins should check that hasOwner() returns true before calling this + * plugin. + * + * @param owner the new owner of the skull + * @return true if the owner was successfully set + */ + boolean setOwner(String owner); + + SkullMeta clone(); +} diff --git a/src/main/java/org/bukkit/map/MapCanvas.java b/src/main/java/org/bukkit/map/MapCanvas.java new file mode 100644 index 0000000..d68bb17 --- /dev/null +++ b/src/main/java/org/bukkit/map/MapCanvas.java @@ -0,0 +1,84 @@ +package org.bukkit.map; + +import java.awt.Image; + +/** + * Represents a canvas for drawing to a map. Each canvas is associated with a + * specific {@link MapRenderer} and represents that renderer's layer on the + * map. + */ +public interface MapCanvas { + + /** + * Get the map this canvas is attached to. + * + * @return The MapView this canvas is attached to. + */ + public MapView getMapView(); + + /** + * Get the cursor collection associated with this canvas. + * + * @return The MapCursorCollection associated with this canvas. + */ + public MapCursorCollection getCursors(); + + /** + * Set the cursor collection associated with this canvas. This does not + * usually need to be called since a MapCursorCollection is already + * provided. + * + * @param cursors The MapCursorCollection to associate with this canvas. + */ + public void setCursors(MapCursorCollection cursors); + + /** + * Draw a pixel to the canvas. + * + * @param x The x coordinate, from 0 to 127. + * @param y The y coordinate, from 0 to 127. + * @param color The color. See {@link MapPalette}. + */ + public void setPixel(int x, int y, byte color); + + /** + * Get a pixel from the canvas. + * + * @param x The x coordinate, from 0 to 127. + * @param y The y coordinate, from 0 to 127. + * @return The color. See {@link MapPalette}. + */ + public byte getPixel(int x, int y); + + /** + * Get a pixel from the layers below this canvas. + * + * @param x The x coordinate, from 0 to 127. + * @param y The y coordinate, from 0 to 127. + * @return The color. See {@link MapPalette}. + */ + public byte getBasePixel(int x, int y); + + /** + * Draw an image to the map. The image will be clipped if necessary. + * + * @param x The x coordinate of the image. + * @param y The y coordinate of the image. + * @param image The Image to draw. + */ + public void drawImage(int x, int y, Image image); + + /** + * Render text to the map using fancy formatting. Newline (\n) characters + * will move down one line and return to the original column, and the text + * color can be changed using sequences such as "§12;", replacing 12 with + * the palette index of the color (see {@link MapPalette}). + * + * @param x The column to start rendering on. + * @param y The row to start rendering on. + * @param font The font to use. + * @param text The formatted text to render. + */ + public void drawText(int x, int y, MapFont font, String text); + +} diff --git a/src/main/java/org/bukkit/map/MapCursor.java b/src/main/java/org/bukkit/map/MapCursor.java new file mode 100644 index 0000000..d3698a6 --- /dev/null +++ b/src/main/java/org/bukkit/map/MapCursor.java @@ -0,0 +1,189 @@ +package org.bukkit.map; + +/** + * Represents a cursor on a map. + */ +public final class MapCursor { + private byte x, y; + private byte direction, type; + private boolean visible; + + /** + * Initialize the map cursor. + * + * @param x The x coordinate, from -128 to 127. + * @param y The y coordinate, from -128 to 127. + * @param direction The facing of the cursor, from 0 to 15. + * @param type The type (color/style) of the map cursor. + * @param visible Whether the cursor is visible by default. + * @deprecated Magic value + */ + @Deprecated + public MapCursor(byte x, byte y, byte direction, byte type, boolean visible) { + this.x = x; + this.y = y; + setDirection(direction); + setRawType(type); + this.visible = visible; + } + + /** + * Get the X position of this cursor. + * + * @return The X coordinate. + */ + public byte getX() { + return x; + } + + /** + * Get the Y position of this cursor. + * + * @return The Y coordinate. + */ + public byte getY() { + return y; + } + + /** + * Get the direction of this cursor. + * + * @return The facing of the cursor, from 0 to 15. + */ + public byte getDirection() { + return direction; + } + + /** + * Get the type of this cursor. + * + * @return The type (color/style) of the map cursor. + */ + public Type getType() { + return Type.byValue(type); + } + + /** + * Get the type of this cursor. + * + * @return The type (color/style) of the map cursor. + * @deprecated Magic value + */ + @Deprecated + public byte getRawType() { + return type; + } + + /** + * Get the visibility status of this cursor. + * + * @return True if visible, false otherwise. + */ + public boolean isVisible() { + return visible; + } + + /** + * Set the X position of this cursor. + * + * @param x The X coordinate. + */ + public void setX(byte x) { + this.x = x; + } + + /** + * Set the Y position of this cursor. + * + * @param y The Y coordinate. + */ + public void setY(byte y) { + this.y = y; + } + + /** + * Set the direction of this cursor. + * + * @param direction The facing of the cursor, from 0 to 15. + */ + public void setDirection(byte direction) { + if (direction < 0 || direction > 15) { + throw new IllegalArgumentException("Direction must be in the range 0-15"); + } + this.direction = direction; + } + + /** + * Set the type of this cursor. + * + * @param type The type (color/style) of the map cursor. + */ + public void setType(Type type) { + setRawType(type.value); + } + + /** + * Set the type of this cursor. + * + * @param type The type (color/style) of the map cursor. + * @deprecated Magic value + */ + @Deprecated + public void setRawType(byte type) { + if (type < 0 || type > 15) { + throw new IllegalArgumentException("Type must be in the range 0-15"); + } + this.type = type; + } + + /** + * Set the visibility status of this cursor. + * + * @param visible True if visible. + */ + public void setVisible(boolean visible) { + this.visible = visible; + } + + /** + * Represents the standard types of map cursors. More may be made + * available by texture packs - the value is used by the client as an + * index in the file './misc/mapicons.png' from minecraft.jar or from a + * texture pack. + */ + public enum Type { + WHITE_POINTER(0), + GREEN_POINTER(1), + RED_POINTER(2), + BLUE_POINTER(3), + WHITE_CROSS(4); + + private byte value; + + private Type(int value) { + this.value = (byte) value; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public byte getValue() { + return value; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public static Type byValue(byte value) { + for (Type t : values()) { + if (t.value == value) return t; + } + return null; + } + } + +} diff --git a/src/main/java/org/bukkit/map/MapCursorCollection.java b/src/main/java/org/bukkit/map/MapCursorCollection.java new file mode 100644 index 0000000..1dc9025 --- /dev/null +++ b/src/main/java/org/bukkit/map/MapCursorCollection.java @@ -0,0 +1,96 @@ +package org.bukkit.map; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents all the map cursors on a {@link MapCanvas}. Like MapCanvas, a + * MapCursorCollection is linked to a specific {@link MapRenderer}. + */ +public final class MapCursorCollection { + private List cursors = new ArrayList(); + + /** + * Get the amount of cursors in this collection. + * + * @return The size of this collection. + */ + public int size() { + return cursors.size(); + } + + /** + * Get a cursor from this collection. + * + * @param index The index of the cursor. + * @return The MapCursor. + */ + public MapCursor getCursor(int index) { + return cursors.get(index); + } + + /** + * Remove a cursor from the collection. + * + * @param cursor The MapCursor to remove. + * @return Whether the cursor was removed successfully. + */ + public boolean removeCursor(MapCursor cursor) { + return cursors.remove(cursor); + } + + /** + * Add a cursor to the collection. + * + * @param cursor The MapCursor to add. + * @return The MapCursor that was passed. + */ + public MapCursor addCursor(MapCursor cursor) { + cursors.add(cursor); + return cursor; + } + + /** + * Add a cursor to the collection. + * + * @param x The x coordinate, from -128 to 127. + * @param y The y coordinate, from -128 to 127. + * @param direction The facing of the cursor, from 0 to 15. + * @return The newly added MapCursor. + */ + public MapCursor addCursor(int x, int y, byte direction) { + return addCursor(x, y, direction, (byte) 0, true); + } + + /** + * Add a cursor to the collection. + * + * @param x The x coordinate, from -128 to 127. + * @param y The y coordinate, from -128 to 127. + * @param direction The facing of the cursor, from 0 to 15. + * @param type The type (color/style) of the map cursor. + * @return The newly added MapCursor. + * @deprecated Magic value + */ + @Deprecated + public MapCursor addCursor(int x, int y, byte direction, byte type) { + return addCursor(x, y, direction, type, true); + } + + /** + * Add a cursor to the collection. + * + * @param x The x coordinate, from -128 to 127. + * @param y The y coordinate, from -128 to 127. + * @param direction The facing of the cursor, from 0 to 15. + * @param type The type (color/style) of the map cursor. + * @param visible Whether the cursor is visible. + * @return The newly added MapCursor. + * @deprecated Magic value + */ + @Deprecated + public MapCursor addCursor(int x, int y, byte direction, byte type, boolean visible) { + return addCursor(new MapCursor((byte) x, (byte) y, direction, type, visible)); + } + +} diff --git a/src/main/java/org/bukkit/map/MapFont.java b/src/main/java/org/bukkit/map/MapFont.java new file mode 100644 index 0000000..ea8f0ea --- /dev/null +++ b/src/main/java/org/bukkit/map/MapFont.java @@ -0,0 +1,144 @@ +package org.bukkit.map; + +import java.util.HashMap; + +/** + * Represents a bitmap font drawable to a map. + */ +public class MapFont { + + private final HashMap chars = new HashMap(); + private int height = 0; + protected boolean malleable = true; + + /** + * Set the sprite for a given character. + * + * @param ch The character to set the sprite for. + * @param sprite The CharacterSprite to set. + * @throws IllegalStateException if this font is static. + */ + public void setChar(char ch, CharacterSprite sprite) { + if (!malleable) { + throw new IllegalStateException("this font is not malleable"); + } + + chars.put(ch, sprite); + if (sprite.getHeight() > height) { + height = sprite.getHeight(); + } + } + + /** + * Get the sprite for a given character. + * + * @param ch The character to get the sprite for. + * @return The CharacterSprite associated with the character, or null if + * there is none. + */ + public CharacterSprite getChar(char ch) { + return chars.get(ch); + } + + /** + * Get the width of the given text as it would be rendered using this + * font. + * + * @param text The text. + * @return The width in pixels. + */ + public int getWidth(String text) { + if (!isValid(text)) { + throw new IllegalArgumentException("text contains invalid characters"); + } + + if (text.length() == 0){ + return 0; + } + + int result = 0; + for (int i = 0; i < text.length(); ++i) { + result += chars.get(text.charAt(i)).getWidth(); + } + result += text.length() - 1; // Account for 1px spacing between characters + + return result; + } + + /** + * Get the height of this font. + * + * @return The height of the font. + */ + public int getHeight() { + return height; + } + + /** + * Check whether the given text is valid. + * + * @param text The text. + * @return True if the string contains only defined characters, false + * otherwise. + */ + public boolean isValid(String text) { + for (int i = 0; i < text.length(); ++i) { + char ch = text.charAt(i); + if (ch == '\u00A7' || ch == '\n') continue; + if (chars.get(ch) == null) return false; + } + return true; + } + + /** + * Represents the graphics for a single character in a MapFont. + */ + public static class CharacterSprite { + + private final int width; + private final int height; + private final boolean[] data; + + public CharacterSprite(int width, int height, boolean[] data) { + this.width = width; + this.height = height; + this.data = data; + + if (data.length != width * height) { + throw new IllegalArgumentException("size of data does not match dimensions"); + } + } + + /** + * Get the value of a pixel of the character. + * + * @param row The row, in the range [0,8). + * @param col The column, in the range [0,8). + * @return True if the pixel is solid, false if transparent. + */ + public boolean get(int row, int col) { + if (row < 0 || col < 0 || row >= height || col >= width) return false; + return data[row * width + col]; + } + + /** + * Get the width of the character sprite. + * + * @return The width of the character. + */ + public int getWidth() { + return width; + } + + /** + * Get the height of the character sprite. + * + * @return The height of the character. + */ + public int getHeight() { + return height; + } + + } + +} diff --git a/src/main/java/org/bukkit/map/MapPalette.java b/src/main/java/org/bukkit/map/MapPalette.java new file mode 100644 index 0000000..35f3e19 --- /dev/null +++ b/src/main/java/org/bukkit/map/MapPalette.java @@ -0,0 +1,241 @@ +package org.bukkit.map; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.image.BufferedImage; + +/** + * Represents the palette that map items use. + *

          + * These fields are hee base color ranges. Each entry corresponds to four + * colors of varying shades with values entry to entry + 3. + */ +public final class MapPalette { + // Internal mechanisms + private MapPalette() {} + + private static Color c(int r, int g, int b) { + return new Color(r, g, b); + } + + private static double getDistance(Color c1, Color c2) { + double rmean = (c1.getRed() + c2.getRed()) / 2.0; + double r = c1.getRed() - c2.getRed(); + double g = c1.getGreen() - c2.getGreen(); + int b = c1.getBlue() - c2.getBlue(); + double weightR = 2 + rmean / 256.0; + double weightG = 4.0; + double weightB = 2 + (255 - rmean) / 256.0; + return weightR * r * r + weightG * g * g + weightB * b * b; + } + + private static final Color[] colors = { + new Color(0, 0, 0, 0), new Color(0, 0, 0, 0), + new Color(0, 0, 0, 0), new Color(0, 0, 0, 0), + c(89, 125, 39), c(109, 153, 48), c(127, 178, 56), c(67, 94, 29), + c(174, 164, 115), c(213, 201, 140), c(247, 233, 163), c(130, 123, 86), + c(117, 117, 117), c(144, 144, 144), c(167, 167, 167), c(88, 88, 88), + c(180, 0, 0), c(220, 0, 0), c(255, 0, 0), c(135, 0, 0), + c(112, 112, 180), c(138, 138, 220), c(160, 160, 255), c(84, 84, 135), + c(117, 117, 117), c(144, 144, 144), c(167, 167, 167), c(88, 88, 88), + c(0, 87, 0), c(0, 106, 0), c(0, 124, 0), c(0, 65, 0), + c(180, 180, 180), c(220, 220, 220), c(255, 255, 255), c(135, 135, 135), + c(115, 118, 129), c(141, 144, 158), c(164, 168, 184), c(86, 88, 97), + c(129, 74, 33), c(157, 91, 40), c(183, 106, 47), c(96, 56, 24), + c(79, 79, 79), c(96, 96, 96), c(112, 112, 112), c(59, 59, 59), + c(45, 45, 180), c(55, 55, 220), c(64, 64, 255), c(33, 33, 135), + c(73, 58, 35), c(89, 71, 43), c(104, 83, 50), c(55, 43, 26), + c(180, 177, 172), c(220, 217, 211), c(255, 252, 245), c(135, 133, 129), + c(152, 89, 36), c(186, 109, 44), c(216, 127, 51), c(114, 67, 27), + c(125, 53, 152), c(153, 65, 186), c(178, 76, 216), c(94, 40, 114), + c(72, 108, 152), c(88, 132, 186), c(102, 153, 216), c(54, 81, 114), + c(161, 161, 36), c(197, 197, 44), c(229, 229, 51), c(121, 121, 27), + c(89, 144, 17), c(109, 176, 21), c(127, 204, 25), c(67, 108, 13), + c(170, 89, 116), c(208, 109, 142), c(242, 127, 165), c(128, 67, 87), + c(53, 53, 53), c(65, 65, 65), c(76, 76, 76), c(40, 40, 40), + c(108, 108, 108), c(132, 132, 132), c(153, 153, 153), c(81, 81, 81), + c(53, 89, 108), c(65, 109, 132), c(76, 127, 153), c(40, 67, 81), + c(89, 44, 125), c(109, 54, 153), c(127, 63, 178), c(67, 33, 94), + c(36, 53, 125), c(44, 65, 153), c(51, 76, 178), c(27, 40, 94), + c(72, 53, 36), c(88, 65, 44), c(102, 76, 51), c(54, 40, 27), + c(72, 89, 36), c(88, 109, 44), c(102, 127, 51), c(54, 67, 27), + c(108, 36, 36), c(132, 44, 44), c(153, 51, 51), c(81, 27, 27), + c(17, 17, 17), c(21, 21, 21), c(25, 25, 25), c(13, 13, 13), + c(176, 168, 54), c(215, 205, 66), c(250, 238, 77), c(132, 126, 40), + c(64, 154, 150), c(79, 188, 183), c(92, 219, 213), c(48, 115, 112), + c(52, 90, 180), c(63, 110, 220), c(74, 128, 255), c(39, 67, 135), + c(0, 153, 40), c(0, 187, 50), c(0, 217, 58), c(0, 114, 30), + c(14, 14, 21), c(18, 17, 26), c(21, 20, 31), c(11, 10, 16), + c(79, 1, 0), c(96, 1, 0), c(112, 2, 0), c(59, 1, 0) + }; + + // Interface + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte TRANSPARENT = 0; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte LIGHT_GREEN = 4; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte LIGHT_BROWN = 8; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte GRAY_1 = 12; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte RED = 16; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte PALE_BLUE = 20; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte GRAY_2 = 24; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte DARK_GREEN = 28; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte WHITE = 32; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte LIGHT_GRAY = 36; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte BROWN = 40; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte DARK_GRAY = 44; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte BLUE = 48; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte DARK_BROWN = 52; + + /** + * Resize an image to 128x128. + * + * @param image The image to resize. + * @return The resized image. + */ + public static BufferedImage resizeImage(Image image) { + BufferedImage result = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = result.createGraphics(); + graphics.drawImage(image, 0, 0, 128, 128, null); + graphics.dispose(); + return result; + } + + /** + * Convert an Image to a byte[] using the palette. + * + * @param image The image to convert. + * @return A byte[] containing the pixels of the image. + * @deprecated Magic value + */ + @Deprecated + public static byte[] imageToBytes(Image image) { + BufferedImage temp = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = temp.createGraphics(); + graphics.drawImage(image, 0, 0, null); + graphics.dispose(); + + int[] pixels = new int[temp.getWidth() * temp.getHeight()]; + temp.getRGB(0, 0, temp.getWidth(), temp.getHeight(), pixels, 0, temp.getWidth()); + + byte[] result = new byte[temp.getWidth() * temp.getHeight()]; + for (int i = 0; i < pixels.length; i++) { + result[i] = matchColor(new Color(pixels[i], true)); + } + return result; + } + + /** + * Get the index of the closest matching color in the palette to the given + * color. + * + * @param r The red component of the color. + * @param b The blue component of the color. + * @param g The green component of the color. + * @return The index in the palette. + * @deprecated Magic value + */ + @Deprecated + public static byte matchColor(int r, int g, int b) { + return matchColor(new Color(r, g, b)); + } + + /** + * Get the index of the closest matching color in the palette to the given + * color. + * + * @param color The Color to match. + * @return The index in the palette. + * @deprecated Magic value + */ + @Deprecated + public static byte matchColor(Color color) { + if (color.getAlpha() < 128) return 0; + + int index = 0; + double best = -1; + + for (int i = 4; i < colors.length; i++) { + double distance = getDistance(color, colors[i]); + if (distance < best || best == -1) { + best = distance; + index = i; + } + } + + // Minecraft has 143 colors, some of which have negative byte representations + return (byte) (index < 128 ? index : -129 + (index - 127)); + } + + /** + * Get the value of the given color in the palette. + * + * @param index The index in the palette. + * @return The Color of the palette entry. + * @deprecated Magic value + */ + @Deprecated + public static Color getColor(byte index) { + if ((index > -113 && index < 0) || index > 127) { + throw new IndexOutOfBoundsException(); + } else { + // Minecraft has 143 colors, some of which have negative byte representations + return colors[index >= 0 ? index : index + 256]; + } + } +} diff --git a/src/main/java/org/bukkit/map/MapRenderer.java b/src/main/java/org/bukkit/map/MapRenderer.java new file mode 100644 index 0000000..322d0ce --- /dev/null +++ b/src/main/java/org/bukkit/map/MapRenderer.java @@ -0,0 +1,56 @@ +package org.bukkit.map; + +import org.bukkit.entity.Player; + +/** + * Represents a renderer for a map. + */ +public abstract class MapRenderer { + + private boolean contextual; + + /** + * Initialize the map renderer base to be non-contextual. See {@link + * #isContextual()}. + */ + public MapRenderer() { + this(false); + } + + /** + * Initialize the map renderer base with the given contextual status. + * + * @param contextual Whether the renderer is contextual. See {@link + * #isContextual()}. + */ + public MapRenderer(boolean contextual) { + this.contextual = contextual; + } + + /** + * Get whether the renderer is contextual, i.e. has different canvases for + * different players. + * + * @return True if contextual, false otherwise. + */ + final public boolean isContextual() { + return contextual; + } + + /** + * Initialize this MapRenderer for the given map. + * + * @param map The MapView being initialized. + */ + public void initialize(MapView map) {} + + /** + * Render to the given map. + * + * @param map The MapView being rendered to. + * @param canvas The canvas to use for rendering. + * @param player The player who triggered the rendering. + */ + abstract public void render(MapView map, MapCanvas canvas, Player player); + +} diff --git a/src/main/java/org/bukkit/map/MapView.java b/src/main/java/org/bukkit/map/MapView.java new file mode 100644 index 0000000..ff370f4 --- /dev/null +++ b/src/main/java/org/bukkit/map/MapView.java @@ -0,0 +1,157 @@ +package org.bukkit.map; + +import java.util.List; +import org.bukkit.World; + +/** + * Represents a map item. + */ +public interface MapView { + + /** + * An enum representing all possible scales a map can be set to. + */ + public static enum Scale { + CLOSEST(0), + CLOSE(1), + NORMAL(2), + FAR(3), + FARTHEST(4); + + private byte value; + + private Scale(int value) { + this.value = (byte) value; + } + + /** + * Get the scale given the raw value. + * + * @param value The raw scale + * @return The enum scale, or null for an invalid input + * @deprecated Magic value + */ + @Deprecated + public static Scale valueOf(byte value) { + switch (value) { + case 0: return CLOSEST; + case 1: return CLOSE; + case 2: return NORMAL; + case 3: return FAR; + case 4: return FARTHEST; + default: return null; + } + } + + /** + * Get the raw value of this scale level. + * + * @return The scale value + * @deprecated Magic value + */ + @Deprecated + public byte getValue() { + return value; + } + } + + /** + * Get the ID of this map item. Corresponds to the damage value of a map + * in an inventory. + * + * @return The ID of the map. + * @deprecated Magic value + */ + @Deprecated + public short getId(); + + /** + * Check whether this map is virtual. A map is virtual if its lowermost + * MapRenderer is plugin-provided. + * + * @return Whether the map is virtual. + */ + public boolean isVirtual(); + + /** + * Get the scale of this map. + * + * @return The scale of the map. + */ + public Scale getScale(); + + /** + * Set the scale of this map. + * + * @param scale The scale to set. + */ + public void setScale(Scale scale); + + /** + * Get the center X position of this map. + * + * @return The center X position. + */ + public int getCenterX(); + + /** + * Get the center Z position of this map. + * + * @return The center Z position. + */ + public int getCenterZ(); + + /** + * Set the center X position of this map. + * + * @param x The center X position. + */ + public void setCenterX(int x); + + /** + * Set the center Z position of this map. + * + * @param z The center Z position. + */ + public void setCenterZ(int z); + + /** + * Get the world that this map is associated with. Primarily used by the + * internal renderer, but may be used by external renderers. May return + * null if the world the map is associated with is not loaded. + * + * @return The World this map is associated with. + */ + public World getWorld(); + + /** + * Set the world that this map is associated with. The world is used by + * the internal renderer, and may also be used by external renderers. + * + * @param world The World to associate this map with. + */ + public void setWorld(World world); + + /** + * Get a list of MapRenderers currently in effect. + * + * @return A List containing each map renderer. + */ + public List getRenderers(); + + /** + * Add a renderer to this map. + * + * @param renderer The MapRenderer to add. + */ + public void addRenderer(MapRenderer renderer); + + /** + * Remove a renderer from this map. + * + * @param renderer The MapRenderer to remove. + * @return True if the renderer was successfully removed. + */ + public boolean removeRenderer(MapRenderer renderer); + +} diff --git a/src/main/java/org/bukkit/map/MinecraftFont.java b/src/main/java/org/bukkit/map/MinecraftFont.java new file mode 100644 index 0000000..9ec8d10 --- /dev/null +++ b/src/main/java/org/bukkit/map/MinecraftFont.java @@ -0,0 +1,328 @@ +package org.bukkit.map; + +/** + * Represents the built-in Minecraft font. + */ +public class MinecraftFont extends MapFont { + + private static final int spaceSize = 2; + + private static final String fontChars = + " !\"#$%&'()*+,-./0123456789:;<=>?" + + "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" + + "'abcdefghijklmnopqrstuvwxyz{|}~\u007F" + + "\u00C7\u00FC\u00E9\u00E2\u00E4\u00E0\u00E5\u00E7" + // Çüéâäàåç + "\u00EA\u00EB\u00E8\u00EF\u00EE\u00EC\u00C4\u00C5" + // êëèïîìÄÅ + "\u00C9\u00E6\u00C6\u00F4\u00F6\u00F2\u00FB\u00F9" + // ÉæÆôöòûù + "\u00FF\u00D6\u00DC\u00F8\u00A3\u00D8\u00D7\u0191" + // ÿÖÜø£Ø×ƒ + "\u00E1\u00ED\u00F3\u00FA\u00F1\u00D1\u00AA\u00BA" + // áíóúñѪº + "\u00BF\u00AE\u00AC\u00BD\u00BC\u00A1\u00AB\u00BB"; // ¿®¬½¼¡«» + + private static final int[][] fontData = new int[][] { + /* null */ {0,0,0,0,0,0,0,0}, + /* 1 */ {126,129,165,129,189,153,129,126}, + /* 2 */ {126,255,219,255,195,231,255,126}, + /* 3 */ {54,127,127,127,62,28,8,0}, + /* 4 */ {8,28,62,127,62,28,8,0}, + /* 5 */ {28,62,28,127,127,62,28,62}, + /* 6 */ {8,8,28,62,127,62,28,62}, + /* 7 */ {0,0,24,60,60,24,0,0}, + /* 8 */ {255,255,231,195,195,231,255,255}, + /* 9 */ {0,60,102,66,66,102,60,0}, + /* 10 */ {255,195,153,189,189,153,195,255}, + /* 11 */ {240,224,240,190,51,51,51,30}, + /* 12 */ {60,102,102,102,60,24,126,24}, + /* 13 */ {252,204,252,12,12,14,15,7}, + /* 14 */ {254,198,254,198,198,230,103,3}, + /* 15 */ {153,90,60,231,231,60,90,153}, + /* 16 */ {1,7,31,127,31,7,1,0}, + /* 17 */ {64,112,124,127,124,112,64,0}, + /* 18 */ {24,60,126,24,24,126,60,24}, + /* 19 */ {102,102,102,102,102,0,102,0}, + /* 20 */ {254,219,219,222,216,216,216,0}, + /* 21 */ {124,198,28,54,54,28,51,30}, + /* 22 */ {0,0,0,0,126,126,126,0}, + /* 23 */ {24,60,126,24,126,60,24,255}, + /* 24 */ {24,60,126,24,24,24,24,0}, + /* 25 */ {24,24,24,24,126,60,24,0}, + /* 26 */ {0,24,48,127,48,24,0,0}, + /* 27 */ {0,12,6,127,6,12,0,0}, + /* 28 */ {0,0,3,3,3,127,0,0}, + /* 29 */ {0,36,102,255,102,36,0,0}, + /* 30 */ {0,24,60,126,255,255,0,0}, + /* 31 */ {0,255,255,126,60,24,0,0}, + /* */ {0,0,0,0,0,0,0,0}, + /* ! */ {1,1,1,1,1,0,1,0}, + /* " */ {10,10,5,0,0,0,0,0}, + /* # */ {10,10,31,10,31,10,10,0}, + /* $ */ {4,30,1,14,16,15,4,0}, + /* % */ {17,9,8,4,2,18,17,0}, + /* & */ {4,10,4,22,13,9,22,0}, + /* ' */ {2,2,1,0,0,0,0,0}, + /* ( */ {12,2,1,1,1,2,12,0}, + /* ) */ {3,4,8,8,8,4,3,0}, + /* * */ {0,0,9,6,9,0,0,0}, + /* + */ {0,4,4,31,4,4,0,0}, + /* , */ {0,0,0,0,0,1,1,1}, + /* - */ {0,0,0,31,0,0,0,0}, + /* . */ {0,0,0,0,0,1,1,0}, + /* / */ {16,8,8,4,2,2,1,0}, + /* 0 */ {14,17,25,21,19,17,14,0}, + /* 1 */ {4,6,4,4,4,4,31,0}, + /* 2 */ {14,17,16,12,2,17,31,0}, + /* 3 */ {14,17,16,12,16,17,14,0}, + /* 4 */ {24,20,18,17,31,16,16,0}, + /* 5 */ {31,1,15,16,16,17,14,0}, + /* 6 */ {12,2,1,15,17,17,14,0}, + /* 7 */ {31,17,16,8,4,4,4,0}, + /* 8 */ {14,17,17,14,17,17,14,0}, + /* 9 */ {14,17,17,30,16,8,6,0}, + /* : */ {0,1,1,0,0,1,1,0}, + /* ; */ {0,1,1,0,0,1,1,1}, + /* < */ {8,4,2,1,2,4,8,0}, + /* = */ {0,0,31,0,0,31,0,0}, + /* > */ {1,2,4,8,4,2,1,0}, + /* ? */ {14,17,16,8,4,0,4,0}, + /* @ */ {30,33,45,45,61,1,30,0}, + /* A */ {14,17,31,17,17,17,17,0}, + /* B */ {15,17,15,17,17,17,15,0}, + /* C */ {14,17,1,1,1,17,14,0}, + /* D */ {15,17,17,17,17,17,15,0}, + /* E */ {31,1,7,1,1,1,31,0}, + /* F */ {31,1,7,1,1,1,1,0}, + /* G */ {30,1,25,17,17,17,14,0}, + /* H */ {17,17,31,17,17,17,17,0}, + /* I */ {7,2,2,2,2,2,7,0}, + /* J */ {16,16,16,16,16,17,14,0}, + /* K */ {17,9,7,9,17,17,17,0}, + /* L */ {1,1,1,1,1,1,31,0}, + /* M */ {17,27,21,17,17,17,17,0}, + /* N */ {17,19,21,25,17,17,17,0}, + /* O */ {14,17,17,17,17,17,14,0}, + /* P */ {15,17,15,1,1,1,1,0}, + /* Q */ {14,17,17,17,17,9,22,0}, + /* R */ {15,17,15,17,17,17,17,0}, + /* S */ {30,1,14,16,16,17,14,0}, + /* T */ {31,4,4,4,4,4,4,0}, + /* U */ {17,17,17,17,17,17,14,0}, + /* V */ {17,17,17,17,10,10,4,0}, + /* W */ {17,17,17,17,21,27,17,0}, + /* X */ {17,10,4,10,17,17,17,0}, + /* Y */ {17,10,4,4,4,4,4,0}, + /* Z */ {31,16,8,4,2,1,31,0}, + /* [ */ {7,1,1,1,1,1,7,0}, + /* \ */ {1,2,2,4,8,8,16,0}, + /* ] */ {7,4,4,4,4,4,7,0}, + /* ^ */ {4,10,17,0,0,0,0,0}, + /* _ */ {0,0,0,0,0,0,0,31}, + /* ` */ {1,1,2,0,0,0,0,0}, + /* a */ {0,0,14,16,30,17,30,0}, + /* b */ {1,1,13,19,17,17,15,0}, + /* c */ {0,0,14,17,1,17,14,0}, + /* d */ {16,16,22,25,17,17,30,0}, + /* e */ {0,0,14,17,31,1,30,0}, + /* f */ {12,2,15,2,2,2,2,0}, + /* g */ {0,0,30,17,17,30,16,15}, + /* h */ {1,1,13,19,17,17,17,0}, + /* i */ {1,0,1,1,1,1,1,0}, + /* j */ {16,0,16,16,16,17,17,14}, + /* k */ {1,1,9,5,3,5,9,0}, + /* l */ {1,1,1,1,1,1,2,0}, + /* m */ {0,0,11,21,21,17,17,0}, + /* n */ {0,0,15,17,17,17,17,0}, + /* o */ {0,0,14,17,17,17,14,0}, + /* p */ {0,0,13,19,17,15,1,1}, + /* q */ {0,0,22,25,17,30,16,16}, + /* r */ {0,0,13,19,1,1,1,0}, + /* s */ {0,0,30,1,14,16,15,0}, + /* t */ {2,2,7,2,2,2,4,0}, + /* u */ {0,0,17,17,17,17,30,0}, + /* v */ {0,0,17,17,17,10,4,0}, + /* w */ {0,0,17,17,21,21,30,0}, + /* x */ {0,0,17,10,4,10,17,0}, + /* y */ {0,0,17,17,17,30,16,15}, + /* z */ {0,0,31,8,4,2,31,0}, + /* { */ {12,2,2,1,2,2,12,0}, + /* | */ {1,1,1,0,1,1,1,0}, + /* } */ {3,4,4,8,4,4,3,0}, + /* ~ */ {38,25,0,0,0,0,0,0}, + /* ⌂ */ {0,0,4,10,17,17,31,0}, + /* Ç */ {14,17,1,1,17,14,16,12}, + /* ü */ {10,0,17,17,17,17,30,0}, + /* é */ {24,0,14,17,31,1,30,0}, + /* â */ {14,17,14,16,30,17,30,0}, + /* ä */ {10,0,14,16,30,17,30,0}, + /* à */ {3,0,14,16,30,17,30,0}, + /* å */ {4,0,14,16,30,17,30,0}, + /* ç */ {0,14,17,1,17,14,16,12}, + /* ê */ {14,17,14,17,31,1,30,0}, + /* ë */ {10,0,14,17,31,1,30,0}, + /* è */ {3,0,14,17,31,1,30,0}, + /* ï */ {5,0,2,2,2,2,2,0}, + /* î */ {14,17,4,4,4,4,4,0}, + /* ì */ {3,0,2,2,2,2,2,0}, + /* Ä */ {17,14,17,31,17,17,17,0}, + /* Å */ {4,0,14,17,31,17,17,0}, + /* É */ {24,0,31,1,7,1,31,0}, + /* æ */ {0,0,10,20,30,5,30,0}, + /* Æ */ {30,5,15,5,5,5,29,0}, + /* ô */ {14,17,14,17,17,17,14,0}, + /* ö */ {10,0,14,17,17,17,14,0}, + /* ò */ {3,0,14,17,17,17,14,0}, + /* û */ {14,17,0,17,17,17,30,0}, + /* ù */ {3,0,17,17,17,17,30,0}, + /* ÿ */ {10,0,17,17,17,30,16,15}, + /* Ö */ {17,14,17,17,17,17,14,0}, + /* Ü */ {17,0,17,17,17,17,14,0}, + /* ø */ {0,0,14,25,21,19,14,4}, + /* £ */ {12,18,2,15,2,2,31,0}, + /* Ø */ {14,17,25,21,19,17,14,0}, + /* × */ {0,0,5,2,5,0,0,0}, + /* ƒ */ {8,20,4,14,4,4,5,2}, + /* á */ {24,0,14,16,30,17,30,0}, + /* í */ {3,0,1,1,1,1,1,0}, + /* ó */ {24,0,14,17,17,17,14,0}, + /* ú */ {24,0,17,17,17,17,30,0}, + /* ñ */ {31,0,15,17,17,17,17,0}, + /* Ñ */ {31,0,17,19,21,25,17,0}, + /* ª */ {14,16,31,30,0,31,0,0}, + /* º */ {14,17,17,14,0,31,0,0}, + /* ¿ */ {4,0,4,2,1,17,14,0}, + /* ® */ {0,30,45,37,43,30,0,0}, + /* ¬ */ {0,0,0,31,16,16,0,0}, + /* ½ */ {17,9,8,4,18,10,25,0}, + /* ¼ */ {17,9,8,4,26,26,17,0}, + /* ¡ */ {0,1,0,1,1,1,1,0}, + /* « */ {0,20,10,5,10,20,0,0}, + /* » */ {0,5,10,20,10,5,0,0}, + /* 176 */ {68,17,68,17,68,17,68,17}, + /* 177 */ {170,85,170,85,170,85,170,85}, + /* 178 */ {219,238,219,119,219,238,219,119}, + /* 179 */ {24,24,24,24,24,24,24,24}, + /* 180 */ {24,24,24,24,31,24,24,24}, + /* 181 */ {24,24,31,24,31,24,24,24}, + /* 182 */ {108,108,108,108,111,108,108,108}, + /* 183 */ {0,0,0,0,127,108,108,108}, + /* 184 */ {0,0,31,24,31,24,24,24}, + /* 185 */ {108,108,111,96,111,108,108,108}, + /* 186 */ {108,108,108,108,108,108,108,108}, + /* 187 */ {0,0,127,96,111,108,108,108}, + /* 188 */ {108,108,111,96,127,0,0,0}, + /* 189 */ {108,108,108,108,127,0,0,0}, + /* 190 */ {24,24,31,24,31,0,0,0}, + /* 191 */ {0,0,0,0,31,24,24,24}, + /* 192 */ {24,24,24,24,248,0,0,0}, + /* 193 */ {24,24,24,24,255,0,0,0}, + /* 194 */ {0,0,0,0,255,24,24,24}, + /* 195 */ {24,24,24,24,248,24,24,24}, + /* 196 */ {0,0,0,0,255,0,0,0}, + /* 197 */ {24,24,24,24,255,24,24,24}, + /* 198 */ {24,24,248,24,248,24,24,24}, + /* 199 */ {108,108,108,108,236,108,108,108}, + /* 200 */ {108,108,236,12,252,0,0,0}, + /* 201 */ {0,0,252,12,236,108,108,108}, + /* 202 */ {108,108,239,0,255,0,0,0}, + /* 203 */ {0,0,255,0,239,108,108,108}, + /* 204 */ {108,108,236,12,236,108,108,108}, + /* 205 */ {0,0,255,0,255,0,0,0}, + /* 206 */ {108,108,239,0,239,108,108,108}, + /* 207 */ {24,24,255,0,255,0,0,0}, + /* 208 */ {108,108,108,108,255,0,0,0}, + /* 209 */ {0,0,255,0,255,24,24,24}, + /* 210 */ {0,0,0,0,255,108,108,108}, + /* 211 */ {108,108,108,108,252,0,0,0}, + /* 212 */ {24,24,248,24,248,0,0,0}, + /* 213 */ {0,0,248,24,248,24,24,24}, + /* 214 */ {0,0,0,0,252,108,108,108}, + /* 215 */ {108,108,108,108,255,108,108,108}, + /* 216 */ {24,24,255,24,255,24,24,24}, + /* 217 */ {24,24,24,24,31,0,0,0}, + /* 218 */ {0,0,0,0,248,24,24,24}, + /* 219 */ {255,255,255,255,255,255,255,255}, + /* 220 */ {0,0,0,0,255,255,255,255}, + /* 221 */ {15,15,15,15,15,15,15,15}, + /* 222 */ {240,240,240,240,240,240,240,240}, + /* 223 */ {255,255,255,255,0,0,0,0}, + /* 224 */ {0,0,110,59,19,59,110,0}, + /* 225 */ {0,30,51,31,51,31,3,3}, + /* 226 */ {0,63,51,3,3,3,3,0}, + /* 227 */ {0,127,54,54,54,54,54,0}, + /* 228 */ {63,51,6,12,6,51,63,0}, + /* 229 */ {0,0,126,27,27,27,14,0}, + /* 230 */ {0,102,102,102,102,62,6,3}, + /* 231 */ {0,110,59,24,24,24,24,0}, + /* 232 */ {63,12,30,51,51,30,12,63}, + /* 233 */ {28,54,99,127,99,54,28,0}, + /* 234 */ {28,54,99,99,54,54,119,0}, + /* 235 */ {56,12,24,62,51,51,30,0}, + /* 236 */ {0,0,126,219,219,126,0,0}, + /* 237 */ {96,48,126,219,219,126,6,3}, + /* 238 */ {28,6,3,31,3,6,28,0}, + /* 239 */ {30,51,51,51,51,51,51,0}, + /* 240 */ {0,63,0,63,0,63,0,0}, + /* 241 */ {12,12,63,12,12,0,63,0}, + /* 242 */ {6,12,24,12,6,0,63,0}, + /* 243 */ {24,12,6,12,24,0,63,0}, + /* 244 */ {112,216,216,24,24,24,24,24}, + /* 245 */ {24,24,24,24,24,27,27,14}, + /* 246 */ {12,12,0,63,0,12,12,0}, + /* 247 */ {0,110,59,0,110,59,0,0}, + /* 248 */ {28,54,54,28,0,0,0,0}, + /* 249 */ {0,0,0,24,24,0,0,0}, + /* 250 */ {0,0,0,0,24,0,0,0}, + /* 251 */ {240,48,48,48,55,54,60,56}, + /* 252 */ {30,54,54,54,54,0,0,0}, + /* 253 */ {14,24,12,6,30,0,0,0}, + /* 254 */ {0,0,60,60,60,60,0,0}, + /* 255 */ {0,0,0,0,0,0,0,0}, + }; + + /** + * A static non-malleable MinecraftFont. + */ + public static final MinecraftFont Font = new MinecraftFont(false); + + /** + * Initialize a new MinecraftFont. + */ + public MinecraftFont() { + this(true); + } + + private MinecraftFont(boolean malleable) { + for (int i = 1; i < fontData.length; ++i) { + char ch = (char) i; + if (i >= 32 && i < 32 + fontChars.length()) { + ch = fontChars.charAt(i - 32); + } + + if (ch == ' ') { + setChar(ch, new CharacterSprite(spaceSize, 8, new boolean[spaceSize * 8])); + continue; + } + + int[] rows = fontData[i]; + int width = 0; + for (int r = 0; r < 8; ++r) { + for (int c = 0; c < 8; ++c) { + if ((rows[r] & (1 << c)) != 0 && c > width) { + width = c; + } + } + } + ++width; + + boolean[] data = new boolean[width * 8]; + for (int r = 0; r < 8; ++r) { + for (int c = 0; c < width; ++c) { + data[r * width + c] = (rows[r] & (1 << c)) != 0; + } + } + + setChar(ch, new CharacterSprite(width, 8, data)); + } + + this.malleable = malleable; + } + +} diff --git a/src/main/java/org/bukkit/material/Attachable.java b/src/main/java/org/bukkit/material/Attachable.java new file mode 100644 index 0000000..1d3f107 --- /dev/null +++ b/src/main/java/org/bukkit/material/Attachable.java @@ -0,0 +1,16 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; + +/** + * Indicates that a block can be attached to another block + */ +public interface Attachable extends Directional { + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace(); +} diff --git a/src/main/java/org/bukkit/material/Bed.java b/src/main/java/org/bukkit/material/Bed.java new file mode 100644 index 0000000..a1c087a --- /dev/null +++ b/src/main/java/org/bukkit/material/Bed.java @@ -0,0 +1,142 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a bed. + */ +public class Bed extends MaterialData implements Directional { + + /** + * Default constructor for a bed. + */ + public Bed() { + super(Material.BED_BLOCK); + } + + /** + * Instantiate a bed facing in a particular direction. + * + * @param direction the direction the bed's head is facing + */ + public Bed(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Bed(final int type) { + super(type); + } + + public Bed(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Bed(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Bed(final Material type, final byte data) { + super(type, data); + } + + /** + * Determine if this block represents the head of the bed + * + * @return true if this is the head of the bed, false if it is the foot + */ + public boolean isHeadOfBed() { + return (getData() & 0x8) == 0x8; + } + + /** + * Configure this to be either the head or the foot of the bed + * + * @param isHeadOfBed True to make it the head. + */ + public void setHeadOfBed(boolean isHeadOfBed) { + setData((byte) (isHeadOfBed ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * Set which direction the head of the bed is facing. Note that this will + * only affect one of the two blocks the bed is made of. + */ + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case SOUTH: + data = 0x0; + break; + + case WEST: + data = 0x1; + break; + + case NORTH: + data = 0x2; + break; + + case EAST: + default: + data = 0x3; + } + + if (isHeadOfBed()) { + data |= 0x8; + } + + setData(data); + } + + /** + * Get the direction that this bed's head is facing toward + * + * @return the direction the head of the bed is facing + */ + public BlockFace getFacing() { + byte data = (byte) (getData() & 0x7); + + switch (data) { + case 0x0: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.NORTH; + + case 0x3: + default: + return BlockFace.EAST; + } + } + + @Override + public String toString() { + return (isHeadOfBed() ? "HEAD" : "FOOT") + " of " + super.toString() + " facing " + getFacing(); + } + + @Override + public Bed clone() { + return (Bed) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Button.java b/src/main/java/org/bukkit/material/Button.java new file mode 100644 index 0000000..2eeeaa6 --- /dev/null +++ b/src/main/java/org/bukkit/material/Button.java @@ -0,0 +1,126 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; +import org.bukkit.Material; + +/** + * Represents a button + */ +public class Button extends SimpleAttachableMaterialData implements Redstone { + public Button() { + super(Material.STONE_BUTTON); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Button(final int type) { + super(type); + } + + public Button(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Button(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Button(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return (getData() & 0x8) == 0x8; + } + + /** + * Sets the current state of this button + * + * @param bool + * whether or not the button is powered + */ + public void setPowered(boolean bool) { + setData((byte) (bool ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + byte data = (byte) (getData() & 0x7); + + switch (data) { + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.SOUTH; + } + + return null; + } + + /** + * Sets the direction this button is pointing toward + */ + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x8); + + switch (face) { + case EAST: + data |= 0x1; + break; + + case WEST: + data |= 0x2; + break; + + case SOUTH: + data |= 0x3; + break; + + case NORTH: + data |= 0x4; + break; + } + + setData(data); + } + + @Override + public String toString() { + return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public Button clone() { + return (Button) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Cake.java b/src/main/java/org/bukkit/material/Cake.java new file mode 100644 index 0000000..360ae58 --- /dev/null +++ b/src/main/java/org/bukkit/material/Cake.java @@ -0,0 +1,91 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +public class Cake extends MaterialData { + public Cake() { + super(Material.CAKE_BLOCK); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Cake(int type) { + super(type); + } + + public Cake(Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Cake(int type, byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Cake(Material type, byte data) { + super(type, data); + } + + /** + * Gets the number of slices eaten from this cake + * + * @return The number of slices eaten + */ + public int getSlicesEaten() { + return getData(); + } + + /** + * Gets the number of slices remaining on this cake + * + * @return The number of slices remaining + */ + public int getSlicesRemaining() { + return 6 - getData(); + } + + /** + * Sets the number of slices eaten from this cake + * + * @param n The number of slices eaten + */ + public void setSlicesEaten(int n) { + if (n < 6) { + setData((byte) n); + } // TODO: else destroy the block? Probably not possible though + } + + /** + * Sets the number of slices remaining on this cake + * + * @param n The number of slices remaining + */ + public void setSlicesRemaining(int n) { + if (n > 6) { + n = 6; + } + setData((byte) (6 - n)); + } + + @Override + public String toString() { + return super.toString() + " " + getSlicesEaten() + "/" + getSlicesRemaining() + " slices eaten/remaining"; + } + + @Override + public Cake clone() { + return (Cake) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Cauldron.java b/src/main/java/org/bukkit/material/Cauldron.java new file mode 100644 index 0000000..b464bbd --- /dev/null +++ b/src/main/java/org/bukkit/material/Cauldron.java @@ -0,0 +1,61 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a cauldron + */ +public class Cauldron extends MaterialData { + private static final int CAULDRON_FULL = 3; + private static final int CAULDRON_EMPTY = 0; + + public Cauldron() { + super(Material.CAULDRON); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Cauldron(int type, byte data){ + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Cauldron(byte data) { + super(Material.CAULDRON, data); + } + + /** + * Check if the cauldron is full. + * + * @return True if it is full. + */ + public boolean isFull() { + return getData() >= CAULDRON_FULL; + } + + /** + * Check if the cauldron is empty. + * + * @return True if it is empty. + */ + public boolean isEmpty() { + return getData() <= CAULDRON_EMPTY; + } + + @Override + public String toString() { + return (isEmpty() ? "EMPTY" : (isFull() ? "FULL" : getData() + "/3 FULL")) + " CAULDRON"; + } + + @Override + public Cauldron clone() { + return (Cauldron) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Chest.java b/src/main/java/org/bukkit/material/Chest.java new file mode 100644 index 0000000..b9f6988 --- /dev/null +++ b/src/main/java/org/bukkit/material/Chest.java @@ -0,0 +1,60 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a chest + */ +public class Chest extends DirectionalContainer { + + public Chest() { + super(Material.CHEST); + } + + /** + * Instantiate a chest facing in a particular direction. + * + * @param direction the direction the chest's lit opens towards + */ + public Chest(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Chest(final int type) { + super(type); + } + + public Chest(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Chest(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Chest(final Material type, final byte data) { + super(type, data); + } + + @Override + public Chest clone() { + return (Chest) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Coal.java b/src/main/java/org/bukkit/material/Coal.java new file mode 100644 index 0000000..3a4f7c3 --- /dev/null +++ b/src/main/java/org/bukkit/material/Coal.java @@ -0,0 +1,77 @@ +package org.bukkit.material; + +import org.bukkit.CoalType; +import org.bukkit.Material; + +/** + * Represents the different types of coals. + */ +public class Coal extends MaterialData { + public Coal() { + super(Material.COAL); + } + + public Coal(CoalType type) { + this(); + setType(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Coal(final int type) { + super(type); + } + + public Coal(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Coal(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Coal(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current type of this coal + * + * @return CoalType of this coal + */ + public CoalType getType() { + return CoalType.getByData(getData()); + } + + /** + * Sets the type of this coal + * + * @param type New type of this coal + */ + public void setType(CoalType type) { + setData(type.getData()); + } + + @Override + public String toString() { + return getType() + " " + super.toString(); + } + + @Override + public Coal clone() { + return (Coal) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/CocoaPlant.java b/src/main/java/org/bukkit/material/CocoaPlant.java new file mode 100644 index 0000000..b8280b5 --- /dev/null +++ b/src/main/java/org/bukkit/material/CocoaPlant.java @@ -0,0 +1,132 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents the cocoa plant + */ +public class CocoaPlant extends MaterialData implements Directional, Attachable { + + public enum CocoaPlantSize { + SMALL, + MEDIUM, + LARGE + } + + public CocoaPlant() { + super(Material.COCOA); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public CocoaPlant(final int type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public CocoaPlant(final int type, final byte data) { + super(type, data); + } + + public CocoaPlant(CocoaPlantSize sz) { + this(); + setSize(sz); + } + + public CocoaPlant(CocoaPlantSize sz, BlockFace dir) { + this(); + setSize(sz); + setFacingDirection(dir); + } + + /** + * Get size of plant + * + * @return size + */ + public CocoaPlantSize getSize() { + switch (getData() & 0xC) { + case 0: + return CocoaPlantSize.SMALL; + case 4: + return CocoaPlantSize.MEDIUM; + default: + return CocoaPlantSize.LARGE; + } + } + + /** + * Set size of plant + * + * @param sz - size of plant + */ + public void setSize(CocoaPlantSize sz) { + int dat = getData() & 0x3; + switch (sz) { + case SMALL: + break; + case MEDIUM: + dat |= 0x4; + break; + case LARGE: + dat |= 0x8; + break; + } + setData((byte) dat); + } + + public BlockFace getAttachedFace() { + return getFacing().getOppositeFace(); + } + + public void setFacingDirection(BlockFace face) { + int dat = getData() & 0xC; + switch (face) { + default: + case SOUTH: + break; + case WEST: + dat |= 0x1; + break; + case NORTH: + dat |= 0x2; + break; + case EAST: + dat |= 0x3; + break; + } + setData((byte) dat); + } + + public BlockFace getFacing() { + switch (getData() & 0x3) { + case 0: + return BlockFace.SOUTH; + case 1: + return BlockFace.WEST; + case 2: + return BlockFace.NORTH; + case 3: + return BlockFace.EAST; + } + return null; + } + + @Override + public CocoaPlant clone() { + return (CocoaPlant) super.clone(); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + " " + getSize(); + } +} diff --git a/src/main/java/org/bukkit/material/Colorable.java b/src/main/java/org/bukkit/material/Colorable.java new file mode 100644 index 0000000..3b91b24 --- /dev/null +++ b/src/main/java/org/bukkit/material/Colorable.java @@ -0,0 +1,24 @@ +package org.bukkit.material; + +import org.bukkit.DyeColor; + +/** + * An object that can be colored. + */ +public interface Colorable { + + /** + * Gets the color of this object. + * + * @return The DyeColor of this object. + */ + public DyeColor getColor(); + + /** + * Sets the color of this object to the specified DyeColor. + * + * @param color The color of the object, as a DyeColor. + */ + public void setColor(DyeColor color); + +} diff --git a/src/main/java/org/bukkit/material/Command.java b/src/main/java/org/bukkit/material/Command.java new file mode 100644 index 0000000..174e1ff --- /dev/null +++ b/src/main/java/org/bukkit/material/Command.java @@ -0,0 +1,73 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a command block + */ +public class Command extends MaterialData implements Redstone { + public Command() { + super(Material.COMMAND); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Command(final int type) { + super(type); + } + + public Command(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Command(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Command(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return (getData() & 1) != 0; + } + + /** + * Sets the current state of this Material + * + * @param bool + * whether or not the command block is powered + */ + public void setPowered(boolean bool) { + setData((byte) (bool ? (getData() | 1) : (getData() & -2))); + } + + @Override + public String toString() { + return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public Command clone() { + return (Command) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Crops.java b/src/main/java/org/bukkit/material/Crops.java new file mode 100644 index 0000000..2791998 --- /dev/null +++ b/src/main/java/org/bukkit/material/Crops.java @@ -0,0 +1,77 @@ +package org.bukkit.material; + +import org.bukkit.CropState; +import org.bukkit.Material; + +/** + * Represents the different types of crops. + */ +public class Crops extends MaterialData { + public Crops() { + super(Material.CROPS); + } + + public Crops(CropState state) { + this(); + setState(state); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Crops(final int type) { + super(type); + } + + public Crops(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Crops(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Crops(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current growth state of this crop + * + * @return CropState of this crop + */ + public CropState getState() { + return CropState.getByData(getData()); + } + + /** + * Sets the growth state of this crop + * + * @param state New growth state of this crop + */ + public void setState(CropState state) { + setData(state.getData()); + } + + @Override + public String toString() { + return getState() + " " + super.toString(); + } + + @Override + public Crops clone() { + return (Crops) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/DetectorRail.java b/src/main/java/org/bukkit/material/DetectorRail.java new file mode 100644 index 0000000..b1d3073 --- /dev/null +++ b/src/main/java/org/bukkit/material/DetectorRail.java @@ -0,0 +1,56 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a detector rail + */ +public class DetectorRail extends ExtendedRails implements PressureSensor { + public DetectorRail() { + super(Material.DETECTOR_RAIL); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public DetectorRail(final int type) { + super(type); + } + + public DetectorRail(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public DetectorRail(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public DetectorRail(final Material type, final byte data) { + super(type, data); + } + + public boolean isPressed() { + return (getData() & 0x8) == 0x8; + } + + public void setPressed(boolean isPressed) { + setData((byte) (isPressed ? (getData() | 0x8) : (getData() & ~0x8))); + } + + @Override + public DetectorRail clone() { + return (DetectorRail) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Diode.java b/src/main/java/org/bukkit/material/Diode.java new file mode 100644 index 0000000..04210b7 --- /dev/null +++ b/src/main/java/org/bukkit/material/Diode.java @@ -0,0 +1,123 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +public class Diode extends MaterialData implements Directional { + public Diode() { + super(Material.DIODE_BLOCK_ON); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Diode(int type) { + super(type); + } + + public Diode(Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Diode(int type, byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Diode(Material type, byte data) { + super(type, data); + } + + /** + * Sets the delay of the repeater + * + * @param delay + * The new delay (1-4) + */ + public void setDelay(int delay) { + if (delay > 4) { + delay = 4; + } + if (delay < 1) { + delay = 1; + } + byte newData = (byte) (getData() & 0x3); + + setData((byte) (newData | ((delay - 1) << 2))); + } + + /** + * Gets the delay of the repeater in ticks + * + * @return The delay (1-4) + */ + public int getDelay() { + return (getData() >> 2) + 1; + } + + public void setFacingDirection(BlockFace face) { + int delay = getDelay(); + byte data; + + switch (face) { + case EAST: + data = 0x1; + break; + + case SOUTH: + data = 0x2; + break; + + case WEST: + data = 0x3; + break; + + case NORTH: + default: + data = 0x0; + } + + setData(data); + setDelay(delay); + } + + public BlockFace getFacing() { + byte data = (byte) (getData() & 0x3); + + switch (data) { + case 0x0: + default: + return BlockFace.NORTH; + + case 0x1: + return BlockFace.EAST; + + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.WEST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + " with " + getDelay() + " ticks delay"; + } + + @Override + public Diode clone() { + return (Diode) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Directional.java b/src/main/java/org/bukkit/material/Directional.java new file mode 100644 index 0000000..25624d2 --- /dev/null +++ b/src/main/java/org/bukkit/material/Directional.java @@ -0,0 +1,20 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; + +public interface Directional { + + /** + * Sets the direction that this block is facing in + * + * @param face The facing direction + */ + public void setFacingDirection(BlockFace face); + + /** + * Gets the direction this block is facing + * + * @return the direction this block is facing + */ + public BlockFace getFacing(); +} diff --git a/src/main/java/org/bukkit/material/DirectionalContainer.java b/src/main/java/org/bukkit/material/DirectionalContainer.java new file mode 100644 index 0000000..9b0a047 --- /dev/null +++ b/src/main/java/org/bukkit/material/DirectionalContainer.java @@ -0,0 +1,93 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a furnace or a dispenser. + */ +public class DirectionalContainer extends MaterialData implements Directional { + /** + * + * @deprecated Magic value + */ + @Deprecated + public DirectionalContainer(final int type) { + super(type); + } + + public DirectionalContainer(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public DirectionalContainer(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public DirectionalContainer(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case NORTH: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case EAST: + default: + data = 0x5; + } + + setData(data); + } + + public BlockFace getFacing() { + byte data = getData(); + + switch (data) { + case 0x2: + return BlockFace.NORTH; + + case 0x3: + return BlockFace.SOUTH; + + case 0x4: + return BlockFace.WEST; + + case 0x5: + default: + return BlockFace.EAST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public DirectionalContainer clone() { + return (DirectionalContainer) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Dispenser.java b/src/main/java/org/bukkit/material/Dispenser.java new file mode 100644 index 0000000..b62f8c9 --- /dev/null +++ b/src/main/java/org/bukkit/material/Dispenser.java @@ -0,0 +1,112 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a dispenser. + */ +public class Dispenser extends FurnaceAndDispenser { + + public Dispenser() { + super(Material.DISPENSER); + } + + public Dispenser(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Dispenser(final int type) { + super(type); + } + + public Dispenser(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Dispenser(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Dispenser(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case DOWN: + data = 0x0; + break; + + case UP: + data = 0x1; + break; + + case NORTH: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case EAST: + default: + data = 0x5; + } + + setData(data); + } + + public BlockFace getFacing() { + int data = getData() & 0x7; + + switch (data) { + case 0x0: + return BlockFace.DOWN; + + case 0x1: + return BlockFace.UP; + + case 0x2: + return BlockFace.NORTH; + + case 0x3: + return BlockFace.SOUTH; + + case 0x4: + return BlockFace.WEST; + + case 0x5: + default: + return BlockFace.EAST; + } + } + + @Override + public Dispenser clone() { + return (Dispenser) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Door.java b/src/main/java/org/bukkit/material/Door.java new file mode 100644 index 0000000..65fa32c --- /dev/null +++ b/src/main/java/org/bukkit/material/Door.java @@ -0,0 +1,160 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a door. + * + * @deprecated No longer functions. Do not use. + */ +@Deprecated +public class Door extends MaterialData implements Directional, Openable { + public Door() { + super(Material.WOODEN_DOOR); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Door(final int type) { + super(type); + } + + public Door(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Door(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Door(final Material type, final byte data) { + super(type, data); + } + + /** + * @deprecated Does not work (correctly) anymore + */ + @Deprecated + public boolean isOpen() { + return ((getData() & 0x4) == 0x4); + } + + /** + * @deprecated Does not work (correctly) anymore + */ + @Deprecated + public void setOpen(boolean isOpen) { + setData((byte) (isOpen ? (getData() | 0x4) : (getData() & ~0x4))); + } + + /** + * @return whether this is the top half of the door + */ + public boolean isTopHalf() { + return ((getData() & 0x8) == 0x8); + } + + /** + * Configure this part of the door to be either the top or the bottom half + * + * @param isTopHalf True to make it the top half. + * @deprecated Shouldn't be used anymore + */ + @Deprecated + public void setTopHalf(boolean isTopHalf) { + setData((byte) (isTopHalf ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * @return BlockFace.SELF + * @deprecated Does not work (correctly) anymore + */ + @Deprecated + public BlockFace getHingeCorner() { + byte d = getData(); + + if ((d & 0x3) == 0x3) { + return BlockFace.NORTH_WEST; + } else if ((d & 0x1) == 0x1) { + return BlockFace.SOUTH_EAST; + } else if ((d & 0x2) == 0x2) { + return BlockFace.SOUTH_WEST; + } + + return BlockFace.NORTH_EAST; + } + + @Override + public String toString() { + return (isTopHalf() ? "TOP" : "BOTTOM") + " half of " + super.toString(); + } + + /** + * Set the direction that this door should is facing. + * + * @param face the direction + * @deprecated Does not work (correctly) anymore + */ + @Deprecated + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x12); + switch (face) { + case NORTH: + data |= 0x1; + break; + + case EAST: + data |= 0x2; + break; + + case SOUTH: + data |= 0x3; + break; + } + setData(data); + } + + /** + * Get the direction that this door is facing. + * + * @return the direction + * @deprecated Does not work (correctly) anymore + */ + @Deprecated + public BlockFace getFacing() { + byte data = (byte) (getData() & 0x3); + switch (data) { + case 0: + return BlockFace.WEST; + + case 1: + return BlockFace.NORTH; + + case 2: + return BlockFace.EAST; + + case 3: + return BlockFace.SOUTH; + } + return null; // shouldn't happen + } + + @Override + public Door clone() { + return (Door) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Dye.java b/src/main/java/org/bukkit/material/Dye.java new file mode 100644 index 0000000..4412c1f --- /dev/null +++ b/src/main/java/org/bukkit/material/Dye.java @@ -0,0 +1,72 @@ +package org.bukkit.material; + +import org.bukkit.DyeColor; +import org.bukkit.Material; + +/** + * Represents dye + */ +public class Dye extends MaterialData implements Colorable { + public Dye() { + super(Material.INK_SACK); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Dye(final int type) { + super(type); + } + + public Dye(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Dye(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Dye(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current color of this dye + * + * @return DyeColor of this dye + */ + public DyeColor getColor() { + return DyeColor.getByDyeData(getData()); + } + + /** + * Sets the color of this dye + * + * @param color New color of this dye + */ + public void setColor(DyeColor color) { + setData(color.getDyeData()); + } + + @Override + public String toString() { + return getColor() + " DYE(" + getData() + ")"; + } + + @Override + public Dye clone() { + return (Dye) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/EnderChest.java b/src/main/java/org/bukkit/material/EnderChest.java new file mode 100644 index 0000000..696dc65 --- /dev/null +++ b/src/main/java/org/bukkit/material/EnderChest.java @@ -0,0 +1,60 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents an ender chest + */ +public class EnderChest extends DirectionalContainer { + + public EnderChest() { + super(Material.ENDER_CHEST); + } + + /** + * Instantiate an ender chest facing in a particular direction. + * + * @param direction the direction the ender chest's lid opens towards + */ + public EnderChest(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public EnderChest(final int type) { + super(type); + } + + public EnderChest(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public EnderChest(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public EnderChest(final Material type, final byte data) { + super(type, data); + } + + @Override + public EnderChest clone() { + return (EnderChest) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/ExtendedRails.java b/src/main/java/org/bukkit/material/ExtendedRails.java new file mode 100644 index 0000000..0dbbf7c --- /dev/null +++ b/src/main/java/org/bukkit/material/ExtendedRails.java @@ -0,0 +1,73 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * This is the superclass for the {@link DetectorRail} and {@link PoweredRail} + * classes + */ +public class ExtendedRails extends Rails { + /** + * + * @deprecated Magic value + */ + @Deprecated + public ExtendedRails(final int type) { + super(type); + } + + public ExtendedRails(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public ExtendedRails(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public ExtendedRails(final Material type, final byte data) { + super(type, data); + } + + @Override + public boolean isCurve() { + return false; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + @Override + protected byte getConvertedData() { + return (byte) (getData() & 0x7); + } + + @Override + public void setDirection(BlockFace face, boolean isOnSlope) { + boolean extraBitSet = (getData() & 0x8) == 0x8; + + if (face != BlockFace.WEST && face != BlockFace.EAST && face != BlockFace.NORTH && face != BlockFace.SOUTH) { + throw new IllegalArgumentException("Detector rails and powered rails cannot be set on a curve!"); + } + + super.setDirection(face, isOnSlope); + setData((byte) (extraBitSet ? (getData() | 0x8) : (getData() & ~0x8))); + } + + @Override + public ExtendedRails clone() { + return (ExtendedRails) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/FlowerPot.java b/src/main/java/org/bukkit/material/FlowerPot.java new file mode 100644 index 0000000..787c58d --- /dev/null +++ b/src/main/java/org/bukkit/material/FlowerPot.java @@ -0,0 +1,135 @@ +package org.bukkit.material; + +import org.bukkit.GrassSpecies; +import org.bukkit.Material; +import org.bukkit.TreeSpecies; + +/** + * Represents a flower pot. + */ +public class FlowerPot extends MaterialData { + + /** + * Default constructor for a flower pot. + */ + public FlowerPot() { + super(Material.FLOWER_POT); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public FlowerPot(final int type) { + super(type); + } + + public FlowerPot(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public FlowerPot(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public FlowerPot(final Material type, final byte data) { + super(type, data); + } + + /** + * Get the material in the flower pot + * + * @return material MaterialData for the block currently in the flower pot + * or null if empty + */ + public MaterialData getContents() { + switch (getData()) { + case 1: + return new MaterialData(Material.RED_ROSE); + case 2: + return new MaterialData(Material.YELLOW_FLOWER); + case 3: + return new Tree(TreeSpecies.GENERIC); + case 4: + return new Tree(TreeSpecies.REDWOOD); + case 5: + return new Tree(TreeSpecies.BIRCH); + case 6: + return new Tree(TreeSpecies.JUNGLE); + case 7: + return new MaterialData(Material.RED_MUSHROOM); + case 8: + return new MaterialData(Material.BROWN_MUSHROOM); + case 9: + return new MaterialData(Material.CACTUS); + case 10: + return new MaterialData(Material.DEAD_BUSH); + case 11: + return new LongGrass(GrassSpecies.FERN_LIKE); + default: + return null; + } + } + + /** + * Set the contents of the flower pot + * + * @param materialData MaterialData of the block to put in the flower pot. + */ + public void setContents(MaterialData materialData) { + Material mat = materialData.getItemType(); + + if (mat == Material.RED_ROSE) { + setData((byte) 1); + } else if (mat == Material.YELLOW_FLOWER) { + setData((byte) 2); + } else if (mat == Material.RED_MUSHROOM) { + setData((byte) 7); + } else if (mat == Material.BROWN_MUSHROOM) { + setData((byte) 8); + } else if (mat == Material.CACTUS) { + setData((byte) 9); + } else if (mat == Material.DEAD_BUSH) { + setData((byte) 10); + } else if (mat == Material.SAPLING) { + TreeSpecies species = ((Tree) materialData).getSpecies(); + + if (species == TreeSpecies.GENERIC) { + setData((byte) 3); + } else if (species == TreeSpecies.REDWOOD) { + setData((byte) 4); + } else if (species == TreeSpecies.BIRCH) { + setData((byte) 5); + } else { + setData((byte) 6); + } + } else if (mat == Material.LONG_GRASS) { + GrassSpecies species = ((LongGrass) materialData).getSpecies(); + + if (species == GrassSpecies.FERN_LIKE) { + setData((byte) 11); + } + } + } + + @Override + public String toString() { + return super.toString() + " containing " + getContents(); + } + + @Override + public FlowerPot clone() { + return (FlowerPot) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Furnace.java b/src/main/java/org/bukkit/material/Furnace.java new file mode 100644 index 0000000..49645aa --- /dev/null +++ b/src/main/java/org/bukkit/material/Furnace.java @@ -0,0 +1,60 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a furnace. + */ +public class Furnace extends FurnaceAndDispenser { + + public Furnace() { + super(Material.FURNACE); + } + + /** + * Instantiate a furnace facing in a particular direction. + * + * @param direction the direction the furnace's "opening" is facing + */ + public Furnace(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Furnace(final int type) { + super(type); + } + + public Furnace(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Furnace(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Furnace(final Material type, final byte data) { + super(type, data); + } + + @Override + public Furnace clone() { + return (Furnace) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/FurnaceAndDispenser.java b/src/main/java/org/bukkit/material/FurnaceAndDispenser.java new file mode 100644 index 0000000..3665479 --- /dev/null +++ b/src/main/java/org/bukkit/material/FurnaceAndDispenser.java @@ -0,0 +1,45 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a furnace or dispenser, two types of directional containers + */ +public class FurnaceAndDispenser extends DirectionalContainer { + + /** + * + * @deprecated Magic value + */ + @Deprecated + public FurnaceAndDispenser(final int type) { + super(type); + } + + public FurnaceAndDispenser(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public FurnaceAndDispenser(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public FurnaceAndDispenser(final Material type, final byte data) { + super(type, data); + } + + @Override + public FurnaceAndDispenser clone() { + return (FurnaceAndDispenser) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Gate.java b/src/main/java/org/bukkit/material/Gate.java new file mode 100644 index 0000000..8adc1cf --- /dev/null +++ b/src/main/java/org/bukkit/material/Gate.java @@ -0,0 +1,91 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a fence gate + */ +public class Gate extends MaterialData implements Directional, Openable { + private static final byte OPEN_BIT = 0x4; + private static final byte DIR_BIT = 0x3; + private static final byte GATE_SOUTH = 0x0; + private static final byte GATE_WEST = 0x1; + private static final byte GATE_NORTH = 0x2; + private static final byte GATE_EAST = 0x3; + + public Gate() { + super(Material.FENCE_GATE); + } + + public Gate(int type, byte data){ + super(type, data); + } + + public Gate(byte data) { + super(Material.FENCE_GATE, data); + } + + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() &~ DIR_BIT); + + switch (face) { + default: + case EAST: + data |= GATE_SOUTH; + break; + case SOUTH: + data |= GATE_WEST; + break; + case WEST: + data |= GATE_NORTH; + break; + case NORTH: + data |= GATE_EAST; + break; + } + + setData(data); + } + + public BlockFace getFacing() { + switch (getData() & DIR_BIT) { + case GATE_SOUTH: + return BlockFace.EAST; + case GATE_WEST: + return BlockFace.SOUTH; + case GATE_NORTH: + return BlockFace.WEST; + case GATE_EAST: + return BlockFace.NORTH; + } + + return BlockFace.EAST; + } + + public boolean isOpen() { + return (getData() & OPEN_BIT) > 0; + } + + public void setOpen(boolean isOpen) { + byte data = getData(); + + if (isOpen) { + data |= OPEN_BIT; + } else { + data &= ~OPEN_BIT; + } + + setData(data); + } + + @Override + public String toString() { + return (isOpen() ? "OPEN " : "CLOSED ") + " facing and opening " + getFacing(); + } + + @Override + public Gate clone() { + return (Gate) super.clone(); + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/material/Ladder.java b/src/main/java/org/bukkit/material/Ladder.java new file mode 100644 index 0000000..09862bf --- /dev/null +++ b/src/main/java/org/bukkit/material/Ladder.java @@ -0,0 +1,102 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; +import org.bukkit.Material; + +/** + * Represents Ladder data + */ +public class Ladder extends SimpleAttachableMaterialData { + public Ladder() { + super(Material.LADDER); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Ladder(final int type) { + super(type); + } + + public Ladder(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Ladder(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Ladder(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + byte data = getData(); + + switch (data) { + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.EAST; + + case 0x5: + return BlockFace.WEST; + } + + return null; + } + + /** + * Sets the direction this ladder is facing + */ + public void setFacingDirection(BlockFace face) { + byte data = (byte) 0x0; + + switch (face) { + case SOUTH: + data = 0x2; + break; + + case NORTH: + data = 0x3; + break; + + case EAST: + data = 0x4; + break; + + case WEST: + data = 0x5; + break; + } + + setData(data); + + } + + @Override + public Ladder clone() { + return (Ladder) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Leaves.java b/src/main/java/org/bukkit/material/Leaves.java new file mode 100644 index 0000000..97ba382 --- /dev/null +++ b/src/main/java/org/bukkit/material/Leaves.java @@ -0,0 +1,77 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.TreeSpecies; + +/** + * Represents the different types of leaves. + */ +public class Leaves extends MaterialData { + public Leaves() { + super(Material.LEAVES); + } + + public Leaves(TreeSpecies species) { + this(); + setSpecies(species); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Leaves(final int type) { + super(type); + } + + public Leaves(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Leaves(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Leaves(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current species of this leave + * + * @return TreeSpecies of this leave + */ + public TreeSpecies getSpecies() { + return TreeSpecies.getByData((byte) (getData() & 3)); + } + + /** + * Sets the species of this leave + * + * @param species New species of this leave + */ + public void setSpecies(TreeSpecies species) { + setData(species.getData()); + } + + @Override + public String toString() { + return getSpecies() + " " + super.toString(); + } + + @Override + public Leaves clone() { + return (Leaves) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Lever.java b/src/main/java/org/bukkit/material/Lever.java new file mode 100644 index 0000000..b88c536 --- /dev/null +++ b/src/main/java/org/bukkit/material/Lever.java @@ -0,0 +1,160 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; +import org.bukkit.Material; + +/** + * Represents a lever + */ +public class Lever extends SimpleAttachableMaterialData implements Redstone { + public Lever() { + super(Material.LEVER); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Lever(final int type) { + super(type); + } + + public Lever(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Lever(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Lever(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return (getData() & 0x8) == 0x8; + } + + /** + * Set this lever to be powered or not. + * + * @param isPowered whether the lever should be powered or not + */ + public void setPowered(boolean isPowered) { + setData((byte) (isPowered ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + byte data = (byte) (getData() & 0x7); + + switch (data) { + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.SOUTH; + + case 0x5: + case 0x6: + return BlockFace.DOWN; + + case 0x0: + case 0x7: + return BlockFace.UP; + + } + + return null; + } + + /** + * Sets the direction this lever is pointing in + */ + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x8); + BlockFace attach = getAttachedFace(); + + if (attach == BlockFace.DOWN) { + switch (face) { + case SOUTH: + case NORTH: + data |= 0x5; + break; + + case EAST: + case WEST: + data |= 0x6; + break; + } + } else if (attach == BlockFace.UP) { + switch (face) { + case SOUTH: + case NORTH: + data |= 0x7; + break; + + case EAST: + case WEST: + data |= 0x0; + break; + } + } else { + switch (face) { + case EAST: + data |= 0x1; + break; + + case WEST: + data |= 0x2; + break; + + case SOUTH: + data |= 0x3; + break; + + case NORTH: + data |= 0x4; + break; + } + } + setData(data); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public Lever clone() { + return (Lever) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/LongGrass.java b/src/main/java/org/bukkit/material/LongGrass.java new file mode 100644 index 0000000..e8d1f38 --- /dev/null +++ b/src/main/java/org/bukkit/material/LongGrass.java @@ -0,0 +1,77 @@ +package org.bukkit.material; + +import org.bukkit.GrassSpecies; +import org.bukkit.Material; + +/** + * Represents the different types of long grasses. + */ +public class LongGrass extends MaterialData { + public LongGrass() { + super(Material.LONG_GRASS); + } + + public LongGrass(GrassSpecies species) { + this(); + setSpecies(species); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public LongGrass(final int type) { + super(type); + } + + public LongGrass(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public LongGrass(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public LongGrass(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current species of this grass + * + * @return GrassSpecies of this grass + */ + public GrassSpecies getSpecies() { + return GrassSpecies.getByData(getData()); + } + + /** + * Sets the species of this grass + * + * @param species New species of this grass + */ + public void setSpecies(GrassSpecies species) { + setData(species.getData()); + } + + @Override + public String toString() { + return getSpecies() + " " + super.toString(); + } + + @Override + public LongGrass clone() { + return (LongGrass) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/MaterialData.java b/src/main/java/org/bukkit/material/MaterialData.java new file mode 100644 index 0000000..ad7675f --- /dev/null +++ b/src/main/java/org/bukkit/material/MaterialData.java @@ -0,0 +1,135 @@ +package org.bukkit.material; + +import org.bukkit.inventory.ItemStack; +import org.bukkit.Material; + +/** + * Handles specific metadata for certain items or blocks + */ +public class MaterialData implements Cloneable { + private final int type; + private byte data = 0; + + /** + * + * @deprecated Magic value + */ + @Deprecated + public MaterialData(final int type) { + this(type, (byte) 0); + } + + public MaterialData(final Material type) { + this(type, (byte) 0); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public MaterialData(final int type, final byte data) { + this.type = type; + this.data = data; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public MaterialData(final Material type, final byte data) { + this(type.getId(), data); + } + + /** + * Gets the raw data in this material + * + * @return Raw data + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Sets the raw data of this material + * + * @param data New raw data + * @deprecated Magic value + */ + @Deprecated + public void setData(byte data) { + this.data = data; + } + + /** + * Gets the Material that this MaterialData represents + * + * @return Material represented by this MaterialData + */ + public Material getItemType() { + return Material.getMaterial(type); + } + + /** + * Gets the Material Id that this MaterialData represents + * + * @return Material Id represented by this MaterialData + * @deprecated Magic value + */ + @Deprecated + public int getItemTypeId() { + return type; + } + + /** + * Creates a new ItemStack based on this MaterialData + * + * @return New ItemStack containing a copy of this MaterialData + */ + public ItemStack toItemStack() { + return new ItemStack(type, 0, data); + } + + /** + * Creates a new ItemStack based on this MaterialData + * + * @param amount The stack size of the new stack + * @return New ItemStack containing a copy of this MaterialData + */ + public ItemStack toItemStack(int amount) { + return new ItemStack(type, amount, data); + } + + @Override + public String toString() { + return getItemType() + "(" + getData() + ")"; + } + + @Override + public int hashCode() { + return ((getItemTypeId() << 8) ^ getData()); + } + + @Override + public boolean equals(Object obj) { + if (obj != null && obj instanceof MaterialData) { + MaterialData md = (MaterialData) obj; + + return (md.getItemTypeId() == getItemTypeId() && md.getData() == getData()); + } else { + return false; + } + } + + @Override + public MaterialData clone() { + try { + return (MaterialData) super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } +} diff --git a/src/main/java/org/bukkit/material/MonsterEggs.java b/src/main/java/org/bukkit/material/MonsterEggs.java new file mode 100644 index 0000000..d8b627b --- /dev/null +++ b/src/main/java/org/bukkit/material/MonsterEggs.java @@ -0,0 +1,67 @@ +package org.bukkit.material; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Material; + +/** + * Represents the different types of monster eggs + */ +public class MonsterEggs extends TexturedMaterial { + + private static final List textures = new ArrayList(); + static { + textures.add(Material.STONE); + textures.add(Material.COBBLESTONE); + textures.add(Material.SMOOTH_BRICK); + } + + public MonsterEggs() { + super(Material.MONSTER_EGGS); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public MonsterEggs(final int type) { + super(type); + } + + public MonsterEggs(final Material type) { + super((textures.contains(type)) ? Material.MONSTER_EGGS : type); + if (textures.contains(type)) { + setMaterial(type); + } + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public MonsterEggs(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public MonsterEggs(final Material type, final byte data) { + super(type, data); + } + + @Override + public List getTextures() { + return textures; + } + + @Override + public MonsterEggs clone() { + return (MonsterEggs) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Mushroom.java b/src/main/java/org/bukkit/material/Mushroom.java new file mode 100644 index 0000000..716d378 --- /dev/null +++ b/src/main/java/org/bukkit/material/Mushroom.java @@ -0,0 +1,197 @@ +package org.bukkit.material; + +import java.util.EnumSet; +import java.util.Set; + +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a huge mushroom block + */ +public class Mushroom extends MaterialData { + private static final byte SHROOM_NONE = 0; + private static final byte SHROOM_STEM = 10; + private static final byte NORTH_LIMIT = 4; + private static final byte SOUTH_LIMIT = 6; + private static final byte EAST_WEST_LIMIT = 3; + private static final byte EAST_REMAINDER = 0; + private static final byte WEST_REMAINDER = 1; + private static final byte NORTH_SOUTH_MOD = 3; + private static final byte EAST_WEST_MOD = 1; + + public Mushroom(Material shroom) { + super(shroom); + Validate.isTrue(shroom == Material.HUGE_MUSHROOM_1 || shroom == Material.HUGE_MUSHROOM_2, "Not a mushroom!"); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Mushroom(Material shroom, byte data) { + super(shroom, data); + Validate.isTrue(shroom == Material.HUGE_MUSHROOM_1 || shroom == Material.HUGE_MUSHROOM_2, "Not a mushroom!"); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Mushroom(int type, byte data){ + super(type, data); + Validate.isTrue(type == Material.HUGE_MUSHROOM_1.getId() || type == Material.HUGE_MUSHROOM_2.getId(), "Not a mushroom!"); + } + + /** + * @return Whether this is a mushroom stem. + */ + public boolean isStem() { + return getData() == SHROOM_STEM; + } + + /** + * Sets this to be a mushroom stem. + */ + public void setStem() { + setData((byte) 10); + } + + /** + * Checks whether a face of the block is painted. + * + * @param face The face to check. + * @return True if it is painted. + */ + public boolean isFacePainted(BlockFace face) { + byte data = getData(); + + if (data == SHROOM_NONE || data == SHROOM_STEM) { + return false; + } + + switch (face) { + case WEST: + return data < NORTH_LIMIT; + case EAST: + return data > SOUTH_LIMIT; + case NORTH: + return data % EAST_WEST_LIMIT == EAST_REMAINDER; + case SOUTH: + return data % EAST_WEST_LIMIT == WEST_REMAINDER; + case UP: + return true; + default: + return false; + } + } + + /** + * Set a face of the block to be painted or not. Note that due to the + * nature of how the data is stored, setting a face painted or not is not + * guaranteed to leave the other faces unchanged. + * + * @param face The face to paint or unpaint. + * @param painted True if you want to paint it, false if you want the + * pores to show. + */ + public void setFacePainted(BlockFace face, boolean painted) { + if (painted == isFacePainted(face)) { + return; + } + + byte data = getData(); + + if (data == SHROOM_STEM) { + data = 5; + } + + switch (face) { + case WEST: + if (painted) { + data -= NORTH_SOUTH_MOD; + } else { + data += NORTH_SOUTH_MOD; + } + + break; + case EAST: + if (painted) { + data += NORTH_SOUTH_MOD; + } else { + data -= NORTH_SOUTH_MOD; + } + + break; + case NORTH: + if (painted) { + data += EAST_WEST_MOD; + } else { + data -= EAST_WEST_MOD; + } + + break; + case SOUTH: + if (painted) { + data -= EAST_WEST_MOD; + } else { + data += EAST_WEST_MOD; + } + + break; + case UP: + if (!painted) { + data = 0; + } + + break; + default: + throw new IllegalArgumentException("Can't paint that face of a mushroom!"); + } + + setData(data); + } + + /** + * @return A set of all faces that are currently painted (an empty set if + * it is a stem) + */ + public Set getPaintedFaces() { + EnumSet faces = EnumSet.noneOf(BlockFace.class); + + if (isFacePainted(BlockFace.WEST)) { + faces.add(BlockFace.WEST); + } + + if (isFacePainted(BlockFace.NORTH)) { + faces.add(BlockFace.NORTH); + } + + if (isFacePainted(BlockFace.SOUTH)) { + faces.add(BlockFace.SOUTH); + } + + if (isFacePainted(BlockFace.EAST)) { + faces.add(BlockFace.EAST); + } + + if (isFacePainted(BlockFace.UP)) { + faces.add(BlockFace.UP); + } + + return faces; + } + + @Override + public String toString() { + return Material.getMaterial(getItemTypeId()).toString() + (isStem() ? "{STEM}" : getPaintedFaces()); + } + + @Override + public Mushroom clone() { + return (Mushroom) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/NetherWarts.java b/src/main/java/org/bukkit/material/NetherWarts.java new file mode 100644 index 0000000..99ea3f0 --- /dev/null +++ b/src/main/java/org/bukkit/material/NetherWarts.java @@ -0,0 +1,99 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.NetherWartsState; + +/** + * Represents nether wart + */ +public class NetherWarts extends MaterialData { + public NetherWarts() { + super(Material.NETHER_WARTS); + } + + public NetherWarts(NetherWartsState state) { + this(); + setState(state); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public NetherWarts(final int type) { + super(type); + } + + public NetherWarts(final Material type) { + super (type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public NetherWarts(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public NetherWarts(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current growth state of this nether wart + * + * @return NetherWartsState of this nether wart + */ + public NetherWartsState getState() { + switch (getData()) { + case 0: + return NetherWartsState.SEEDED; + case 1: + return NetherWartsState.STAGE_ONE; + case 2: + return NetherWartsState.STAGE_TWO; + default: + return NetherWartsState.RIPE; + } + } + + /** + * Sets the growth state of this nether wart + * + * @param state New growth state of this nether wart + */ + public void setState(NetherWartsState state) { + switch (state) { + case SEEDED: + setData((byte) 0x0); + return; + case STAGE_ONE: + setData((byte) 0x1); + return; + case STAGE_TWO: + setData((byte) 0x2); + return; + case RIPE: + setData((byte) 0x3); + return; + } + } + + @Override + public String toString() { + return getState() + " " + super.toString(); + } + + @Override + public NetherWarts clone() { + return (NetherWarts) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Openable.java b/src/main/java/org/bukkit/material/Openable.java new file mode 100644 index 0000000..0ae54f9 --- /dev/null +++ b/src/main/java/org/bukkit/material/Openable.java @@ -0,0 +1,18 @@ +package org.bukkit.material; + +public interface Openable { + + /** + * Check to see if the door is open. + * + * @return true if the door has swung counterclockwise around its hinge. + */ + boolean isOpen(); + + /** + * Configure this door to be either open or closed; + * + * @param isOpen True to open the door. + */ + void setOpen(boolean isOpen); +} diff --git a/src/main/java/org/bukkit/material/PistonBaseMaterial.java b/src/main/java/org/bukkit/material/PistonBaseMaterial.java new file mode 100644 index 0000000..f3586dc --- /dev/null +++ b/src/main/java/org/bukkit/material/PistonBaseMaterial.java @@ -0,0 +1,111 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Material data for the piston base block + */ +public class PistonBaseMaterial extends MaterialData implements Directional, Redstone { + /** + * + * @deprecated Magic value + */ + @Deprecated + public PistonBaseMaterial(final int type) { + super(type); + } + + public PistonBaseMaterial(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PistonBaseMaterial(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PistonBaseMaterial(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x8); + + switch (face) { + case UP: + data |= 1; + break; + case NORTH: + data |= 2; + break; + case SOUTH: + data |= 3; + break; + case WEST: + data |= 4; + break; + case EAST: + data |= 5; + break; + } + setData(data); + } + + public BlockFace getFacing() { + byte dir = (byte) (getData() & 7); + + switch (dir) { + case 0: + return BlockFace.DOWN; + case 1: + return BlockFace.UP; + case 2: + return BlockFace.NORTH; + case 3: + return BlockFace.SOUTH; + case 4: + return BlockFace.WEST; + case 5: + return BlockFace.EAST; + default: + return BlockFace.SELF; + } + } + + public boolean isPowered() { + return (getData() & 0x8) == 0x8; + } + + /** + * Sets the current state of this piston + * + * @param powered true if the piston is extended & powered, or false + */ + public void setPowered(boolean powered) { + setData((byte) (powered ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * Checks if this piston base is sticky, and returns true if so + * + * @return true if this piston is "sticky", or false + */ + public boolean isSticky() { + return this.getItemType() == Material.PISTON_STICKY_BASE; + } + + @Override + public PistonBaseMaterial clone() { + return (PistonBaseMaterial) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/PistonExtensionMaterial.java b/src/main/java/org/bukkit/material/PistonExtensionMaterial.java new file mode 100644 index 0000000..85dee84 --- /dev/null +++ b/src/main/java/org/bukkit/material/PistonExtensionMaterial.java @@ -0,0 +1,111 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Material data for the piston extension block + */ +public class PistonExtensionMaterial extends MaterialData implements Attachable { + /** + * + * @deprecated Magic value + */ + @Deprecated + public PistonExtensionMaterial(final int type) { + super(type); + } + + public PistonExtensionMaterial(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PistonExtensionMaterial(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PistonExtensionMaterial(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x8); + + switch (face) { + case UP: + data |= 1; + break; + case NORTH: + data |= 2; + break; + case SOUTH: + data |= 3; + break; + case WEST: + data |= 4; + break; + case EAST: + data |= 5; + break; + } + setData(data); + } + + public BlockFace getFacing() { + byte dir = (byte) (getData() & 7); + + switch (dir) { + case 0: + return BlockFace.DOWN; + case 1: + return BlockFace.UP; + case 2: + return BlockFace.NORTH; + case 3: + return BlockFace.SOUTH; + case 4: + return BlockFace.WEST; + case 5: + return BlockFace.EAST; + default: + return BlockFace.SELF; + } + } + + /** + * Checks if this piston extension is sticky, and returns true if so + * + * @return true if this piston is "sticky", or false + */ + public boolean isSticky() { + return (getData() & 8) == 8; + } + + /** + * Sets whether or not this extension is sticky + * + * @param sticky true if sticky, otherwise false + */ + public void setSticky(boolean sticky) { + setData((byte) (sticky ? (getData() | 0x8) : (getData() & ~0x8))); + } + + public BlockFace getAttachedFace() { + return getFacing().getOppositeFace(); + } + + @Override + public PistonExtensionMaterial clone() { + return (PistonExtensionMaterial) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/PoweredRail.java b/src/main/java/org/bukkit/material/PoweredRail.java new file mode 100644 index 0000000..444e53b --- /dev/null +++ b/src/main/java/org/bukkit/material/PoweredRail.java @@ -0,0 +1,61 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a powered rail + */ +public class PoweredRail extends ExtendedRails implements Redstone { + public PoweredRail() { + super(Material.POWERED_RAIL); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PoweredRail(final int type) { + super(type); + } + + public PoweredRail(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PoweredRail(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PoweredRail(final Material type, final byte data) { + super(type, data); + } + + public boolean isPowered() { + return (getData() & 0x8) == 0x8; + } + + /** + * Set whether this PoweredRail should be powered or not. + * + * @param isPowered whether or not the rail is powered + */ + public void setPowered(boolean isPowered) { + setData((byte) (isPowered ? (getData() | 0x8) : (getData() & ~0x8))); + } + + @Override + public PoweredRail clone() { + return (PoweredRail) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/PressurePlate.java b/src/main/java/org/bukkit/material/PressurePlate.java new file mode 100644 index 0000000..8c3bc75 --- /dev/null +++ b/src/main/java/org/bukkit/material/PressurePlate.java @@ -0,0 +1,57 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a pressure plate + */ +public class PressurePlate extends MaterialData implements PressureSensor { + public PressurePlate() { + super(Material.WOOD_PLATE); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PressurePlate(int type) { + super(type); + } + + public PressurePlate(Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PressurePlate(int type, byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public PressurePlate(Material type, byte data) { + super(type, data); + } + + public boolean isPressed() { + return getData() == 0x1; + } + + @Override + public String toString() { + return super.toString() + (isPressed() ? " PRESSED" : ""); + } + + @Override + public PressurePlate clone() { + return (PressurePlate) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/PressureSensor.java b/src/main/java/org/bukkit/material/PressureSensor.java new file mode 100644 index 0000000..de20bd3 --- /dev/null +++ b/src/main/java/org/bukkit/material/PressureSensor.java @@ -0,0 +1,5 @@ +package org.bukkit.material; + +public interface PressureSensor { + public boolean isPressed(); +} diff --git a/src/main/java/org/bukkit/material/Pumpkin.java b/src/main/java/org/bukkit/material/Pumpkin.java new file mode 100644 index 0000000..d6ca83c --- /dev/null +++ b/src/main/java/org/bukkit/material/Pumpkin.java @@ -0,0 +1,112 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a pumpkin. + */ +public class Pumpkin extends MaterialData implements Directional { + + public Pumpkin() { + super(Material.PUMPKIN); + } + + /** + * Instantiate a pumpkin facing in a particular direction. + * + * @param direction the direction the pumkin's face is facing + */ + public Pumpkin(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Pumpkin(final int type) { + super(type); + } + + public Pumpkin(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Pumpkin(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Pumpkin(final Material type, final byte data) { + super(type, data); + } + + public boolean isLit() { + return getItemType() == Material.JACK_O_LANTERN; + } + + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case NORTH: + data = 0x0; + break; + + case EAST: + data = 0x1; + break; + + case SOUTH: + data = 0x2; + break; + + case WEST: + default: + data = 0x3; + } + + setData(data); + } + + public BlockFace getFacing() { + byte data = getData(); + + switch (data) { + case 0x0: + return BlockFace.NORTH; + + case 0x1: + return BlockFace.EAST; + + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + default: + return BlockFace.EAST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + " " + (isLit() ? "" : "NOT ") + "LIT"; + } + + @Override + public Pumpkin clone() { + return (Pumpkin) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Rails.java b/src/main/java/org/bukkit/material/Rails.java new file mode 100644 index 0000000..74fd95a --- /dev/null +++ b/src/main/java/org/bukkit/material/Rails.java @@ -0,0 +1,176 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents minecart rails. + */ +public class Rails extends MaterialData { + + public Rails() { + super(Material.RAILS); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Rails(final int type) { + super(type); + } + + public Rails(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Rails(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Rails(final Material type, final byte data) { + super(type, data); + } + + /** + * @return the whether this track is set on a slope + */ + public boolean isOnSlope() { + byte d = getConvertedData(); + + return (d == 0x2 || d == 0x3 || d == 0x4 || d == 0x5); + } + + /** + * @return the whether this track is set as a curve + */ + public boolean isCurve() { + byte d = getConvertedData(); + + return (d == 0x6 || d == 0x7 || d == 0x8 || d == 0x9); + } + + /** + * @return the direction these tracks are set + *

          + * Note that tracks are bidirectional and that the direction returned + * is the ascending direction if the track is set on a slope. If it is + * set as a curve, the corner of the track is returned. + */ + public BlockFace getDirection() { + byte d = getConvertedData(); + + switch (d) { + case 0x0: + default: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.EAST; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.WEST; + + case 0x4: + return BlockFace.NORTH; + + case 0x5: + return BlockFace.SOUTH; + + case 0x6: + return BlockFace.NORTH_WEST; + + case 0x7: + return BlockFace.NORTH_EAST; + + case 0x8: + return BlockFace.SOUTH_EAST; + + case 0x9: + return BlockFace.SOUTH_WEST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getDirection() + (isCurve() ? " on a curve" : (isOnSlope() ? " on a slope" : "")); + } + + /** + * Return the data without the extended properties used by {@link + * PoweredRail} and {@link DetectorRail}. Overridden in {@link + * ExtendedRails} + * + * @return the data without the extended part + * @deprecated Magic value + */ + @Deprecated + protected byte getConvertedData() { + return getData(); + } + + /** + * Set the direction of these tracks + *

          + * Note that tracks are bidirectional and that the direction returned is + * the ascending direction if the track is set on a slope. If it is set as + * a curve, the corner of the track should be supplied. + * + * @param face the direction the track should be facing + * @param isOnSlope whether or not the track should be on a slope + */ + public void setDirection(BlockFace face, boolean isOnSlope) { + switch (face) { + case EAST: + setData((byte) (isOnSlope ? 0x2 : 0x1)); + break; + + case WEST: + setData((byte) (isOnSlope ? 0x3 : 0x1)); + break; + + case NORTH: + setData((byte) (isOnSlope ? 0x4 : 0x0)); + break; + + case SOUTH: + setData((byte) (isOnSlope ? 0x5 : 0x0)); + break; + + case NORTH_WEST: + setData((byte) 0x6); + break; + + case NORTH_EAST: + setData((byte) 0x7); + break; + + case SOUTH_EAST: + setData((byte) 0x8); + break; + + case SOUTH_WEST: + setData((byte) 0x9); + break; + } + } + + @Override + public Rails clone() { + return (Rails) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Redstone.java b/src/main/java/org/bukkit/material/Redstone.java new file mode 100644 index 0000000..3e46603 --- /dev/null +++ b/src/main/java/org/bukkit/material/Redstone.java @@ -0,0 +1,15 @@ +package org.bukkit.material; + +/** + * Indicated a Material that may carry or create a Redstone current + */ +public interface Redstone { + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered(); +} diff --git a/src/main/java/org/bukkit/material/RedstoneTorch.java b/src/main/java/org/bukkit/material/RedstoneTorch.java new file mode 100644 index 0000000..76a3ddd --- /dev/null +++ b/src/main/java/org/bukkit/material/RedstoneTorch.java @@ -0,0 +1,63 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a redstone torch + */ +public class RedstoneTorch extends Torch implements Redstone { + public RedstoneTorch() { + super(Material.REDSTONE_TORCH_ON); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public RedstoneTorch(final int type) { + super(type); + } + + public RedstoneTorch(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public RedstoneTorch(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public RedstoneTorch(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return getItemType() == Material.REDSTONE_TORCH_ON; + } + + @Override + public String toString() { + return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public RedstoneTorch clone() { + return (RedstoneTorch) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/RedstoneWire.java b/src/main/java/org/bukkit/material/RedstoneWire.java new file mode 100644 index 0000000..b429af0 --- /dev/null +++ b/src/main/java/org/bukkit/material/RedstoneWire.java @@ -0,0 +1,63 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents redstone wire + */ +public class RedstoneWire extends MaterialData implements Redstone { + public RedstoneWire() { + super(Material.REDSTONE_WIRE); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public RedstoneWire(final int type) { + super(type); + } + + public RedstoneWire(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public RedstoneWire(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public RedstoneWire(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return getData() > 0; + } + + @Override + public String toString() { + return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public RedstoneWire clone() { + return (RedstoneWire) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Sandstone.java b/src/main/java/org/bukkit/material/Sandstone.java new file mode 100644 index 0000000..26cbbb5 --- /dev/null +++ b/src/main/java/org/bukkit/material/Sandstone.java @@ -0,0 +1,77 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.SandstoneType; + +/** + * Represents the different types of sandstone. + */ +public class Sandstone extends MaterialData { + public Sandstone() { + super(Material.SANDSTONE); + } + + public Sandstone(SandstoneType type) { + this(); + setType(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Sandstone(final int type) { + super(type); + } + + public Sandstone(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Sandstone(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Sandstone(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current type of this sandstone + * + * @return SandstoneType of this sandstone + */ + public SandstoneType getType() { + return SandstoneType.getByData(getData()); + } + + /** + * Sets the type of this sandstone + * + * @param type New type of this sandstone + */ + public void setType(SandstoneType type) { + setData(type.getData()); + } + + @Override + public String toString() { + return getType() + " " + super.toString(); + } + + @Override + public Sandstone clone() { + return (Sandstone) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Sign.java b/src/main/java/org/bukkit/material/Sign.java new file mode 100644 index 0000000..e8da7aa --- /dev/null +++ b/src/main/java/org/bukkit/material/Sign.java @@ -0,0 +1,250 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; +import org.bukkit.Material; + +/** + * MaterialData for signs + */ +public class Sign extends MaterialData implements Attachable { + public Sign() { + super(Material.SIGN_POST); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Sign(final int type) { + super(type); + } + + public Sign(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Sign(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Sign(final Material type, final byte data) { + super(type, data); + } + + /** + * Check if this sign is attached to a wall + * + * @return true if this sign is attached to a wall, false if set on top of + * a block + */ + public boolean isWallSign() { + return getItemType() == Material.WALL_SIGN; + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + if (isWallSign()) { + byte data = getData(); + + switch (data) { + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.EAST; + + case 0x5: + return BlockFace.WEST; + } + + return null; + } else { + return BlockFace.DOWN; + } + } + + /** + * Gets the direction that this sign is currently facing + * + * @return BlockFace indicating where this sign is facing + */ + public BlockFace getFacing() { + byte data = getData(); + + if (!isWallSign()) { + switch (data) { + case 0x0: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.SOUTH_SOUTH_WEST; + + case 0x2: + return BlockFace.SOUTH_WEST; + + case 0x3: + return BlockFace.WEST_SOUTH_WEST; + + case 0x4: + return BlockFace.WEST; + + case 0x5: + return BlockFace.WEST_NORTH_WEST; + + case 0x6: + return BlockFace.NORTH_WEST; + + case 0x7: + return BlockFace.NORTH_NORTH_WEST; + + case 0x8: + return BlockFace.NORTH; + + case 0x9: + return BlockFace.NORTH_NORTH_EAST; + + case 0xA: + return BlockFace.NORTH_EAST; + + case 0xB: + return BlockFace.EAST_NORTH_EAST; + + case 0xC: + return BlockFace.EAST; + + case 0xD: + return BlockFace.EAST_SOUTH_EAST; + + case 0xE: + return BlockFace.SOUTH_EAST; + + case 0xF: + return BlockFace.SOUTH_SOUTH_EAST; + } + + return null; + } else { + return getAttachedFace().getOppositeFace(); + } + } + + public void setFacingDirection(BlockFace face) { + byte data; + + if (isWallSign()) { + switch (face) { + case NORTH: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case EAST: + default: + data = 0x5; + } + } else { + switch (face) { + case SOUTH: + data = 0x0; + break; + + case SOUTH_SOUTH_WEST: + data = 0x1; + break; + + case SOUTH_WEST: + data = 0x2; + break; + + case WEST_SOUTH_WEST: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case WEST_NORTH_WEST: + data = 0x5; + break; + + case NORTH_WEST: + data = 0x6; + break; + + case NORTH_NORTH_WEST: + data = 0x7; + break; + + case NORTH: + data = 0x8; + break; + + case NORTH_NORTH_EAST: + data = 0x9; + break; + + case NORTH_EAST: + data = 0xA; + break; + + case EAST_NORTH_EAST: + data = 0xB; + break; + + case EAST: + data = 0xC; + break; + + case EAST_SOUTH_EAST: + data = 0xD; + break; + + case SOUTH_SOUTH_EAST: + data = 0xF; + break; + + case SOUTH_EAST: + default: + data = 0xE; + } + } + + setData(data); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public Sign clone() { + return (Sign) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java b/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java new file mode 100644 index 0000000..b5703c6 --- /dev/null +++ b/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java @@ -0,0 +1,66 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Simple utility class for attachable MaterialData subclasses + */ +public abstract class SimpleAttachableMaterialData extends MaterialData implements Attachable { + + /** + * + * @deprecated Magic value + */ + @Deprecated + public SimpleAttachableMaterialData(int type) { + super(type); + } + + public SimpleAttachableMaterialData(int type, BlockFace direction) { + this(type); + setFacingDirection(direction); + } + + public SimpleAttachableMaterialData(Material type, BlockFace direction) { + this(type); + setFacingDirection(direction); + } + + public SimpleAttachableMaterialData(Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public SimpleAttachableMaterialData(int type, byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public SimpleAttachableMaterialData(Material type, byte data) { + super(type, data); + } + + public BlockFace getFacing() { + BlockFace attachedFace = getAttachedFace(); + return attachedFace == null ? null : attachedFace.getOppositeFace(); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public SimpleAttachableMaterialData clone() { + return (SimpleAttachableMaterialData) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Skull.java b/src/main/java/org/bukkit/material/Skull.java new file mode 100644 index 0000000..6e0d71f --- /dev/null +++ b/src/main/java/org/bukkit/material/Skull.java @@ -0,0 +1,114 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a skull. + */ +public class Skull extends MaterialData implements Directional { + public Skull() { + super(Material.SKULL); + } + + /** + * Instantiate a skull facing in a particular direction. + * + * @param direction the direction the skull's face is facing + */ + public Skull(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Skull(final int type) { + super(type); + } + + public Skull(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Skull(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Skull(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + int data; + + switch (face) { + case SELF: + default: + data = 0x1; + break; + + case NORTH: + data = 0x2; + break; + + case EAST: + data = 0x4; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x5; + } + + setData((byte) data); + } + + public BlockFace getFacing() { + int data = getData(); + + switch (data) { + case 0x1: + default: + return BlockFace.SELF; + + case 0x2: + return BlockFace.NORTH; + + case 0x3: + return BlockFace.SOUTH; + + case 0x4: + return BlockFace.EAST; + + case 0x5: + return BlockFace.WEST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public Skull clone() { + return (Skull) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/SmoothBrick.java b/src/main/java/org/bukkit/material/SmoothBrick.java new file mode 100644 index 0000000..b7ab607 --- /dev/null +++ b/src/main/java/org/bukkit/material/SmoothBrick.java @@ -0,0 +1,68 @@ +package org.bukkit.material; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Material; + +/** + * Represents the different types of smooth bricks. + */ +public class SmoothBrick extends TexturedMaterial { + + private static final List textures = new ArrayList(); + static { + textures.add(Material.STONE); + textures.add(Material.MOSSY_COBBLESTONE); + textures.add(Material.COBBLESTONE); + textures.add(Material.SMOOTH_BRICK); + } + + public SmoothBrick() { + super(Material.SMOOTH_BRICK); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public SmoothBrick(final int type) { + super(type); + } + + public SmoothBrick(final Material type) { + super((textures.contains(type)) ? Material.SMOOTH_BRICK : type); + if (textures.contains(type)) { + setMaterial(type); + } + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public SmoothBrick(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public SmoothBrick(final Material type, final byte data) { + super(type, data); + } + + @Override + public List getTextures() { + return textures; + } + + @Override + public SmoothBrick clone() { + return (SmoothBrick) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/SpawnEgg.java b/src/main/java/org/bukkit/material/SpawnEgg.java new file mode 100644 index 0000000..ed973c5 --- /dev/null +++ b/src/main/java/org/bukkit/material/SpawnEgg.java @@ -0,0 +1,65 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +/** + * Represents a spawn egg that can be used to spawn mobs + */ +public class SpawnEgg extends MaterialData { + + public SpawnEgg() { + super(Material.MONSTER_EGG); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public SpawnEgg(int type, byte data){ + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public SpawnEgg(byte data) { + super(Material.MONSTER_EGG, data); + } + + public SpawnEgg(EntityType type) { + this(); + setSpawnedType(type); + } + + /** + * Get the type of entity this egg will spawn. + * + * @return The entity type. + */ + public EntityType getSpawnedType() { + return EntityType.fromId(getData()); + } + + /** + * Set the type of entity this egg will spawn. + * + * @param type The entity type. + */ + public void setSpawnedType(EntityType type) { + setData((byte) type.getTypeId()); + } + + @Override + public String toString() { + return "SPAWN EGG{" + getSpawnedType() + "}"; + } + + @Override + public SpawnEgg clone() { + return (SpawnEgg) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Stairs.java b/src/main/java/org/bukkit/material/Stairs.java new file mode 100644 index 0000000..1f73c77 --- /dev/null +++ b/src/main/java/org/bukkit/material/Stairs.java @@ -0,0 +1,138 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents stairs. + */ +public class Stairs extends MaterialData implements Directional { + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Stairs(final int type) { + super(type); + } + + public Stairs(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Stairs(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Stairs(final Material type, final byte data) { + super(type, data); + } + + /** + * @return the direction the stairs ascend towards + */ + public BlockFace getAscendingDirection() { + byte data = getData(); + + switch (data & 0x3) { + case 0x0: + default: + return BlockFace.EAST; + + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.NORTH; + } + } + + /** + * @return the direction the stairs descend towards + */ + public BlockFace getDescendingDirection() { + return getAscendingDirection().getOppositeFace(); + } + + /** + * Set the direction the stair part of the block is facing + */ + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case NORTH: + data = 0x3; + break; + + case SOUTH: + data = 0x2; + break; + + case EAST: + default: + data = 0x0; + break; + + case WEST: + data = 0x1; + break; + } + + setData((byte) ((getData() & 0xC) | data)); + } + + /** + * @return the direction the stair part of the block is facing + */ + public BlockFace getFacing() { + return getDescendingDirection(); + } + + /** + * Test if step is inverted + * + * @return true if inverted (top half), false if normal (bottom half) + */ + public boolean isInverted() { + return ((getData() & 0x4) != 0); + } + + /** + * Set step inverted state + * + * @param inv - true if step is inverted (top half), false if step is + * normal (bottom half) + */ + public void setInverted(boolean inv) { + int dat = getData() & 0x3; + if (inv) { + dat |= 0x4; + } + setData((byte) dat); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + (isInverted()?" inverted":""); + } + + @Override + public Stairs clone() { + return (Stairs) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Step.java b/src/main/java/org/bukkit/material/Step.java new file mode 100644 index 0000000..605f817 --- /dev/null +++ b/src/main/java/org/bukkit/material/Step.java @@ -0,0 +1,119 @@ +package org.bukkit.material; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Material; + +/** + * Represents the different types of steps. + */ +public class Step extends TexturedMaterial { + private static final List textures = new ArrayList(); + static { + textures.add(Material.STONE); + textures.add(Material.SANDSTONE); + textures.add(Material.WOOD); + textures.add(Material.COBBLESTONE); + textures.add(Material.BRICK); + textures.add(Material.SMOOTH_BRICK); + textures.add(Material.NETHER_BRICK); + textures.add(Material.QUARTZ_BLOCK); + } + + public Step() { + super(Material.STEP); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Step(final int type) { + super(type); + } + + public Step(final Material type) { + super((textures.contains(type)) ? Material.STEP : type); + if (textures.contains(type)) { + setMaterial(type); + } + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Step(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Step(final Material type, final byte data) { + super(type, data); + } + + @Override + public List getTextures() { + return textures; + } + + /** + * Test if step is inverted + * + * @return true if inverted (top half), false if normal (bottom half) + */ + public boolean isInverted() { + return ((getData() & 0x8) != 0); + } + + /** + * Set step inverted state + * + * @param inv - true if step is inverted (top half), false if step is + * normal (bottom half) + */ + public void setInverted(boolean inv) { + int dat = getData() & 0x7; + if (inv) { + dat |= 0x8; + } + setData((byte) dat); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + @Override + protected int getTextureIndex() { + return getData() & 0x7; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + @Override + protected void setTextureIndex(int idx) { + setData((byte) ((getData() & 0x8) | idx)); + } + + @Override + public Step clone() { + return (Step) super.clone(); + } + + @Override + public String toString() { + return super.toString() + (isInverted()?"inverted":""); + } +} diff --git a/src/main/java/org/bukkit/material/TexturedMaterial.java b/src/main/java/org/bukkit/material/TexturedMaterial.java new file mode 100644 index 0000000..cfd971b --- /dev/null +++ b/src/main/java/org/bukkit/material/TexturedMaterial.java @@ -0,0 +1,110 @@ +package org.bukkit.material; + +import java.util.List; + +import org.bukkit.Material; + +/** + * Represents textured materials like steps and smooth bricks + */ +public abstract class TexturedMaterial extends MaterialData { + + public TexturedMaterial(Material m) { + super(m); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public TexturedMaterial(int type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public TexturedMaterial(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public TexturedMaterial(final Material type, final byte data) { + super(type, data); + } + + /** + * Retrieve a list of possible textures. The first element of the list + * will be used as a default. + * + * @return a list of possible textures for this block + */ + public abstract List getTextures(); + + /** + * Gets the current Material this block is made of + * + * @return Material of this block + */ + public Material getMaterial() { + int n = getTextureIndex(); + if (n > getTextures().size() - 1) { + n = 0; + } + + return getTextures().get(n); + } + + /** + * Sets the material this block is made of + * + * @param material + * New material of this block + */ + public void setMaterial(Material material) { + if (getTextures().contains(material)) { + setTextureIndex(getTextures().indexOf(material)); + } else { + setTextureIndex(0x0); + } + } + + /** + * Get material index from data + * + * @return index of data in textures list + * @deprecated Magic value + */ + @Deprecated + protected int getTextureIndex() { + return getData(); // Default to using all bits - override for other mappings + } + + /** + * Set material index + * + * @param idx - index of data in textures list + * @deprecated Magic value + */ + @Deprecated + protected void setTextureIndex(int idx) { + setData((byte) idx); // Defult to using all bits - override for other mappings + } + + @Override + public String toString() { + return getMaterial() + " " + super.toString(); + } + + @Override + public TexturedMaterial clone() { + return (TexturedMaterial) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Torch.java b/src/main/java/org/bukkit/material/Torch.java new file mode 100644 index 0000000..f03b3cf --- /dev/null +++ b/src/main/java/org/bukkit/material/Torch.java @@ -0,0 +1,104 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; +import org.bukkit.Material; + +/** + * MaterialData for torches + */ +public class Torch extends SimpleAttachableMaterialData { + public Torch() { + super(Material.TORCH); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Torch(final int type) { + super(type); + } + + public Torch(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Torch(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Torch(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + byte data = getData(); + + switch (data) { + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.SOUTH; + + case 0x5: + default: + return BlockFace.DOWN; + } + } + + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case EAST: + data = 0x1; + break; + + case WEST: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case NORTH: + data = 0x4; + break; + + case UP: + default: + data = 0x5; + } + + setData(data); + } + + @Override + public Torch clone() { + return (Torch) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/TrapDoor.java b/src/main/java/org/bukkit/material/TrapDoor.java new file mode 100644 index 0000000..bd4bcc2 --- /dev/null +++ b/src/main/java/org/bukkit/material/TrapDoor.java @@ -0,0 +1,131 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a trap door + */ +public class TrapDoor extends SimpleAttachableMaterialData implements Openable { + public TrapDoor() { + super(Material.TRAP_DOOR); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public TrapDoor(final int type) { + super(type); + } + + public TrapDoor(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public TrapDoor(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public TrapDoor(final Material type, final byte data) { + super(type, data); + } + + public boolean isOpen() { + return ((getData() & 0x4) == 0x4); + } + + public void setOpen(boolean isOpen) { + byte data = getData(); + + if (isOpen) { + data |= 0x4; + } else { + data &= ~0x4; + } + + setData(data); + } + + /** + * Test if trapdoor is inverted + * + * @return true if inverted (top half), false if normal (bottom half) + */ + public boolean isInverted() { + return ((getData() & 0x8) != 0); + } + + /** + * Set trapdoor inverted state + * + * @param inv - true if inverted (top half), false if normal (bottom half) + */ + public void setInverted(boolean inv) { + int dat = getData() & 0x7; + if (inv) { + dat |= 0x8; + } + setData((byte) dat); + } + + public BlockFace getAttachedFace() { + byte data = (byte) (getData() & 0x3); + + switch (data) { + case 0x0: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.NORTH; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.WEST; + } + + return null; + + } + + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0xC); + + switch (face) { + case SOUTH: + data |= 0x1; + break; + case WEST: + data |= 0x2; + break; + case EAST: + data |= 0x3; + break; + } + + setData(data); + } + + @Override + public String toString() { + return (isOpen() ? "OPEN " : "CLOSED ") + super.toString() + " with hinges set " + getAttachedFace() + (isInverted() ? " inverted" : ""); + } + + @Override + public TrapDoor clone() { + return (TrapDoor) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Tree.java b/src/main/java/org/bukkit/material/Tree.java new file mode 100644 index 0000000..fe56872 --- /dev/null +++ b/src/main/java/org/bukkit/material/Tree.java @@ -0,0 +1,136 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.TreeSpecies; +import org.bukkit.block.BlockFace; + +/** + * Represents the different types of Trees. + */ +public class Tree extends MaterialData { + public Tree() { + super(Material.LOG); + } + + public Tree(TreeSpecies species) { + this(); + setSpecies(species); + } + + public Tree(TreeSpecies species, BlockFace dir) { + this(); + setSpecies(species); + setDirection(dir); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Tree(final int type) { + super(type); + } + + public Tree(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Tree(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Tree(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current species of this tree + * + * @return TreeSpecies of this tree + */ + public TreeSpecies getSpecies() { + return TreeSpecies.getByData((byte) (getData() & 0x3)); + } + + /** + * Sets the species of this tree + * + * @param species New species of this tree + */ + public void setSpecies(TreeSpecies species) { + setData((byte) ((getData() & 0xC) | species.getData())); + } + + /** + * Get direction of the log + * + * @return one of: + *

            + *
          • BlockFace.TOP for upright (default) + *
          • BlockFace.NORTH (east-west) + *
          • BlockFace.WEST (north-south) + *
          • BlockFace.SELF (directionless) + *
          + */ + public BlockFace getDirection() { + switch ((getData() >> 2) & 0x3) { + case 0: // Up-down + default: + return BlockFace.UP; + case 1: // North-south + return BlockFace.WEST; + case 2: // East-west + return BlockFace.NORTH; + case 3: // Directionless (bark on all sides) + return BlockFace.SELF; + } + } + /** + * Set direction of the log + * + * @param dir - direction of end of log (BlockFace.SELF for no direction) + */ + public void setDirection(BlockFace dir) { + int dat; + switch (dir) { + case UP: + case DOWN: + default: + dat = 0; + break; + case WEST: + case EAST: + dat = 1; + break; + case NORTH: + case SOUTH: + dat = 2; + break; + case SELF: + dat = 3; + break; + } + setData((byte) ((getData() & 0x3) | (dat << 2))); + } + + @Override + public String toString() { + return getSpecies() + " " + getDirection() + " " + super.toString(); + } + + @Override + public Tree clone() { + return (Tree) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/Tripwire.java b/src/main/java/org/bukkit/material/Tripwire.java new file mode 100644 index 0000000..583860b --- /dev/null +++ b/src/main/java/org/bukkit/material/Tripwire.java @@ -0,0 +1,85 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents the tripwire + */ +public class Tripwire extends MaterialData { + + public Tripwire() { + super(Material.TRIPWIRE); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Tripwire(final int type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Tripwire(final int type, final byte data) { + super(type, data); + } + + /** + * Test if tripwire is currently activated + * + * @return true if activated, false if not + */ + public boolean isActivated() { + return (getData() & 0x4) != 0; + } + + /** + * Set tripwire activated state + * + * @param act - true if activated, false if not + */ + public void setActivated(boolean act) { + int dat = getData() & (0x8 | 0x3); + if (act) { + dat |= 0x4; + } + setData((byte) dat); + } + + /** + * Test if object triggering this tripwire directly + * + * @return true if object activating tripwire, false if not + */ + public boolean isObjectTriggering() { + return (getData() & 0x1) != 0; + } + + /** + * Set object triggering state for this tripwire + * + * @param trig - true if object activating tripwire, false if not + */ + public void setObjectTriggering(boolean trig) { + int dat = getData() & 0xE; + if (trig) { + dat |= 0x1; + } + setData((byte) dat); + } + + @Override + public Tripwire clone() { + return (Tripwire) super.clone(); + } + + @Override + public String toString() { + return super.toString() + (isActivated()?" Activated":"") + (isObjectTriggering()?" Triggered":""); + } +} diff --git a/src/main/java/org/bukkit/material/TripwireHook.java b/src/main/java/org/bukkit/material/TripwireHook.java new file mode 100644 index 0000000..7ad2d2a --- /dev/null +++ b/src/main/java/org/bukkit/material/TripwireHook.java @@ -0,0 +1,128 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents the tripwire hook + */ +public class TripwireHook extends SimpleAttachableMaterialData implements Redstone { + + public TripwireHook() { + super(Material.TRIPWIRE_HOOK); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public TripwireHook(final int type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public TripwireHook(final int type, final byte data) { + super(type, data); + } + + public TripwireHook(BlockFace dir) { + this(); + setFacingDirection(dir); + } + + /** + * Test if tripwire is connected + * + * @return true if connected, false if not + */ + public boolean isConnected() { + return (getData() & 0x4) != 0; + } + + /** + * Set tripwire connection state + * + * @param connected - true if connected, false if not + */ + public void setConnected(boolean connected) { + int dat = getData() & (0x8 | 0x3); + if (connected) { + dat |= 0x4; + } + setData((byte) dat); + } + + /** + * Test if hook is currently activated + * + * @return true if activated, false if not + */ + public boolean isActivated() { + return (getData() & 0x8) != 0; + } + + /** + * Set hook activated state + * + * @param act - true if activated, false if not + */ + public void setActivated(boolean act) { + int dat = getData() & (0x4 | 0x3); + if (act) { + dat |= 0x8; + } + setData((byte) dat); + } + + public void setFacingDirection(BlockFace face) { + int dat = getData() & 0xC; + switch (face) { + case WEST: + dat |= 0x1; + break; + case NORTH: + dat |= 0x2; + break; + case EAST: + dat |= 0x3; + break; + case SOUTH: + default: + break; + } + setData((byte) dat); + } + + public BlockFace getAttachedFace() { + switch (getData() & 0x3) { + case 0: + return BlockFace.NORTH; + case 1: + return BlockFace.EAST; + case 2: + return BlockFace.SOUTH; + case 3: + return BlockFace.WEST; + } + return null; + } + + public boolean isPowered() { + return isActivated(); + } + + @Override + public TripwireHook clone() { + return (TripwireHook) super.clone(); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + (isActivated()?" Activated":"") + (isConnected()?" Connected":""); + } +} diff --git a/src/main/java/org/bukkit/material/Vine.java b/src/main/java/org/bukkit/material/Vine.java new file mode 100644 index 0000000..a4f7ad5 --- /dev/null +++ b/src/main/java/org/bukkit/material/Vine.java @@ -0,0 +1,196 @@ +package org.bukkit.material; + +import java.util.Arrays; +import java.util.EnumSet; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a vine + */ +public class Vine extends MaterialData { + private static final int VINE_NORTH = 0x4; + private static final int VINE_EAST = 0x8; + private static final int VINE_WEST = 0x2; + private static final int VINE_SOUTH = 0x1; + EnumSet possibleFaces = EnumSet.of(BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST); + + public Vine() { + super(Material.VINE); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Vine(int type, byte data){ + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Vine(byte data) { + super(Material.VINE, data); + } + + public Vine(BlockFace... faces) { + this(EnumSet.copyOf(Arrays.asList(faces))); + } + + public Vine(EnumSet faces) { + this((byte) 0); + faces.retainAll(possibleFaces); + + byte data = 0; + + if (faces.contains(BlockFace.WEST)) { + data |= VINE_WEST; + } + + if (faces.contains(BlockFace.NORTH)) { + data |= VINE_NORTH; + } + + if (faces.contains(BlockFace.SOUTH)) { + data |= VINE_SOUTH; + } + + if (faces.contains(BlockFace.EAST)) { + data |= VINE_EAST; + } + + setData(data); + } + + /** + * Check if the vine is attached to the specified face of an adjacent + * block. You can check two faces at once by passing e.g. {@link + * BlockFace#NORTH_EAST}. + * + * @param face The face to check. + * @return Whether it is attached to that face. + */ + public boolean isOnFace(BlockFace face) { + switch (face) { + case WEST: + return (getData() & VINE_WEST) == VINE_WEST; + case NORTH: + return (getData() & VINE_NORTH) == VINE_NORTH; + case SOUTH: + return (getData() & VINE_SOUTH) == VINE_SOUTH; + case EAST: + return (getData() & VINE_EAST) == VINE_EAST; + case NORTH_EAST: + return isOnFace(BlockFace.EAST) && isOnFace(BlockFace.NORTH); + case NORTH_WEST: + return isOnFace(BlockFace.WEST) && isOnFace(BlockFace.NORTH); + case SOUTH_EAST: + return isOnFace(BlockFace.EAST) && isOnFace(BlockFace.SOUTH); + case SOUTH_WEST: + return isOnFace(BlockFace.WEST) && isOnFace(BlockFace.SOUTH); + case UP: // It's impossible to be accurate with this since it's contextual + return true; + default: + return false; + } + } + + /** + * Attach the vine to the specified face of an adjacent block. + * + * @param face The face to attach. + */ + public void putOnFace(BlockFace face) { + switch(face) { + case WEST: + setData((byte) (getData() | VINE_WEST)); + break; + case NORTH: + setData((byte) (getData() | VINE_NORTH)); + break; + case SOUTH: + setData((byte) (getData() | VINE_SOUTH)); + break; + case EAST: + setData((byte) (getData() | VINE_EAST)); + break; + case NORTH_WEST: + putOnFace(BlockFace.WEST); + putOnFace(BlockFace.NORTH); + break; + case SOUTH_WEST: + putOnFace(BlockFace.WEST); + putOnFace(BlockFace.SOUTH); + break; + case NORTH_EAST: + putOnFace(BlockFace.EAST); + putOnFace(BlockFace.NORTH); + break; + case SOUTH_EAST: + putOnFace(BlockFace.EAST); + putOnFace(BlockFace.SOUTH); + break; + case UP: + break; + default: + throw new IllegalArgumentException("Vines can't go on face " + face.toString()); + } + } + + /** + * Detach the vine from the specified face of an adjacent block. + * + * @param face The face to detach. + */ + public void removeFromFace(BlockFace face) { + switch(face) { + case WEST: + setData((byte) (getData() & ~VINE_WEST)); + break; + case NORTH: + setData((byte) (getData() & ~VINE_NORTH)); + break; + case SOUTH: + setData((byte) (getData() & ~VINE_SOUTH)); + break; + case EAST: + setData((byte) (getData() & ~VINE_EAST)); + break; + case NORTH_WEST: + removeFromFace(BlockFace.WEST); + removeFromFace(BlockFace.NORTH); + break; + case SOUTH_WEST: + removeFromFace(BlockFace.WEST); + removeFromFace(BlockFace.SOUTH); + break; + case NORTH_EAST: + removeFromFace(BlockFace.EAST); + removeFromFace(BlockFace.NORTH); + break; + case SOUTH_EAST: + removeFromFace(BlockFace.EAST); + removeFromFace(BlockFace.SOUTH); + break; + case UP: + break; + default: + throw new IllegalArgumentException("Vines can't go on face " + face.toString()); + } + } + + @Override + public String toString() { + return "VINE"; + } + + @Override + public Vine clone() { + return (Vine) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/material/WoodenStep.java b/src/main/java/org/bukkit/material/WoodenStep.java new file mode 100644 index 0000000..9584e25 --- /dev/null +++ b/src/main/java/org/bukkit/material/WoodenStep.java @@ -0,0 +1,103 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.TreeSpecies; + +/** + * Represents the different types of wooden steps. + */ +public class WoodenStep extends MaterialData { + + public WoodenStep() { + super(Material.WOOD_STEP); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public WoodenStep(final int type) { + super(type); + } + + public WoodenStep(TreeSpecies species) { + this(); + setSpecies(species); + } + + public WoodenStep(TreeSpecies species, boolean inv) { + this(); + setSpecies(species); + setInverted(inv); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public WoodenStep(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public WoodenStep(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current species of this tree + * + * @return TreeSpecies of this tree + */ + public TreeSpecies getSpecies() { + return TreeSpecies.getByData((byte) (getData() & 0x3)); + } + + /** + * Sets the species of this tree + * + * @param species New species of this tree + */ + public void setSpecies(TreeSpecies species) { + setData((byte) ((getData() & 0xC) | species.getData())); + } + + /** + * Test if step is inverted + * + * @return true if inverted (top half), false if normal (bottom half) + */ + public boolean isInverted() { + return ((getData() & 0x8) != 0); + } + + /** + * Set step inverted state + * + * @param inv - true if step is inverted (top half), false if step is + * normal (bottom half) + */ + public void setInverted(boolean inv) { + int dat = getData() & 0x7; + if (inv) { + dat |= 0x8; + } + setData((byte) dat); + } + + @Override + public WoodenStep clone() { + return (WoodenStep) super.clone(); + } + + @Override + public String toString() { + return super.toString() + " " + getSpecies() + (isInverted()?" inverted":""); + } +} diff --git a/src/main/java/org/bukkit/material/Wool.java b/src/main/java/org/bukkit/material/Wool.java new file mode 100644 index 0000000..8115bdc --- /dev/null +++ b/src/main/java/org/bukkit/material/Wool.java @@ -0,0 +1,77 @@ +package org.bukkit.material; + +import org.bukkit.DyeColor; +import org.bukkit.Material; + +/** + * Represents a Wool/Cloth block + */ +public class Wool extends MaterialData implements Colorable { + public Wool() { + super(Material.WOOL); + } + + public Wool(DyeColor color) { + this(); + setColor(color); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Wool(final int type) { + super(type); + } + + public Wool(final Material type) { + super(type); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Wool(final int type, final byte data) { + super(type, data); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public Wool(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current color of this dye + * + * @return DyeColor of this dye + */ + public DyeColor getColor() { + return DyeColor.getByWoolData(getData()); + } + + /** + * Sets the color of this dye + * + * @param color New color of this dye + */ + public void setColor(DyeColor color) { + setData(color.getWoolData()); + } + + @Override + public String toString() { + return getColor() + " " + super.toString(); + } + + @Override + public Wool clone() { + return (Wool) super.clone(); + } +} diff --git a/src/main/java/org/bukkit/metadata/FixedMetadataValue.java b/src/main/java/org/bukkit/metadata/FixedMetadataValue.java new file mode 100644 index 0000000..bce6f00 --- /dev/null +++ b/src/main/java/org/bukkit/metadata/FixedMetadataValue.java @@ -0,0 +1,43 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; + +import java.util.concurrent.Callable; + +/** + * A FixedMetadataValue is a special case metadata item that contains the same + * value forever after initialization. Invalidating a FixedMetadataValue has + * no effect. + *

          + * This class extends LazyMetadataValue for historical reasons, even though it + * overrides all the implementation methods. it is possible that in the future + * that the inheritance hierarchy may change. + */ +public class FixedMetadataValue extends LazyMetadataValue { + + /** + * Store the internal value that is represented by this fixed value. + */ + private final Object internalValue; + + /** + * Initializes a FixedMetadataValue with an Object + * + * @param owningPlugin the {@link Plugin} that created this metadata value + * @param value the value assigned to this metadata value + */ + public FixedMetadataValue(Plugin owningPlugin, final Object value) { + super(owningPlugin); + this.internalValue = value; + } + + @Override + public void invalidate() { + + } + + @Override + public Object value() { + return internalValue; + } +} diff --git a/src/main/java/org/bukkit/metadata/LazyMetadataValue.java b/src/main/java/org/bukkit/metadata/LazyMetadataValue.java new file mode 100644 index 0000000..a9546e5 --- /dev/null +++ b/src/main/java/org/bukkit/metadata/LazyMetadataValue.java @@ -0,0 +1,120 @@ +package org.bukkit.metadata; + +import java.lang.ref.SoftReference; +import java.util.concurrent.Callable; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.Plugin; + +/** + * The LazyMetadataValue class implements a type of metadata that is not + * computed until another plugin asks for it. + *

          + * By making metadata values lazy, no computation is done by the providing + * plugin until absolutely necessary (if ever). Additionally, + * LazyMetadataValue objects cache their values internally unless overridden + * by a {@link CacheStrategy} or invalidated at the individual or plugin + * level. Once invalidated, the LazyMetadataValue will recompute its value + * when asked. + */ +public class LazyMetadataValue extends MetadataValueAdapter implements MetadataValue { + private Callable lazyValue; + private CacheStrategy cacheStrategy; + private SoftReference internalValue; + private static final Object ACTUALLY_NULL = new Object(); + + /** + * Initialized a LazyMetadataValue object with the default + * CACHE_AFTER_FIRST_EVAL cache strategy. + * + * @param owningPlugin the {@link Plugin} that created this metadata + * value. + * @param lazyValue the lazy value assigned to this metadata value. + */ + public LazyMetadataValue(Plugin owningPlugin, Callable lazyValue) { + this(owningPlugin, CacheStrategy.CACHE_AFTER_FIRST_EVAL, lazyValue); + } + + /** + * Initializes a LazyMetadataValue object with a specific cache strategy. + * + * @param owningPlugin the {@link Plugin} that created this metadata + * value. + * @param cacheStrategy determines the rules for caching this metadata + * value. + * @param lazyValue the lazy value assigned to this metadata value. + */ + public LazyMetadataValue(Plugin owningPlugin, CacheStrategy cacheStrategy, Callable lazyValue) { + super(owningPlugin); + Validate.notNull(cacheStrategy, "cacheStrategy cannot be null"); + Validate.notNull(lazyValue, "lazyValue cannot be null"); + this.internalValue = new SoftReference(null); + this.lazyValue = lazyValue; + this.cacheStrategy = cacheStrategy; + } + + /** + * Protected special constructor used by FixedMetadataValue to bypass + * standard setup. + */ + protected LazyMetadataValue(Plugin owningPlugin) { + super(owningPlugin); + } + + public Object value() { + eval(); + Object value = internalValue.get(); + if (value == ACTUALLY_NULL) { + return null; + } + return value; + } + + /** + * Lazily evaluates the value of this metadata item. + * + * @throws MetadataEvaluationException if computing the metadata value + * fails. + */ + private synchronized void eval() throws MetadataEvaluationException { + if (cacheStrategy == CacheStrategy.NEVER_CACHE || internalValue.get() == null) { + try { + Object value = lazyValue.call(); + if (value == null) { + value = ACTUALLY_NULL; + } + internalValue = new SoftReference(value); + } catch (Exception e) { + throw new MetadataEvaluationException(e); + } + } + } + + public synchronized void invalidate() { + if (cacheStrategy != CacheStrategy.CACHE_ETERNALLY) { + internalValue.clear(); + } + } + + /** + * Describes possible caching strategies for metadata. + */ + public enum CacheStrategy { + /** + * Once the metadata value has been evaluated, do not re-evaluate the + * value until it is manually invalidated. + */ + CACHE_AFTER_FIRST_EVAL, + + /** + * Re-evaluate the metadata item every time it is requested + */ + NEVER_CACHE, + + /** + * Once the metadata value has been evaluated, do not re-evaluate the + * value in spite of manual invalidation. + */ + CACHE_ETERNALLY + } +} diff --git a/src/main/java/org/bukkit/metadata/MetadataConversionException.java b/src/main/java/org/bukkit/metadata/MetadataConversionException.java new file mode 100644 index 0000000..a3def46 --- /dev/null +++ b/src/main/java/org/bukkit/metadata/MetadataConversionException.java @@ -0,0 +1,13 @@ +package org.bukkit.metadata; + +/** + * A MetadataConversionException is thrown any time a {@link + * LazyMetadataValue} attempts to convert a metadata value to an inappropriate + * data type. + */ +@SuppressWarnings("serial") +public class MetadataConversionException extends RuntimeException { + MetadataConversionException(String message) { + super(message); + } +} diff --git a/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java b/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java new file mode 100644 index 0000000..918e7c8 --- /dev/null +++ b/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java @@ -0,0 +1,13 @@ +package org.bukkit.metadata; + +/** + * A MetadataEvaluationException is thrown any time a {@link + * LazyMetadataValue} fails to evaluate its value due to an exception. The + * originating exception will be included as this exception's cause. + */ +@SuppressWarnings("serial") +public class MetadataEvaluationException extends RuntimeException { + MetadataEvaluationException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/org/bukkit/metadata/MetadataStore.java b/src/main/java/org/bukkit/metadata/MetadataStore.java new file mode 100644 index 0000000..700d0bf --- /dev/null +++ b/src/main/java/org/bukkit/metadata/MetadataStore.java @@ -0,0 +1,60 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; + +import java.util.List; + +public interface MetadataStore { + /** + * Adds a metadata value to an object. + * + * @param subject The object receiving the metadata. + * @param metadataKey A unique key to identify this metadata. + * @param newMetadataValue The metadata value to apply. + * @throws IllegalArgumentException If value is null, or the owning plugin + * is null + */ + public void setMetadata(T subject, String metadataKey, MetadataValue newMetadataValue); + + /** + * Returns all metadata values attached to an object. If multiple plugins + * have attached metadata, each will value will be included. + * + * @param subject the object being interrogated. + * @param metadataKey the unique metadata key being sought. + * @return A list of values, one for each plugin that has set the + * requested value. + */ + public List getMetadata(T subject, String metadataKey); + + /** + * Tests to see if a metadata attribute has been set on an object. + * + * @param subject the object upon which the has-metadata test is + * performed. + * @param metadataKey the unique metadata key being queried. + * @return the existence of the metadataKey within subject. + */ + public boolean hasMetadata(T subject, String metadataKey); + + /** + * Removes a metadata item owned by a plugin from a subject. + * + * @param subject the object to remove the metadata from. + * @param metadataKey the unique metadata key identifying the metadata to + * remove. + * @param owningPlugin the plugin attempting to remove a metadata item. + * @throws IllegalArgumentException If plugin is null + */ + public void removeMetadata(T subject, String metadataKey, Plugin owningPlugin); + + /** + * Invalidates all metadata in the metadata store that originates from the + * given plugin. Doing this will force each invalidated metadata item to + * be recalculated the next time it is accessed. + * + * @param owningPlugin the plugin requesting the invalidation. + * @throws IllegalArgumentException If plugin is null + */ + public void invalidateAll(Plugin owningPlugin); +} diff --git a/src/main/java/org/bukkit/metadata/MetadataStoreBase.java b/src/main/java/org/bukkit/metadata/MetadataStoreBase.java new file mode 100644 index 0000000..093c144 --- /dev/null +++ b/src/main/java/org/bukkit/metadata/MetadataStoreBase.java @@ -0,0 +1,136 @@ +package org.bukkit.metadata; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.Plugin; + +import java.util.*; + +public abstract class MetadataStoreBase { + private Map> metadataMap = new HashMap>(); + + /** + * Adds a metadata value to an object. Each metadata value is owned by a + * specific {@link Plugin}. If a plugin has already added a metadata value + * to an object, that value will be replaced with the value of {@code + * newMetadataValue}. Multiple plugins can set independent values for the + * same {@code metadataKey} without conflict. + *

          + * Implementation note: I considered using a {@link + * java.util.concurrent.locks.ReadWriteLock} for controlling access to + * {@code metadataMap}, but decided that the added overhead wasn't worth + * the finer grained access control. + *

          + * Bukkit is almost entirely single threaded so locking overhead shouldn't + * pose a problem. + * + * @param subject The object receiving the metadata. + * @param metadataKey A unique key to identify this metadata. + * @param newMetadataValue The metadata value to apply. + * @see MetadataStore#setMetadata(Object, String, MetadataValue) + * @throws IllegalArgumentException If value is null, or the owning plugin + * is null + */ + public synchronized void setMetadata(T subject, String metadataKey, MetadataValue newMetadataValue) { + Validate.notNull(newMetadataValue, "Value cannot be null"); + Plugin owningPlugin = newMetadataValue.getOwningPlugin(); + Validate.notNull(owningPlugin, "Plugin cannot be null"); + String key = disambiguate(subject, metadataKey); + Map entry = metadataMap.get(key); + if (entry == null) { + entry = new WeakHashMap(1); + metadataMap.put(key, entry); + } + entry.put(owningPlugin, newMetadataValue); + } + + /** + * Returns all metadata values attached to an object. If multiple + * have attached metadata, each will value will be included. + * + * @param subject the object being interrogated. + * @param metadataKey the unique metadata key being sought. + * @return A list of values, one for each plugin that has set the + * requested value. + * @see MetadataStore#getMetadata(Object, String) + */ + public synchronized List getMetadata(T subject, String metadataKey) { + String key = disambiguate(subject, metadataKey); + if (metadataMap.containsKey(key)) { + Collection values = metadataMap.get(key).values(); + return Collections.unmodifiableList(new ArrayList(values)); + } else { + return Collections.emptyList(); + } + } + + /** + * Tests to see if a metadata attribute has been set on an object. + * + * @param subject the object upon which the has-metadata test is + * performed. + * @param metadataKey the unique metadata key being queried. + * @return the existence of the metadataKey within subject. + */ + public synchronized boolean hasMetadata(T subject, String metadataKey) { + String key = disambiguate(subject, metadataKey); + return metadataMap.containsKey(key); + } + + /** + * Removes a metadata item owned by a plugin from a subject. + * + * @param subject the object to remove the metadata from. + * @param metadataKey the unique metadata key identifying the metadata to + * remove. + * @param owningPlugin the plugin attempting to remove a metadata item. + * @see MetadataStore#removeMetadata(Object, String, + * org.bukkit.plugin.Plugin) + * @throws IllegalArgumentException If plugin is null + */ + public synchronized void removeMetadata(T subject, String metadataKey, Plugin owningPlugin) { + Validate.notNull(owningPlugin, "Plugin cannot be null"); + String key = disambiguate(subject, metadataKey); + Map entry = metadataMap.get(key); + if (entry == null) { + return; + } + + entry.remove(owningPlugin); + if (entry.isEmpty()) { + metadataMap.remove(key); + } + } + + /** + * Invalidates all metadata in the metadata store that originates from the + * given plugin. Doing this will force each invalidated metadata item to + * be recalculated the next time it is accessed. + * + * @param owningPlugin the plugin requesting the invalidation. + * @see MetadataStore#invalidateAll(org.bukkit.plugin.Plugin) + * @throws IllegalArgumentException If plugin is null + */ + public synchronized void invalidateAll(Plugin owningPlugin) { + Validate.notNull(owningPlugin, "Plugin cannot be null"); + for (Map values : metadataMap.values()) { + if (values.containsKey(owningPlugin)) { + values.get(owningPlugin).invalidate(); + } + } + } + + /** + * Creates a unique name for the object receiving metadata by combining + * unique data from the subject with a metadataKey. + *

          + * The name created must be globally unique for the given object and any + * two equivalent objects must generate the same unique name. For example, + * two Player objects must generate the same string if they represent the + * same player, even if the objects would fail a reference equality test. + * + * @param subject The object for which this key is being generated. + * @param metadataKey The name identifying the metadata value. + * @return a unique metadata key for the given subject. + */ + protected abstract String disambiguate(T subject, String metadataKey); +} diff --git a/src/main/java/org/bukkit/metadata/MetadataValue.java b/src/main/java/org/bukkit/metadata/MetadataValue.java new file mode 100644 index 0000000..eded8c0 --- /dev/null +++ b/src/main/java/org/bukkit/metadata/MetadataValue.java @@ -0,0 +1,83 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; + +public interface MetadataValue { + + /** + * Fetches the value of this metadata item. + * + * @return the metadata value. + */ + public Object value(); + + /** + * Attempts to convert the value of this metadata item into an int. + * + * @return the value as an int. + */ + public int asInt(); + + /** + * Attempts to convert the value of this metadata item into a float. + * + * @return the value as a float. + */ + public float asFloat(); + + /** + * Attempts to convert the value of this metadata item into a double. + * + * @return the value as a double. + */ + public double asDouble(); + + /** + * Attempts to convert the value of this metadata item into a long. + * + * @return the value as a long. + */ + public long asLong(); + + /** + * Attempts to convert the value of this metadata item into a short. + * + * @return the value as a short. + */ + public short asShort(); + + /** + * Attempts to convert the value of this metadata item into a byte. + * + * @return the value as a byte. + */ + public byte asByte(); + + /** + * Attempts to convert the value of this metadata item into a boolean. + * + * @return the value as a boolean. + */ + public boolean asBoolean(); + + /** + * Attempts to convert the value of this metadata item into a string. + * + * @return the value as a string. + */ + public String asString(); + + /** + * Returns the {@link Plugin} that created this metadata item. + * + * @return the plugin that owns this metadata value. This should never be + * null. + */ + public Plugin getOwningPlugin(); + + /** + * Invalidates this metadata item, forcing it to recompute when next + * accessed. + */ + public void invalidate(); +} diff --git a/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java b/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java new file mode 100644 index 0000000..bbc3da8 --- /dev/null +++ b/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java @@ -0,0 +1,78 @@ +package org.bukkit.metadata; + +import java.lang.ref.WeakReference; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.Plugin; +import org.bukkit.util.NumberConversions; + +/** + * Optional base class for facilitating MetadataValue implementations. + *

          + * This provides all the conversion functions for MetadataValue so that + * writing an implementation of MetadataValue is as simple as implementing + * value() and invalidate(). + */ +public abstract class MetadataValueAdapter implements MetadataValue { + protected final WeakReference owningPlugin; + + protected MetadataValueAdapter(Plugin owningPlugin) { + Validate.notNull(owningPlugin, "owningPlugin cannot be null"); + this.owningPlugin = new WeakReference(owningPlugin); + } + + public Plugin getOwningPlugin() { + return owningPlugin.get(); + } + + public int asInt() { + return NumberConversions.toInt(value()); + } + + public float asFloat() { + return NumberConversions.toFloat(value()); + } + + public double asDouble() { + return NumberConversions.toDouble(value()); + } + + public long asLong() { + return NumberConversions.toLong(value()); + } + + public short asShort() { + return NumberConversions.toShort(value()); + } + + public byte asByte() { + return NumberConversions.toByte(value()); + } + + public boolean asBoolean() { + Object value = value(); + if (value instanceof Boolean) { + return (Boolean) value; + } + + if (value instanceof Number) { + return ((Number) value).intValue() != 0; + } + + if (value instanceof String) { + return Boolean.parseBoolean((String) value); + } + + return value != null; + } + + public String asString() { + Object value = value(); + + if (value == null) { + return ""; + } + return value.toString(); + } + +} diff --git a/src/main/java/org/bukkit/metadata/Metadatable.java b/src/main/java/org/bukkit/metadata/Metadatable.java new file mode 100644 index 0000000..b47cf2b --- /dev/null +++ b/src/main/java/org/bukkit/metadata/Metadatable.java @@ -0,0 +1,52 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; + +import java.util.List; + +/** + * This interface is implemented by all objects that can provide metadata + * about themselves. + */ +public interface Metadatable { + /** + * Sets a metadata value in the implementing object's metadata store. + * + * @param metadataKey A unique key to identify this metadata. + * @param newMetadataValue The metadata value to apply. + * @throws IllegalArgumentException If value is null, or the owning plugin + * is null + */ + public void setMetadata(String metadataKey, MetadataValue newMetadataValue); + + /** + * Returns a list of previously set metadata values from the implementing + * object's metadata store. + * + * @param metadataKey the unique metadata key being sought. + * @return A list of values, one for each plugin that has set the + * requested value. + */ + public List getMetadata(String metadataKey); + + /** + * Tests to see whether the implementing object contains the given + * metadata value in its metadata store. + * + * @param metadataKey the unique metadata key being queried. + * @return the existence of the metadataKey within subject. + */ + public boolean hasMetadata(String metadataKey); + + /** + * Removes the given metadata value from the implementing object's + * metadata store. + * + * @param metadataKey the unique metadata key identifying the metadata to + * remove. + * @param owningPlugin This plugin's metadata value will be removed. All + * other values will be left untouched. + * @throws IllegalArgumentException If plugin is null + */ + public void removeMetadata(String metadataKey, Plugin owningPlugin); +} diff --git a/src/main/java/org/bukkit/permissions/Permissible.java b/src/main/java/org/bukkit/permissions/Permissible.java new file mode 100644 index 0000000..5cd3cff --- /dev/null +++ b/src/main/java/org/bukkit/permissions/Permissible.java @@ -0,0 +1,122 @@ +package org.bukkit.permissions; + +import java.util.Set; +import org.bukkit.plugin.Plugin; + +/** + * Represents an object that may be assigned permissions + */ +public interface Permissible extends ServerOperator { + + /** + * Checks if this object contains an override for the specified + * permission, by fully qualified name + * + * @param name Name of the permission + * @return true if the permission is set, otherwise false + */ + public boolean isPermissionSet(String name); + + /** + * Checks if this object contains an override for the specified {@link + * Permission} + * + * @param perm Permission to check + * @return true if the permission is set, otherwise false + */ + public boolean isPermissionSet(Permission perm); + + /** + * Gets the value of the specified permission, if set. + *

          + * If a permission override is not set on this object, the default value + * of the permission will be returned. + * + * @param name Name of the permission + * @return Value of the permission + */ + public boolean hasPermission(String name); + + /** + * Gets the value of the specified permission, if set. + *

          + * If a permission override is not set on this object, the default value + * of the permission will be returned + * + * @param perm Permission to get + * @return Value of the permission + */ + public boolean hasPermission(Permission perm); + + /** + * Adds a new {@link PermissionAttachment} with a single permission by + * name and value + * + * @param plugin Plugin responsible for this attachment, may not be null + * or disabled + * @param name Name of the permission to attach + * @param value Value of the permission + * @return The PermissionAttachment that was just created + */ + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value); + + /** + * Adds a new empty {@link PermissionAttachment} to this object + * + * @param plugin Plugin responsible for this attachment, may not be null + * or disabled + * @return The PermissionAttachment that was just created + */ + public PermissionAttachment addAttachment(Plugin plugin); + + /** + * Temporarily adds a new {@link PermissionAttachment} with a single + * permission by name and value + * + * @param plugin Plugin responsible for this attachment, may not be null + * or disabled + * @param name Name of the permission to attach + * @param value Value of the permission + * @param ticks Amount of ticks to automatically remove this attachment + * after + * @return The PermissionAttachment that was just created + */ + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks); + + /** + * Temporarily adds a new empty {@link PermissionAttachment} to this + * object + * + * @param plugin Plugin responsible for this attachment, may not be null + * or disabled + * @param ticks Amount of ticks to automatically remove this attachment + * after + * @return The PermissionAttachment that was just created + */ + public PermissionAttachment addAttachment(Plugin plugin, int ticks); + + /** + * Removes the given {@link PermissionAttachment} from this object + * + * @param attachment Attachment to remove + * @throws IllegalArgumentException Thrown when the specified attachment + * isn't part of this object + */ + public void removeAttachment(PermissionAttachment attachment); + + /** + * Recalculates the permissions for this object, if the attachments have + * changed values. + *

          + * This should very rarely need to be called from a plugin. + */ + public void recalculatePermissions(); + + /** + * Gets a set containing all of the permissions currently in effect by + * this object + * + * @return Set of currently effective permissions + */ + public Set getEffectivePermissions(); +} diff --git a/src/main/java/org/bukkit/permissions/PermissibleBase.java b/src/main/java/org/bukkit/permissions/PermissibleBase.java new file mode 100644 index 0000000..3b95061 --- /dev/null +++ b/src/main/java/org/bukkit/permissions/PermissibleBase.java @@ -0,0 +1,246 @@ +package org.bukkit.permissions; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +/** + * Base Permissible for use in any Permissible object via proxy or extension + */ +public class PermissibleBase implements Permissible { + private ServerOperator opable = null; + private Permissible parent = this; + private final List attachments = new LinkedList(); + private final Map permissions = new HashMap(); + + public PermissibleBase(ServerOperator opable) { + this.opable = opable; + + if (opable instanceof Permissible) { + this.parent = (Permissible) opable; + } + + recalculatePermissions(); + } + + public boolean isOp() { + if (opable == null) { + return false; + } else { + return opable.isOp(); + } + } + + public void setOp(boolean value) { + if (opable == null) { + throw new UnsupportedOperationException("Cannot change op value as no ServerOperator is set"); + } else { + opable.setOp(value); + } + } + + public boolean isPermissionSet(String name) { + if (name == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } + + return permissions.containsKey(name.toLowerCase()); + } + + public boolean isPermissionSet(Permission perm) { + if (perm == null) { + throw new IllegalArgumentException("Permission cannot be null"); + } + + return isPermissionSet(perm.getName()); + } + + public boolean hasPermission(String inName) { + if (inName == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } + + String name = inName.toLowerCase(); + + if (isPermissionSet(name)) { + return permissions.get(name).getValue(); + } else { + Permission perm = Bukkit.getServer().getPluginManager().getPermission(name); + + if (perm != null) { + return perm.getDefault().getValue(isOp()); + } else { + return Permission.DEFAULT_PERMISSION.getValue(isOp()); + } + } + } + + public boolean hasPermission(Permission perm) { + if (perm == null) { + throw new IllegalArgumentException("Permission cannot be null"); + } + + String name = perm.getName().toLowerCase(); + + if (isPermissionSet(name)) { + return permissions.get(name).getValue(); + } + return perm.getDefault().getValue(isOp()); + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + if (name == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } else if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + PermissionAttachment result = addAttachment(plugin); + result.setPermission(name, value); + + recalculatePermissions(); + + return result; + } + + public PermissionAttachment addAttachment(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + PermissionAttachment result = new PermissionAttachment(plugin, parent); + + attachments.add(result); + recalculatePermissions(); + + return result; + } + + public void removeAttachment(PermissionAttachment attachment) { + if (attachment == null) { + throw new IllegalArgumentException("Attachment cannot be null"); + } + + if (attachments.contains(attachment)) { + attachments.remove(attachment); + PermissionRemovedExecutor ex = attachment.getRemovalCallback(); + + if (ex != null) { + ex.attachmentRemoved(attachment); + } + + recalculatePermissions(); + } else { + throw new IllegalArgumentException("Given attachment is not part of Permissible object " + parent); + } + } + + public void recalculatePermissions() { + clearPermissions(); + Set defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp()); + Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent); + + for (Permission perm : defaults) { + String name = perm.getName().toLowerCase(); + permissions.put(name, new PermissionAttachmentInfo(parent, name, null, true)); + Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent); + calculateChildPermissions(perm.getChildren(), false, null); + } + + for (PermissionAttachment attachment : attachments) { + calculateChildPermissions(attachment.getPermissions(), false, attachment); + } + } + + public synchronized void clearPermissions() { + Set perms = permissions.keySet(); + + for (String name : perms) { + Bukkit.getServer().getPluginManager().unsubscribeFromPermission(name, parent); + } + + Bukkit.getServer().getPluginManager().unsubscribeFromDefaultPerms(false, parent); + Bukkit.getServer().getPluginManager().unsubscribeFromDefaultPerms(true, parent); + + permissions.clear(); + } + + private void calculateChildPermissions(Map children, boolean invert, PermissionAttachment attachment) { + Set keys = children.keySet(); + + for (String name : keys) { + Permission perm = Bukkit.getServer().getPluginManager().getPermission(name); + boolean value = children.get(name) ^ invert; + String lname = name.toLowerCase(); + + permissions.put(lname, new PermissionAttachmentInfo(parent, lname, attachment, value)); + Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent); + + if (perm != null) { + calculateChildPermissions(perm.getChildren(), !value, attachment); + } + } + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + if (name == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } else if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + PermissionAttachment result = addAttachment(plugin, ticks); + + if (result != null) { + result.setPermission(name, value); + } + + return result; + } + + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + PermissionAttachment result = addAttachment(plugin); + + if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RemoveAttachmentRunnable(result), ticks) == -1) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Could not add PermissionAttachment to " + parent + " for plugin " + plugin.getDescription().getFullName() + ": Scheduler returned -1"); + result.remove(); + return null; + } else { + return result; + } + } + + public Set getEffectivePermissions() { + return new HashSet(permissions.values()); + } + + private class RemoveAttachmentRunnable implements Runnable { + private PermissionAttachment attachment; + + public RemoveAttachmentRunnable(PermissionAttachment attachment) { + this.attachment = attachment; + } + + public void run() { + attachment.remove(); + } + } +} diff --git a/src/main/java/org/bukkit/permissions/Permission.java b/src/main/java/org/bukkit/permissions/Permission.java new file mode 100644 index 0000000..26f6f2b --- /dev/null +++ b/src/main/java/org/bukkit/permissions/Permission.java @@ -0,0 +1,343 @@ +package org.bukkit.permissions; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; + +/** + * Represents a unique permission that may be attached to a {@link + * Permissible} + */ +public class Permission { + public static final PermissionDefault DEFAULT_PERMISSION = PermissionDefault.OP; + + private final String name; + private final Map children = new LinkedHashMap(); + private PermissionDefault defaultValue = DEFAULT_PERMISSION; + private String description; + + public Permission(String name) { + this(name, null, null, null); + } + + public Permission(String name, String description) { + this(name, description, null, null); + } + + public Permission(String name, PermissionDefault defaultValue) { + this(name, null, defaultValue, null); + } + + public Permission(String name, String description, PermissionDefault defaultValue) { + this(name, description, defaultValue, null); + } + + public Permission(String name, Map children) { + this(name, null, null, children); + } + + public Permission(String name, String description, Map children) { + this(name, description, null, children); + } + + public Permission(String name, PermissionDefault defaultValue, Map children) { + this(name, null, defaultValue, children); + } + + public Permission(String name, String description, PermissionDefault defaultValue, Map children) { + this.name = name; + this.description = (description == null) ? "" : description; + + if (defaultValue != null) { + this.defaultValue = defaultValue; + } + + if (children != null) { + this.children.putAll(children); + } + + recalculatePermissibles(); + } + + /** + * Returns the unique fully qualified name of this Permission + * + * @return Fully qualified name + */ + public String getName() { + return name; + } + + /** + * Gets the children of this permission. + *

          + * If you change this map in any form, you must call {@link + * #recalculatePermissibles()} to recalculate all {@link Permissible}s + * + * @return Permission children + */ + public Map getChildren() { + return children; + } + + /** + * Gets the default value of this permission. + * + * @return Default value of this permission. + */ + public PermissionDefault getDefault() { + return defaultValue; + } + + /** + * Sets the default value of this permission. + *

          + * This will not be saved to disk, and is a temporary operation until the + * server reloads permissions. Changing this default will cause all {@link + * Permissible}s that contain this permission to recalculate their + * permissions + * + * @param value The new default to set + */ + public void setDefault(PermissionDefault value) { + if (defaultValue == null) { + throw new IllegalArgumentException("Default value cannot be null"); + } + + defaultValue = value; + recalculatePermissibles(); + } + + /** + * Gets a brief description of this permission, if set + * + * @return Brief description of this permission + */ + public String getDescription() { + return description; + } + + /** + * Sets the description of this permission. + *

          + * This will not be saved to disk, and is a temporary operation until the + * server reloads permissions. + * + * @param value The new description to set + */ + public void setDescription(String value) { + if (value == null) { + description = ""; + } else { + description = value; + } + } + + /** + * Gets a set containing every {@link Permissible} that has this + * permission. + *

          + * This set cannot be modified. + * + * @return Set containing permissibles with this permission + */ + public Set getPermissibles() { + return Bukkit.getServer().getPluginManager().getPermissionSubscriptions(name); + } + + /** + * Recalculates all {@link Permissible}s that contain this permission. + *

          + * This should be called after modifying the children, and is + * automatically called after modifying the default value + */ + public void recalculatePermissibles() { + Set perms = getPermissibles(); + + Bukkit.getServer().getPluginManager().recalculatePermissionDefaults(this); + + for (Permissible p : perms) { + p.recalculatePermissions(); + } + } + + /** + * Adds this permission to the specified parent permission. + *

          + * If the parent permission does not exist, it will be created and + * registered. + * + * @param name Name of the parent permission + * @param value The value to set this permission to + * @return Parent permission it created or loaded + */ + public Permission addParent(String name, boolean value) { + PluginManager pm = Bukkit.getServer().getPluginManager(); + String lname = name.toLowerCase(); + + Permission perm = pm.getPermission(lname); + + if (perm == null) { + perm = new Permission(lname); + pm.addPermission(perm); + } + + addParent(perm, value); + + return perm; + } + + /** + * Adds this permission to the specified parent permission. + * + * @param perm Parent permission to register with + * @param value The value to set this permission to + */ + public void addParent(Permission perm, boolean value) { + perm.getChildren().put(getName(), value); + perm.recalculatePermissibles(); + } + + /** + * Loads a list of Permissions from a map of data, usually used from + * retrieval from a yaml file. + *

          + * The data may contain a list of name:data, where the data contains the + * following keys: + *

            + *
          • default: Boolean true or false. If not specified, false. + *
          • children: Map of child permissions. If not + * specified, empty list. + *
          • description: Short string containing a very small description of + * this description. If not specified, empty string. + *
          + * + * @param data Map of permissions + * @param error An error message to show if a permission is invalid. + * @param def Default permission value to use if missing + * @return Permission object + */ + public static List loadPermissions(Map data, String error, PermissionDefault def) { + List result = new ArrayList(); + + for (Map.Entry entry : data.entrySet()) { + try { + result.add(Permission.loadPermission(entry.getKey().toString(), (Map) entry.getValue(), def, result)); + } catch (Throwable ex) { + Bukkit.getServer().getLogger().log(Level.SEVERE, String.format(error, entry.getKey()), ex); + } + } + + return result; + } + + /** + * Loads a Permission from a map of data, usually used from retrieval from + * a yaml file. + *

          + * The data may contain the following keys: + *

            + *
          • default: Boolean true or false. If not specified, false. + *
          • children: Map of child permissions. If not + * specified, empty list. + *
          • description: Short string containing a very small description of + * this description. If not specified, empty string. + * + * @param name Name of the permission + * @param data Map of keys + * @return Permission object + */ + public static Permission loadPermission(String name, Map data) { + return loadPermission(name, data, DEFAULT_PERMISSION, null); + } + + /** + * Loads a Permission from a map of data, usually used from retrieval from + * a yaml file. + *

            + * The data may contain the following keys: + *

              + *
            • default: Boolean true or false. If not specified, false. + *
            • children: Map of child permissions. If not + * specified, empty list. + *
            • description: Short string containing a very small description of + * this description. If not specified, empty string. + *
            + * + * @param name Name of the permission + * @param data Map of keys + * @param def Default permission value to use if not set + * @param output A list to append any created child-Permissions to, may be null + * @return Permission object + */ + public static Permission loadPermission(String name, Map data, PermissionDefault def, List output) { + Validate.notNull(name, "Name cannot be null"); + Validate.notNull(data, "Data cannot be null"); + + String desc = null; + Map children = null; + + if (data.get("default") != null) { + PermissionDefault value = PermissionDefault.getByName(data.get("default").toString()); + if (value != null) { + def = value; + } else { + throw new IllegalArgumentException("'default' key contained unknown value"); + } + } + + if (data.get("children") != null) { + Object childrenNode = data.get("children"); + if (childrenNode instanceof Iterable) { + children = new LinkedHashMap(); + for (Object child : (Iterable) childrenNode) { + if (child != null) { + children.put(child.toString(), Boolean.TRUE); + } + } + } else if (childrenNode instanceof Map) { + children = extractChildren((Map) childrenNode, name, def, output); + } else { + throw new IllegalArgumentException("'children' key is of wrong type"); + } + } + + if (data.get("description") != null) { + desc = data.get("description").toString(); + } + + return new Permission(name, desc, def, children); + } + + private static Map extractChildren(Map input, String name, PermissionDefault def, List output) { + Map children = new LinkedHashMap(); + + for (Map.Entry entry : input.entrySet()) { + if ((entry.getValue() instanceof Boolean)) { + children.put(entry.getKey().toString(), (Boolean) entry.getValue()); + } else if ((entry.getValue() instanceof Map)) { + try { + Permission perm = loadPermission(entry.getKey().toString(), (Map) entry.getValue(), def, output); + children.put(perm.getName(), Boolean.TRUE); + + if (output != null) { + output.add(perm); + } + } catch (Throwable ex) { + throw new IllegalArgumentException("Permission node '" + entry.getKey().toString() + "' in child of " + name + " is invalid", ex); + } + } else { + throw new IllegalArgumentException("Child '" + entry.getKey().toString() + "' contains invalid value"); + } + } + + return children; + } +} diff --git a/src/main/java/org/bukkit/permissions/PermissionAttachment.java b/src/main/java/org/bukkit/permissions/PermissionAttachment.java new file mode 100644 index 0000000..b2a44d5 --- /dev/null +++ b/src/main/java/org/bukkit/permissions/PermissionAttachment.java @@ -0,0 +1,139 @@ +package org.bukkit.permissions; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.bukkit.plugin.Plugin; + +/** + * Holds information about a permission attachment on a {@link Permissible} + * object + */ +public class PermissionAttachment { + private PermissionRemovedExecutor removed; + private final Map permissions = new LinkedHashMap(); + private final Permissible permissible; + private final Plugin plugin; + + public PermissionAttachment(Plugin plugin, Permissible Permissible) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + this.permissible = Permissible; + this.plugin = plugin; + } + + /** + * Gets the plugin responsible for this attachment + * + * @return Plugin responsible for this permission attachment + */ + public Plugin getPlugin() { + return plugin; + } + + /** + * Sets an object to be called for when this attachment is removed from a + * {@link Permissible}. May be null. + * + * @param ex Object to be called when this is removed + */ + public void setRemovalCallback(PermissionRemovedExecutor ex) { + removed = ex; + } + + /** + * Gets the class that was previously set to be called when this + * attachment was removed from a {@link Permissible}. May be null. + * + * @return Object to be called when this is removed + */ + public PermissionRemovedExecutor getRemovalCallback() { + return removed; + } + + /** + * Gets the Permissible that this is attached to + * + * @return Permissible containing this attachment + */ + public Permissible getPermissible() { + return permissible; + } + + /** + * Gets a copy of all set permissions and values contained within this + * attachment. + *

            + * This map may be modified but will not affect the attachment, as it is a + * copy. + * + * @return Copy of all permissions and values expressed by this attachment + */ + public Map getPermissions() { + return new LinkedHashMap(permissions); + } + + /** + * Sets a permission to the given value, by its fully qualified name + * + * @param name Name of the permission + * @param value New value of the permission + */ + public void setPermission(String name, boolean value) { + permissions.put(name.toLowerCase(), value); + permissible.recalculatePermissions(); + } + + /** + * Sets a permission to the given value + * + * @param perm Permission to set + * @param value New value of the permission + */ + public void setPermission(Permission perm, boolean value) { + setPermission(perm.getName(), value); + } + + /** + * Removes the specified permission from this attachment. + *

            + * If the permission does not exist in this attachment, nothing will + * happen. + * + * @param name Name of the permission to remove + */ + public void unsetPermission(String name) { + permissions.remove(name.toLowerCase()); + permissible.recalculatePermissions(); + } + + /** + * Removes the specified permission from this attachment. + *

            + * If the permission does not exist in this attachment, nothing will + * happen. + * + * @param perm Permission to remove + */ + public void unsetPermission(Permission perm) { + unsetPermission(perm.getName()); + } + + /** + * Removes this attachment from its registered {@link Permissible} + * + * @return true if the permissible was removed successfully, false if it + * did not exist + */ + public boolean remove() { + try { + permissible.removeAttachment(this); + return true; + } catch (IllegalArgumentException ex) { + return false; + } + } +} diff --git a/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java b/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java new file mode 100644 index 0000000..8e8e335 --- /dev/null +++ b/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java @@ -0,0 +1,62 @@ +package org.bukkit.permissions; + +/** + * Holds information on a permission and which {@link PermissionAttachment} + * provides it + */ +public class PermissionAttachmentInfo { + private final Permissible permissible; + private final String permission; + private final PermissionAttachment attachment; + private final boolean value; + + public PermissionAttachmentInfo(Permissible permissible, String permission, PermissionAttachment attachment, boolean value) { + if (permissible == null) { + throw new IllegalArgumentException("Permissible may not be null"); + } else if (permission == null) { + throw new IllegalArgumentException("Permissions may not be null"); + } + + this.permissible = permissible; + this.permission = permission; + this.attachment = attachment; + this.value = value; + } + + /** + * Gets the permissible this is attached to + * + * @return Permissible this permission is for + */ + public Permissible getPermissible() { + return permissible; + } + + /** + * Gets the permission being set + * + * @return Name of the permission + */ + public String getPermission() { + return permission; + } + + /** + * Gets the attachment providing this permission. This may be null for + * default permissions (usually parent permissions). + * + * @return Attachment + */ + public PermissionAttachment getAttachment() { + return attachment; + } + + /** + * Gets the value of this permission + * + * @return Value of the permission + */ + public boolean getValue() { + return value; + } +} diff --git a/src/main/java/org/bukkit/permissions/PermissionDefault.java b/src/main/java/org/bukkit/permissions/PermissionDefault.java new file mode 100644 index 0000000..045e733 --- /dev/null +++ b/src/main/java/org/bukkit/permissions/PermissionDefault.java @@ -0,0 +1,66 @@ +package org.bukkit.permissions; + +import java.util.HashMap; +import java.util.Map; + +/** + * Represents the possible default values for permissions + */ +public enum PermissionDefault { + TRUE("true"), + FALSE("false"), + OP("op", "isop", "operator", "isoperator", "admin", "isadmin"), + NOT_OP("!op", "notop", "!operator", "notoperator", "!admin", "notadmin"); + + private final String[] names; + private final static Map lookup = new HashMap(); + + private PermissionDefault(String... names) { + this.names = names; + } + + /** + * Calculates the value of this PermissionDefault for the given operator + * value + * + * @param op If the target is op + * @return True if the default should be true, or false + */ + public boolean getValue(boolean op) { + switch (this) { + case TRUE: + return true; + case FALSE: + return false; + case OP: + return op; + case NOT_OP: + return !op; + default: + return false; + } + } + + /** + * Looks up a PermissionDefault by name + * + * @param name Name of the default + * @return Specified value, or null if not found + */ + public static PermissionDefault getByName(String name) { + return lookup.get(name.toLowerCase().replaceAll("[^a-z!]", "")); + } + + @Override + public String toString() { + return names[0]; + } + + static { + for (PermissionDefault value : values()) { + for (String name : value.names) { + lookup.put(name, value); + } + } + } +} diff --git a/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java b/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java new file mode 100644 index 0000000..b13d008 --- /dev/null +++ b/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java @@ -0,0 +1,16 @@ +package org.bukkit.permissions; + +/** + * Represents a class which is to be notified when a {@link + * PermissionAttachment} is removed from a {@link Permissible} + */ +public interface PermissionRemovedExecutor { + + /** + * Called when a {@link PermissionAttachment} is removed from a {@link + * Permissible} + * + * @param attachment Attachment which was removed + */ + public void attachmentRemoved(PermissionAttachment attachment); +} diff --git a/src/main/java/org/bukkit/permissions/ServerOperator.java b/src/main/java/org/bukkit/permissions/ServerOperator.java new file mode 100644 index 0000000..26ed243 --- /dev/null +++ b/src/main/java/org/bukkit/permissions/ServerOperator.java @@ -0,0 +1,24 @@ +package org.bukkit.permissions; + +import org.bukkit.entity.Player; + +/** + * Represents an object that may become a server operator, such as a {@link + * Player} + */ +public interface ServerOperator { + + /** + * Checks if this object is a server operator + * + * @return true if this is an operator, otherwise false + */ + public boolean isOp(); + + /** + * Sets the operator status of this object + * + * @param value New operator value + */ + public void setOp(boolean value); +} diff --git a/src/main/java/org/bukkit/plugin/AuthorNagException.java b/src/main/java/org/bukkit/plugin/AuthorNagException.java new file mode 100644 index 0000000..6565a44 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/AuthorNagException.java @@ -0,0 +1,20 @@ +package org.bukkit.plugin; + +@SuppressWarnings("serial") +public class AuthorNagException extends RuntimeException { + private final String message; + + /** + * Constructs a new AuthorNagException based on the given Exception + * + * @param message Brief message explaining the cause of the exception + */ + public AuthorNagException(final String message) { + this.message = message; + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/src/main/java/org/bukkit/plugin/EventExecutor.java b/src/main/java/org/bukkit/plugin/EventExecutor.java new file mode 100644 index 0000000..3b2c99e --- /dev/null +++ b/src/main/java/org/bukkit/plugin/EventExecutor.java @@ -0,0 +1,12 @@ +package org.bukkit.plugin; + +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.Listener; + +/** + * Interface which defines the class for event call backs to plugins + */ +public interface EventExecutor { + public void execute(Listener listener, Event event) throws EventException; +} diff --git a/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java b/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java new file mode 100644 index 0000000..b25447d --- /dev/null +++ b/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java @@ -0,0 +1,25 @@ +package org.bukkit.plugin; + +/** + * Thrown when a plugin attempts to interact with the server when it is not + * enabled + */ +@SuppressWarnings("serial") +public class IllegalPluginAccessException extends RuntimeException { + + /** + * Creates a new instance of IllegalPluginAccessException + * without detail message. + */ + public IllegalPluginAccessException() {} + + /** + * Constructs an instance of IllegalPluginAccessException + * with the specified detail message. + * + * @param msg the detail message. + */ + public IllegalPluginAccessException(String msg) { + super(msg); + } +} diff --git a/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java b/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java new file mode 100644 index 0000000..0a77c2e --- /dev/null +++ b/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java @@ -0,0 +1,45 @@ +package org.bukkit.plugin; + +/** + * Thrown when attempting to load an invalid PluginDescriptionFile + */ +public class InvalidDescriptionException extends Exception { + private static final long serialVersionUID = 5721389122281775896L; + + /** + * Constructs a new InvalidDescriptionException based on the given + * Exception + * + * @param message Brief message explaining the cause of the exception + * @param cause Exception that triggered this Exception + */ + public InvalidDescriptionException(final Throwable cause, final String message) { + super(message, cause); + } + + /** + * Constructs a new InvalidDescriptionException based on the given + * Exception + * + * @param cause Exception that triggered this Exception + */ + public InvalidDescriptionException(final Throwable cause) { + super("Invalid plugin.yml", cause); + } + + /** + * Constructs a new InvalidDescriptionException with the given message + * + * @param message Brief message explaining the cause of the exception + */ + public InvalidDescriptionException(final String message) { + super(message); + } + + /** + * Constructs a new InvalidDescriptionException + */ + public InvalidDescriptionException() { + super("Invalid plugin.yml"); + } +} diff --git a/src/main/java/org/bukkit/plugin/InvalidPluginException.java b/src/main/java/org/bukkit/plugin/InvalidPluginException.java new file mode 100644 index 0000000..7ddf7b6 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/InvalidPluginException.java @@ -0,0 +1,49 @@ +package org.bukkit.plugin; + +/** + * Thrown when attempting to load an invalid Plugin file + */ +public class InvalidPluginException extends Exception { + private static final long serialVersionUID = -8242141640709409544L; + + /** + * Constructs a new InvalidPluginException based on the given Exception + * + * @param cause Exception that triggered this Exception + */ + public InvalidPluginException(final Throwable cause) { + super(cause); + } + + /** + * Constructs a new InvalidPluginException + */ + public InvalidPluginException() { + + } + + /** + * Constructs a new InvalidPluginException with the specified detail + * message and cause. + * + * @param message the detail message (which is saved for later retrieval + * by the getMessage() method). + * @param cause the cause (which is saved for later retrieval by the + * getCause() method). (A null value is permitted, and indicates that + * the cause is nonexistent or unknown.) + */ + public InvalidPluginException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new InvalidPluginException with the specified detail + * message + * + * @param message TThe detail message is saved for later retrieval by the + * getMessage() method. + */ + public InvalidPluginException(final String message) { + super(message); + } +} diff --git a/src/main/java/org/bukkit/plugin/Plugin.java b/src/main/java/org/bukkit/plugin/Plugin.java new file mode 100644 index 0000000..7bdc809 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/Plugin.java @@ -0,0 +1,189 @@ +package org.bukkit.plugin; + +import java.io.File; +import java.io.InputStream; +import java.util.logging.Logger; + +import org.bukkit.Server; +import org.bukkit.command.TabExecutor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.generator.ChunkGenerator; + +import com.avaje.ebean.EbeanServer; + +/** + * Represents a Plugin + *

            + * The use of {@link PluginBase} is recommended for actual Implementation + */ +public interface Plugin extends TabExecutor { + /** + * Returns the folder that the plugin data's files are located in. The + * folder may not yet exist. + * + * @return The folder + */ + public File getDataFolder(); + + /** + * Returns the plugin.yaml file containing the details for this plugin + * + * @return Contents of the plugin.yaml file + */ + public PluginDescriptionFile getDescription(); + + /** + * Gets a {@link FileConfiguration} for this plugin, read through + * "config.yml" + *

            + * If there is a default config.yml embedded in this plugin, it will be + * provided as a default for this Configuration. + * + * @return Plugin configuration + */ + public FileConfiguration getConfig(); + + /** + * Gets an embedded resource in this plugin + * + * @param filename Filename of the resource + * @return File if found, otherwise null + */ + public InputStream getResource(String filename); + + /** + * Saves the {@link FileConfiguration} retrievable by {@link #getConfig()}. + */ + public void saveConfig(); + + /** + * Saves the raw contents of the default config.yml file to the location + * retrievable by {@link #getConfig()}. If there is no default config.yml + * embedded in the plugin, an empty config.yml file is saved. This should + * fail silently if the config.yml already exists. + */ + public void saveDefaultConfig(); + + /** + * Saves the raw contents of any resource embedded with a plugin's .jar + * file assuming it can be found using {@link #getResource(String)}. + *

            + * The resource is saved into the plugin's data folder using the same + * hierarchy as the .jar file (subdirectories are preserved). + * + * @param resourcePath the embedded resource path to look for within the + * plugin's .jar file. (No preceding slash). + * @param replace if true, the embedded resource will overwrite the + * contents of an existing file. + * @throws IllegalArgumentException if the resource path is null, empty, + * or points to a nonexistent resource. + */ + public void saveResource(String resourcePath, boolean replace); + + /** + * Discards any data in {@link #getConfig()} and reloads from disk. + */ + public void reloadConfig(); + + /** + * Gets the associated PluginLoader responsible for this plugin + * + * @return PluginLoader that controls this plugin + */ + public PluginLoader getPluginLoader(); + + /** + * Returns the Server instance currently running this plugin + * + * @return Server running this plugin + */ + public Server getServer(); + + /** + * Returns a value indicating whether or not this plugin is currently + * enabled + * + * @return true if this plugin is enabled, otherwise false + */ + public boolean isEnabled(); + + /** + * Called when this plugin is disabled + */ + public void onDisable(); + + /** + * Called after a plugin is loaded but before it has been enabled. + *

            + * When mulitple plugins are loaded, the onLoad() for all plugins is + * called before any onEnable() is called. + */ + public void onLoad(); + + /** + * Called when this plugin is enabled + */ + public void onEnable(); + + /** + * Simple boolean if we can still nag to the logs about things + * + * @return boolean whether we can nag + */ + public boolean isNaggable(); + + /** + * Set naggable state + * + * @param canNag is this plugin still naggable? + */ + public void setNaggable(boolean canNag); + + /** + * Gets the {@link EbeanServer} tied to this plugin. This will only be + * available if enabled in the {@link + * PluginDescriptionFile#isDatabaseEnabled()} + *

            + * For more information on the use of + * Avaje Ebeans ORM, see Avaje Ebeans + * Documentation + *

            + * For an example using Ebeans ORM, see Bukkit's Homebukkit Plugin + * + * + * @return ebean server instance or null if not enabled + */ + public EbeanServer getDatabase(); + + /** + * Gets a {@link ChunkGenerator} for use in a default world, as specified + * in the server configuration + * + * @param worldName Name of the world that this will be applied to + * @param id Unique ID, if any, that was specified to indicate which + * generator was requested + * @return ChunkGenerator for use in the default world generation + */ + public ChunkGenerator getDefaultWorldGenerator(String worldName, String id); + + /** + * Returns the plugin logger associated with this server's logger. The + * returned logger automatically tags all log messages with the plugin's + * name. + * + * @return Logger associated with this plugin + */ + public Logger getLogger(); + + /** + * Returns the name of the plugin. + *

            + * This should return the bare name of the plugin and should be used for + * comparison. + * + * @return name of the plugin + */ + public String getName(); +} diff --git a/src/main/java/org/bukkit/plugin/PluginAwareness.java b/src/main/java/org/bukkit/plugin/PluginAwareness.java new file mode 100644 index 0000000..ddb47b7 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/PluginAwareness.java @@ -0,0 +1,29 @@ +package org.bukkit.plugin; + +import java.util.Set; + +import org.bukkit.plugin.java.JavaPlugin; + +/** + * Represents a concept that a plugin is aware of. + *

            + * The internal representation may be singleton, or be a parameterized + * instance, but must be immutable. + */ +public interface PluginAwareness { + /** + * Each entry here represents a particular plugin's awareness. These can + * be checked by using {@link PluginDescriptionFile#getAwareness()}.{@link + * Set#contains(Object) contains(flag)}. + */ + public enum Flags implements PluginAwareness { + /** + * This specifies that all (text) resources stored in a plugin's jar + * use UTF-8 encoding. + * + * @see JavaPlugin#getTextResource(String) + */ + UTF8, + ; + } +} diff --git a/src/main/java/org/bukkit/plugin/PluginBase.java b/src/main/java/org/bukkit/plugin/PluginBase.java new file mode 100644 index 0000000..6031af1 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/PluginBase.java @@ -0,0 +1,32 @@ +package org.bukkit.plugin; + +/** + * Represents a base {@link Plugin} + *

            + * Extend this class if your plugin is not a {@link + * org.bukkit.plugin.java.JavaPlugin} + */ +public abstract class PluginBase implements Plugin { + @Override + public final int hashCode() { + return getName().hashCode(); + } + + @Override + public final boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof Plugin)) { + return false; + } + return getName().equals(((Plugin) obj).getName()); + } + + public final String getName() { + return getDescription().getName(); + } +} diff --git a/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java b/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java new file mode 100644 index 0000000..0fd966c --- /dev/null +++ b/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java @@ -0,0 +1,1110 @@ +package org.bukkit.plugin; + +import java.io.InputStream; +import java.io.Reader; +import java.io.Writer; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.PluginCommand; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.AbstractConstruct; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.Tag; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +/** + * This type is the runtime-container for the information in the plugin.yml. + * All plugins must have a respective plugin.yml. For plugins written in java + * using the standard plugin loader, this file must be in the root of the jar + * file. + *

            + * When Bukkit loads a plugin, it needs to know some basic information about + * it. It reads this information from a YAML file, 'plugin.yml'. This file + * consists of a set of attributes, each defined on a new line and with no + * indentation. + *

            + * Every (almost* every) method corresponds with a specific entry in the + * plugin.yml. These are the required entries for every plugin.yml: + *

              + *
            • {@link #getName()} - name + *
            • {@link #getVersion()} - version + *
            • {@link #getMain()} - main + *
            + *

            + * Failing to include any of these items will throw an exception and cause the + * server to ignore your plugin. + *

            + * This is a list of the possible yaml keys, with specific details included in + * the respective method documentations: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
            NodeMethodSummary
            name{@link #getName()}The unique name of plugin
            version{@link #getVersion()}A plugin revision identifier
            main{@link #getMain()}The plugin's initial class file
            author
            authors
            {@link #getAuthors()}The plugin contributors
            description{@link #getDescription()}Human readable plugin summary
            website{@link #getWebsite()}The URL to the plugin's site
            prefix{@link #getPrefix()}The token to prefix plugin log entries
            database{@link #isDatabaseEnabled()}Indicator to enable database support
            load{@link #getLoad()}The phase of server-startup this plugin will load during
            depend{@link #getDepend()}Other required plugins
            softdepend{@link #getSoftDepend()}Other plugins that add functionality
            loadbefore{@link #getLoadBefore()}The inverse softdepend
            commands{@link #getCommands()}The commands the plugin will register
            permissions{@link #getPermissions()}The permissions the plugin will register
            default-permission{@link #getPermissionDefault()}The default {@link Permission#getDefault() default} permission + * state for defined {@link #getPermissions() permissions} the plugin + * will register
            awareness{@link #getAwareness()}The concepts that the plugin acknowledges
            + *

            + * A plugin.yml example:

            + *name: Inferno
            + *version: 1.4.1
            + *description: This plugin is so 31337. You can set yourself on fire.
            + *# We could place every author in the authors list, but chose not to for illustrative purposes
            + *# Also, having an author distinguishes that person as the project lead, and ensures their
            + *# name is displayed first
            + *author: CaptainInflamo
            + *authors: [Cogito, verrier, EvilSeph]
            + *website: http://www.curse.com/server-mods/minecraft/myplugin
            + *
            + *main: com.captaininflamo.bukkit.inferno.Inferno
            + *database: false
            + *depend: [NewFire, FlameWire]
            + *
            + *commands:
            + *  flagrate:
            + *    description: Set yourself on fire.
            + *    aliases: [combust_me, combustMe]
            + *    permission: inferno.flagrate
            + *    usage: Syntax error! Simply type /<command> to ignite yourself.
            + *  burningdeaths:
            + *    description: List how many times you have died by fire.
            + *    aliases: [burning_deaths, burningDeaths]
            + *    permission: inferno.burningdeaths
            + *    usage: |
            + *      /<command> [player]
            + *      Example: /<command> - see how many times you have burned to death
            + *      Example: /<command> CaptainIce - see how many times CaptainIce has burned to death
            + *
            + *permissions:
            + *  inferno.*:
            + *    description: Gives access to all Inferno commands
            + *    children:
            + *      inferno.flagrate: true
            + *      inferno.burningdeaths: true
            + *      inferno.burningdeaths.others: true
            + *  inferno.flagrate:
            + *    description: Allows you to ignite yourself
            + *    default: true
            + *  inferno.burningdeaths:
            + *    description: Allows you to see how many times you have burned to death
            + *    default: true
            + *  inferno.burningdeaths.others:
            + *    description: Allows you to see how many times others have burned to death
            + *    default: op
            + *    children:
            + *      inferno.burningdeaths: true
            + *
            + */ +public final class PluginDescriptionFile { + private static final ThreadLocal YAML = new ThreadLocal() { + @Override + protected Yaml initialValue() { + return new Yaml(new SafeConstructor() { + { + yamlConstructors.put(null, new AbstractConstruct() { + @Override + public Object construct(final Node node) { + if (!node.getTag().startsWith("!@")) { + // Unknown tag - will fail + return SafeConstructor.undefinedConstructor.construct(node); + } + // Unknown awareness - provide a graceful substitution + return new PluginAwareness() { + @Override + public String toString() { + return node.toString(); + } + }; + } + }); + for (final PluginAwareness.Flags flag : PluginAwareness.Flags.values()) { + yamlConstructors.put(new Tag("!@" + flag.name()), new AbstractConstruct() { + @Override + public PluginAwareness.Flags construct(final Node node) { + return flag; + } + }); + } + } + }); + } + }; + String rawName = null; + private String name = null; + private String main = null; + private String classLoaderOf = null; + private List depend = ImmutableList.of(); + private List softDepend = ImmutableList.of(); + private List loadBefore = ImmutableList.of(); + private String version = null; + private Map> commands = null; + private String description = null; + private List authors = null; + private String website = null; + private String prefix = null; + private boolean database = false; + private PluginLoadOrder order = PluginLoadOrder.POSTWORLD; + private List permissions = null; + private Map lazyPermissions = null; + private PermissionDefault defaultPerm = PermissionDefault.OP; + private Set awareness = ImmutableSet.of(); + + public PluginDescriptionFile(final InputStream stream) throws InvalidDescriptionException { + loadMap(asMap(YAML.get().load(stream))); + } + + /** + * Loads a PluginDescriptionFile from the specified reader + * + * @param reader The reader + * @throws InvalidDescriptionException If the PluginDescriptionFile is + * invalid + */ + public PluginDescriptionFile(final Reader reader) throws InvalidDescriptionException { + loadMap(asMap(YAML.get().load(reader))); + } + + /** + * Creates a new PluginDescriptionFile with the given detailed + * + * @param pluginName Name of this plugin + * @param pluginVersion Version of this plugin + * @param mainClass Full location of the main class of this plugin + */ + public PluginDescriptionFile(final String pluginName, final String pluginVersion, final String mainClass) { + name = pluginName.replace(' ', '_'); + version = pluginVersion; + main = mainClass; + } + + /** + * Gives the name of the plugin. This name is a unique identifier for + * plugins. + *
              + *
            • Must consist of all alphanumeric characters, underscores, hyphon, + * and period (a-z,A-Z,0-9, _.-). Any other character will cause the + * plugin.yml to fail loading. + *
            • Used to determine the name of the plugin's data folder. Data + * folders are placed in the ./plugins/ directory by default, but this + * behavior should not be relied on. {@link Plugin#getDataFolder()} + * should be used to reference the data folder. + *
            • It is good practice to name your jar the same as this, for example + * 'MyPlugin.jar'. + *
            • Case sensitive. + *
            • The is the token referenced in {@link #getDepend()}, {@link + * #getSoftDepend()}, and {@link #getLoadBefore()}. + *
            • Using spaces in the plugin's name is deprecated. + *
            + *

            + * In the plugin.yml, this entry is named name. + *

            + * Example:

            name: MyPlugin
            + * + * @return the name of the plugin + */ + public String getName() { + return name; + } + + /** + * Gives the version of the plugin. + *
              + *
            • Version is an arbitrary string, however the most common format is + * MajorRelease.MinorRelease.Build (eg: 1.4.1). + *
            • Typically you will increment this every time you release a new + * feature or bug fix. + *
            • Displayed when a user types /version PluginName + *
            + *

            + * In the plugin.yml, this entry is named version. + *

            + * Example:

            version: 1.4.1
            + * + * @return the version of the plugin + */ + public String getVersion() { + return version; + } + + /** + * Gives the fully qualified name of the main class for a plugin. The + * format should follow the {@link ClassLoader#loadClass(String)} syntax + * to successfully be resolved at runtime. For most plugins, this is the + * class that extends {@link JavaPlugin}. + *
              + *
            • This must contain the full namespace including the class file + * itself. + *
            • If your namespace is org.bukkit.plugin, and your class + * file is called MyPlugin then this must be + * org.bukkit.plugin.MyPlugin + *
            • No plugin can use org.bukkit. as a base package for + * any class, including the main class. + *
            + *

            + * In the plugin.yml, this entry is named main. + *

            + * Example: + *

            main: org.bukkit.plugin.MyPlugin
            + * + * @return the fully qualified main class for the plugin + */ + public String getMain() { + return main; + } + + /** + * Gives a human-friendly description of the functionality the plugin + * provides. + *
              + *
            • The description can have multiple lines. + *
            • Displayed when a user types /version PluginName + *
            + *

            + * In the plugin.yml, this entry is named description. + *

            + * Example: + *

            description: This plugin is so 31337. You can set yourself on fire.
            + * + * @return description of this plugin, or null if not specified + */ + public String getDescription() { + return description; + } + + /** + * Gives the phase of server startup that the plugin should be loaded. + *
              + *
            • Possible values are in {@link PluginLoadOrder}. + *
            • Defaults to {@link PluginLoadOrder#POSTWORLD}. + *
            • Certain caveats apply to each phase. + *
            • When different, {@link #getDepend()}, {@link #getSoftDepend()}, and + * {@link #getLoadBefore()} become relative in order loaded per-phase. + * If a plugin loads at STARTUP, but a dependency loads + * at POSTWORLD, the dependency will not be loaded before + * the plugin is loaded. + *
            + *

            + * In the plugin.yml, this entry is named load. + *

            + * Example:

            load: STARTUP
            + * + * @return the phase when the plugin should be loaded + */ + public PluginLoadOrder getLoad() { + return order; + } + + /** + * Gives the list of authors for the plugin. + *
              + *
            • Gives credit to the developer. + *
            • Used in some server error messages to provide helpful feedback on + * who to contact when an error occurs. + *
            • A bukkit.org forum handle or email address is recommended. + *
            • Is displayed when a user types /version PluginName + *
            • authors must be in YAML list + * format. + *
            + *

            + * In the plugin.yml, this has two entries, author and + * authors. + *

            + * Single author example: + *

            author: CaptainInflamo
            + * Multiple author example: + *
            authors: [Cogito, verrier, EvilSeph]
            + * When both are specified, author will be the first entry in the list, so + * this example: + *
            author: Grum
            +     *authors:
            +     *- feildmaster
            +     *- amaranth
            + * Is equivilant to this example: + *
            authors: [Grum, feildmaster, aramanth]
            + * + * @return an immutable list of the plugin's authors + */ + public List getAuthors() { + return authors; + } + + /** + * Gives the plugin's or plugin's author's website. + *
              + *
            • A link to the Curse page that includes documentation and downloads + * is highly recommended. + *
            • Displayed when a user types /version PluginName + *
            + *

            + * In the plugin.yml, this entry is named website. + *

            + * Example: + *

            website: http://www.curse.com/server-mods/minecraft/myplugin
            + * + * @return description of this plugin, or null if not specified + */ + public String getWebsite() { + return website; + } + + /** + * Gives if the plugin uses a database. + *
              + *
            • Using a database is non-trivial. + *
            • Valid values include true and false + *
            + *

            + * In the plugin.yml, this entry is named database. + *

            + * Example: + *

            database: false
            + * + * @return if this plugin requires a database + * @see Plugin#getDatabase() + */ + public boolean isDatabaseEnabled() { + return database; + } + + /** + * Gives a list of other plugins that the plugin requires. + *
              + *
            • Use the value in the {@link #getName()} of the target plugin to + * specify the dependency. + *
            • If any plugin listed here is not found, your plugin will fail to + * load at startup. + *
            • If multiple plugins list each other in depend, + * creating a network with no individual plugin does not list another + * plugin in the network, + * all plugins in that network will fail. + *
            • depend must be in must be in YAML list + * format. + *
            + *

            + * In the plugin.yml, this entry is named depend. + *

            + * Example: + *

            depend:
            +     *- OnePlugin
            +     *- AnotherPlugin
            + * + * @return immutable list of the plugin's dependencies + */ + public List getDepend() { + return depend; + } + + /** + * Gives a list of other plugins that the plugin requires for full + * functionality. The {@link PluginManager} will make best effort to treat + * all entries here as if they were a {@link #getDepend() dependency}, but + * will never fail because of one of these entries. + *
              + *
            • Use the value in the {@link #getName()} of the target plugin to + * specify the dependency. + *
            • When an unresolvable plugin is listed, it will be ignored and does + * not affect load order. + *
            • When a circular dependency occurs (a network of plugins depending + * or soft-dependending each other), it will arbitrarily choose a + * plugin that can be resolved when ignoring soft-dependencies. + *
            • softdepend must be in YAML list + * format. + *
            + *

            + * In the plugin.yml, this entry is named softdepend. + *

            + * Example: + *

            softdepend: [OnePlugin, AnotherPlugin]
            + * + * @return immutable list of the plugin's preferred dependencies + */ + public List getSoftDepend() { + return softDepend; + } + + /** + * Gets the list of plugins that should consider this plugin a + * soft-dependency. + *
              + *
            • Use the value in the {@link #getName()} of the target plugin to + * specify the dependency. + *
            • The plugin should load before any other plugins listed here. + *
            • Specifying another plugin here is strictly equivalent to having the + * specified plugin's {@link #getSoftDepend()} include {@link + * #getName() this plugin}. + *
            • loadbefore must be in YAML list + * format. + *
            + *

            + * In the plugin.yml, this entry is named loadbefore. + *

            + * Example: + *

            loadbefore:
            +     *- OnePlugin
            +     *- AnotherPlugin
            + * + * @return immutable list of plugins that should consider this plugin a + * soft-dependency + */ + public List getLoadBefore() { + return loadBefore; + } + + /** + * Gives the token to prefix plugin-specific logging messages with. + *
              + *
            • This includes all messages using {@link Plugin#getLogger()}. + *
            • If not specified, the server uses the plugin's {@link #getName() + * name}. + *
            • This should clearly indicate what plugin is being logged. + *
            + *

            + * In the plugin.yml, this entry is named prefix. + *

            + * Example:

            prefix: ex-why-zee
            + * + * @return the prefixed logging token, or null if not specified + */ + public String getPrefix() { + return prefix; + } + + /** + * Gives the map of command-name to command-properties. Each entry in this + * map corresponds to a single command and the respective values are the + * properties of the command. Each property, with the exception of + * aliases, can be defined at runtime using methods in {@link + * PluginCommand} and are defined here only as a convenience. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
            NodeMethodTypeDescriptionExample
            description{@link PluginCommand#setDescription(String)}StringA user-friendly description for a command. It is useful for + * documentation purposes as well as in-game help.
            description: Set yourself on fire
            aliases{@link PluginCommand#setAliases(List)}String or List of + * stringsAlternative command names, with special usefulness for commands + * that are already registered. Aliases are not effective when + * defined at runtime, so the plugin description file is the + * only way to have them properly defined. + *

            + * Note: Command aliases may not have a colon in them.

            Single alias format: + *
            aliases: combust_me
            or + * multiple alias format: + *
            aliases: [combust_me, combustMe]
            permission{@link PluginCommand#setPermission(String)}StringThe name of the {@link Permission} required to use the command. + * A user without the permission will receive the specified + * message (see {@linkplain + * PluginCommand#setPermissionMessage(String) below}), or a + * standard one if no specific message is defined. Without the + * permission node, no {@link + * PluginCommand#setExecutor(CommandExecutor) CommandExecutor} or + * {@link PluginCommand#setTabCompleter(TabCompleter) + * TabCompleter} will be called.
            permission: inferno.flagrate
            permission-message{@link PluginCommand#setPermissionMessage(String)}String
              + *
            • Displayed to a player that attempts to use a command, but + * does not have the required permission. See {@link + * PluginCommand#getPermission() above}. + *
            • <permission> is a macro that is replaced with the + * permission node required to use the command. + *
            • Using empty quotes is a valid way to indicate nothing + * should be displayed to a player. + *
            permission-message: You do not have /<permission>
            usage{@link PluginCommand#setUsage(String)}StringThis message is displayed to a player when the {@link + * PluginCommand#setExecutor(CommandExecutor)} {@linkplain + * CommandExecutor#onCommand(CommandSender,Command,String,String[]) + * returns false}. <command> is a macro that is replaced + * the command issued.
            usage: Syntax error! Perhaps you meant /<command> PlayerName?
            + * It is worth noting that to use a colon in a yaml, like + * `usage: Usage: /god [player]', you need to + * surround + * the message with double-quote: + *
            usage: "Usage: /god [player]"
            + * The commands are structured as a hiearchy of nested mappings. + * The primary (top-level, no intendentation) node is + * `commands', while each individual command name is + * indented, indicating it maps to some value (in our case, the + * properties of the table above). + *

            + * Here is an example bringing together the piecemeal examples above, as + * well as few more definitions:

            +     *commands:
            +     *  flagrate:
            +     *    description: Set yourself on fire.
            +     *    aliases: [combust_me, combustMe]
            +     *    permission: inferno.flagrate
            +     *    permission-message: You do not have /<permission>
            +     *    usage: Syntax error! Perhaps you meant /<command> PlayerName?
            +     *  burningdeaths:
            +     *    description: List how many times you have died by fire.
            +     *    aliases:
            +     *    - burning_deaths
            +     *    - burningDeaths
            +     *    permission: inferno.burningdeaths
            +     *    usage: |
            +     *      /<command> [player]
            +     *      Example: /<command> - see how many times you have burned to death
            +     *      Example: /<command> CaptainIce - see how many times CaptainIce has burned to death
            +     *  # The next command has no description, aliases, etc. defined, but is still valid
            +     *  # Having an empty declaration is useful for defining the description, permission, and messages from a configuration dynamically
            +     *  apocalypse:
            +     *
            + * Note: Command names may not have a colon in their name. + * + * @return the commands this plugin will register + */ + public Map> getCommands() { + return commands; + } + + /** + * Gives the list of permissions the plugin will register at runtime, + * immediately proceding enabling. The format for defining permissions is + * a map from permission name to properties. To represent a map without + * any specific property, empty curly-braces ( + * {} ) may be used (as a null value is not + * accepted, unlike the {@link #getCommands() commands} above). + *

            + * A list of optional properties for permissions: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
            NodeDescriptionExample
            descriptionPlaintext (user-friendly) description of what the permission + * is for.
            description: Allows you to set yourself on fire
            defaultThe default state for the permission, as defined by {@link + * Permission#getDefault()}. If not defined, it will be set to + * the value of {@link PluginDescriptionFile#getPermissionDefault()}. + *

            + * For reference:

              + *
            • true - Represents a positive assignment to + * {@link Permissible permissibles}. + *
            • false - Represents no assignment to {@link + * Permissible permissibles}. + *
            • op - Represents a positive assignment to + * {@link Permissible#isOp() operator permissibles}. + *
            • notop - Represents a positive assignment to + * {@link Permissible#isOp() non-operator permissibiles}. + *
            default: true
            childrenAllows other permissions to be set as a {@linkplain + * Permission#getChildren() relation} to the parent permission. + * When a parent permissions is assigned, child permissions are + * respectively assigned as well. + *
              + *
            • When a parent permission is assigned negatively, child + * permissions are assigned based on an inversion of their + * association. + *
            • When a parent permission is assigned positively, child + * permissions are assigned based on their association. + *
            + *

            + * Child permissions may be defined in a number of ways:

              + *
            • Children may be defined as a list of + * names. Using a list will treat all children associated + * positively to their parent. + *
            • Children may be defined as a map. Each permission name maps + * to either a boolean (representing the association), or a + * nested permission definition (just as another permission). + * Using a nested definition treats the child as a positive + * association. + *
            • A nested permission definition must be a map of these same + * properties. To define a valid nested permission without + * defining any specific property, empty curly-braces ( + * {} ) must be used. + *
            • A nested permission may carry it's own nested permissions + * as children, as they may also have nested permissions, and + * so forth. There is no direct limit to how deep the + * permission tree is defined. + *
            As a list: + *
            children: [inferno.flagrate, inferno.burningdeaths]
            + * Or as a mapping: + *
            children:
            +     *  inferno.flagrate: true
            +     *  inferno.burningdeaths: true
            + * An additional example showing basic nested values can be seen + * here. + *
            + * The permissions are structured as a hiearchy of nested mappings. + * The primary (top-level, no intendentation) node is + * `permissions', while each individual permission name is + * indented, indicating it maps to some value (in our case, the + * properties of the table above). + *

            + * Here is an example using some of the properties:

            +     *permissions:
            +     *  inferno.*:
            +     *    description: Gives access to all Inferno commands
            +     *    children:
            +     *      inferno.flagrate: true
            +     *      inferno.burningdeaths: true
            +     *  inferno.flagate:
            +     *    description: Allows you to ignite yourself
            +     *    default: true
            +     *  inferno.burningdeaths:
            +     *    description: Allows you to see how many times you have burned to death
            +     *    default: true
            +     *
            + * Another example, with nested definitions, can be found here. + */ + public List getPermissions() { + if (permissions == null) { + if (lazyPermissions == null) { + permissions = ImmutableList.of(); + } else { + permissions = ImmutableList.copyOf(Permission.loadPermissions(lazyPermissions, "Permission node '%s' in plugin description file for " + getFullName() + " is invalid", defaultPerm)); + lazyPermissions = null; + } + } + return permissions; + } + + /** + * Gives the default {@link Permission#getDefault() default} state of + * {@link #getPermissions() permissions} registered for the plugin. + *
              + *
            • If not specified, it will be {@link PermissionDefault#OP}. + *
            • It is matched using {@link PermissionDefault#getByName(String)} + *
            • It only affects permissions that do not define the + * default node. + *
            • It may be any value in {@link PermissionDefault}. + *
            + *

            + * In the plugin.yml, this entry is named default-permission. + *

            + * Example:

            default-permission: NOT_OP
            + * + * @return the default value for the plugin's permissions + */ + public PermissionDefault getPermissionDefault() { + return defaultPerm; + } + + /** + * Gives a set of every {@link PluginAwareness} for a plugin. An awareness + * dictates something that a plugin developer acknowledges when the plugin + * is compiled. Some implementions may define extra awarenesses that are + * not included in the API. Any unrecognized + * awareness (one unsupported or in a future version) will cause a dummy + * object to be created instead of failing. + *

            + *

              + *
            • Currently only supports the enumerated values in {@link + * PluginAwareness.Flags}. + *
            • Each awareness starts the identifier with bang-at + * (!@). + *
            • Unrecognized (future / unimplemented) entries are quietly replaced + * by a generic object that implements PluginAwareness. + *
            • A type of awareness must be defined by the runtime and acknowledged + * by the API, effectively discluding any derived type from any + * plugin's classpath. + *
            • awareness must be in YAML list + * format. + *
            + *

            + * In the plugin.yml, this entry is named awareness. + *

            + * Example:

            awareness:
            +     *- !@UTF8
            + *

            + * Note: Although unknown versions of some future awareness are + * gracefully substituted, previous versions of Bukkit (ones prior to the + * first implementation of awareness) will fail to load a plugin that + * defines any awareness. + * + * @return a set containing every awareness for the plugin + */ + public Set getAwareness() { + return awareness; + } + + /** + * Returns the name of a plugin, including the version. This method is + * provided for convenience; it uses the {@link #getName()} and {@link + * #getVersion()} entries. + * + * @return a descriptive name of the plugin and respective version + */ + public String getFullName() { + return name + " v" + version; + } + + /** + * @deprecated unused + */ + @Deprecated + public String getClassLoaderOf() { + return classLoaderOf; + } + + public void setDatabaseEnabled(boolean database) { + this.database = database; + } + + /** + * Saves this PluginDescriptionFile to the given writer + * + * @param writer Writer to output this file to + */ + public void save(Writer writer) { + YAML.get().dump(saveMap(), writer); + } + + private void loadMap(Map map) throws InvalidDescriptionException { + try { + name = rawName = map.get("name").toString(); + + if (!name.matches("^[A-Za-z0-9 _.-]+$")) { + throw new InvalidDescriptionException("name '" + name + "' contains invalid characters."); + } + name = name.replace(' ', '_'); + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "name is not defined"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "name is of wrong type"); + } + + try { + version = map.get("version").toString(); + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "version is not defined"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "version is of wrong type"); + } + + try { + main = map.get("main").toString(); + if (main.startsWith("org.bukkit.")) { + throw new InvalidDescriptionException("main may not be within the org.bukkit namespace"); + } + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "main is not defined"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "main is of wrong type"); + } + + if (map.get("commands") != null) { + ImmutableMap.Builder> commandsBuilder = ImmutableMap.>builder(); + try { + for (Map.Entry command : ((Map) map.get("commands")).entrySet()) { + ImmutableMap.Builder commandBuilder = ImmutableMap.builder(); + if (command.getValue() != null) { + for (Map.Entry commandEntry : ((Map) command.getValue()).entrySet()) { + if (commandEntry.getValue() instanceof Iterable) { + // This prevents internal alias list changes + ImmutableList.Builder commandSubList = ImmutableList.builder(); + for (Object commandSubListItem : (Iterable) commandEntry.getValue()) { + if (commandSubListItem != null) { + commandSubList.add(commandSubListItem); + } + } + commandBuilder.put(commandEntry.getKey().toString(), commandSubList.build()); + } else if (commandEntry.getValue() != null) { + commandBuilder.put(commandEntry.getKey().toString(), commandEntry.getValue()); + } + } + } + commandsBuilder.put(command.getKey().toString(), commandBuilder.build()); + } + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "commands are of wrong type"); + } + commands = commandsBuilder.build(); + } + + if (map.get("class-loader-of") != null) { + classLoaderOf = map.get("class-loader-of").toString(); + } + + depend = makePluginNameList(map, "depend"); + softDepend = makePluginNameList(map, "softdepend"); + loadBefore = makePluginNameList(map, "loadbefore"); + + if (map.get("database") != null) { + try { + database = (Boolean) map.get("database"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "database is of wrong type"); + } + } + + if (map.get("website") != null) { + website = map.get("website").toString(); + } + + if (map.get("description") != null) { + description = map.get("description").toString(); + } + + if (map.get("load") != null) { + try { + order = PluginLoadOrder.valueOf(((String) map.get("load")).toUpperCase().replaceAll("\\W", "")); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "load is of wrong type"); + } catch (IllegalArgumentException ex) { + throw new InvalidDescriptionException(ex, "load is not a valid choice"); + } + } + + if (map.get("authors") != null) { + ImmutableList.Builder authorsBuilder = ImmutableList.builder(); + if (map.get("author") != null) { + authorsBuilder.add(map.get("author").toString()); + } + try { + for (Object o : (Iterable) map.get("authors")) { + authorsBuilder.add(o.toString()); + } + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "authors are of wrong type"); + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "authors are improperly defined"); + } + authors = authorsBuilder.build(); + } else if (map.get("author") != null) { + authors = ImmutableList.of(map.get("author").toString()); + } else { + authors = ImmutableList.of(); + } + + if (map.get("default-permission") != null) { + try { + defaultPerm = PermissionDefault.getByName(map.get("default-permission").toString()); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "default-permission is of wrong type"); + } catch (IllegalArgumentException ex) { + throw new InvalidDescriptionException(ex, "default-permission is not a valid choice"); + } + } + + if (map.get("awareness") instanceof Iterable) { + Set awareness = new HashSet(); + try { + for (Object o : (Iterable) map.get("awareness")) { + awareness.add((PluginAwareness) o); + } + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "awareness has wrong type"); + } + this.awareness = ImmutableSet.copyOf(awareness); + } + + try { + lazyPermissions = (Map) map.get("permissions"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "permissions are of the wrong type"); + } + + if (map.get("prefix") != null) { + prefix = map.get("prefix").toString(); + } + } + + private static List makePluginNameList(final Map map, final String key) throws InvalidDescriptionException { + final Object value = map.get(key); + if (value == null) { + return ImmutableList.of(); + } + + final ImmutableList.Builder builder = ImmutableList.builder(); + try { + for (final Object entry : (Iterable) value) { + builder.add(entry.toString().replace(' ', '_')); + } + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, key + " is of wrong type"); + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "invalid " + key + " format"); + } + return builder.build(); + } + + private Map saveMap() { + Map map = new HashMap(); + + map.put("name", name); + map.put("main", main); + map.put("version", version); + map.put("database", database); + map.put("order", order.toString()); + map.put("default-permission", defaultPerm.toString()); + + if (commands != null) { + map.put("command", commands); + } + if (depend != null) { + map.put("depend", depend); + } + if (softDepend != null) { + map.put("softdepend", softDepend); + } + if (website != null) { + map.put("website", website); + } + if (description != null) { + map.put("description", description); + } + + if (authors.size() == 1) { + map.put("author", authors.get(0)); + } else if (authors.size() > 1) { + map.put("authors", authors); + } + + if (classLoaderOf != null) { + map.put("class-loader-of", classLoaderOf); + } + + if (prefix != null) { + map.put("prefix", prefix); + } + + return map; + } + + private Map asMap(Object object) throws InvalidDescriptionException { + if (object instanceof Map) { + return (Map) object; + } + throw new InvalidDescriptionException(object + " is not properly structured."); + } + + /** + * @deprecated Internal use + */ + @Deprecated + public String getRawName() { + return rawName; + } +} diff --git a/src/main/java/org/bukkit/plugin/PluginLoadOrder.java b/src/main/java/org/bukkit/plugin/PluginLoadOrder.java new file mode 100644 index 0000000..b77436f --- /dev/null +++ b/src/main/java/org/bukkit/plugin/PluginLoadOrder.java @@ -0,0 +1,17 @@ +package org.bukkit.plugin; + +/** + * Represents the order in which a plugin should be initialized and enabled + */ +public enum PluginLoadOrder { + + /** + * Indicates that the plugin will be loaded at startup + */ + STARTUP, + /** + * Indicates that the plugin will be loaded after the first/default world + * was created + */ + POSTWORLD +} diff --git a/src/main/java/org/bukkit/plugin/PluginLoader.java b/src/main/java/org/bukkit/plugin/PluginLoader.java new file mode 100644 index 0000000..e7981a1 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/PluginLoader.java @@ -0,0 +1,76 @@ +package org.bukkit.plugin; + +import java.io.File; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +import org.bukkit.event.Event; +import org.bukkit.event.Listener; + +/** + * Represents a plugin loader, which handles direct access to specific types + * of plugins + */ +public interface PluginLoader { + + /** + * Loads the plugin contained in the specified file + * + * @param file File to attempt to load + * @return Plugin that was contained in the specified file, or null if + * unsuccessful + * @throws InvalidPluginException Thrown when the specified file is not a + * plugin + * @throws UnknownDependencyException If a required dependency could not + * be found + */ + public Plugin loadPlugin(File file) throws InvalidPluginException, UnknownDependencyException; + + /** + * Loads a PluginDescriptionFile from the specified file + * + * @param file File to attempt to load from + * @return A new PluginDescriptionFile loaded from the plugin.yml in the + * specified file + * @throws InvalidDescriptionException If the plugin description file + * could not be created + */ + public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException; + + /** + * Returns a list of all filename filters expected by this PluginLoader + * + * @return The filters + */ + public Pattern[] getPluginFileFilters(); + + /** + * Creates and returns registered listeners for the event classes used in + * this listener + * + * @param listener The object that will handle the eventual call back + * @param plugin The plugin to use when creating registered listeners + * @return The registered listeners. + */ + public Map, Set> createRegisteredListeners(Listener listener, Plugin plugin); + + /** + * Enables the specified plugin + *

            + * Attempting to enable a plugin that is already enabled will have no + * effect + * + * @param plugin Plugin to enable + */ + public void enablePlugin(Plugin plugin); + + /** + * Disables the specified plugin + *

            + * Attempting to disable a plugin that is not enabled will have no effect + * + * @param plugin Plugin to disable + */ + public void disablePlugin(Plugin plugin); +} diff --git a/src/main/java/org/bukkit/plugin/PluginLogger.java b/src/main/java/org/bukkit/plugin/PluginLogger.java new file mode 100644 index 0000000..f43c10b --- /dev/null +++ b/src/main/java/org/bukkit/plugin/PluginLogger.java @@ -0,0 +1,36 @@ +package org.bukkit.plugin; + +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +/** + * The PluginLogger class is a modified {@link Logger} that prepends all + * logging calls with the name of the plugin doing the logging. The API for + * PluginLogger is exactly the same as {@link Logger}. + * + * @see Logger + */ +public class PluginLogger extends Logger { + private String pluginName; + + /** + * Creates a new PluginLogger that extracts the name from a plugin. + * + * @param context A reference to the plugin + */ + public PluginLogger(Plugin context) { + super(context.getClass().getCanonicalName(), null); + String prefix = context.getDescription().getPrefix(); + pluginName = prefix != null ? new StringBuilder().append("[").append(prefix).append("] ").toString() : "[" + context.getDescription().getName() + "] "; + setParent(context.getServer().getLogger()); + setLevel(Level.ALL); + } + + @Override + public void log(LogRecord logRecord) { + logRecord.setMessage(pluginName + logRecord.getMessage()); + super.log(logRecord); + } + +} diff --git a/src/main/java/org/bukkit/plugin/PluginManager.java b/src/main/java/org/bukkit/plugin/PluginManager.java new file mode 100644 index 0000000..e5638d5 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/PluginManager.java @@ -0,0 +1,294 @@ +package org.bukkit.plugin; + +import java.io.File; +import java.util.Set; + +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; + +/** + * Handles all plugin management from the Server + */ +public interface PluginManager { + + /** + * Registers the specified plugin loader + * + * @param loader Class name of the PluginLoader to register + * @throws IllegalArgumentException Thrown when the given Class is not a + * valid PluginLoader + */ + public void registerInterface(Class loader) throws IllegalArgumentException; + + /** + * Checks if the given plugin is loaded and returns it when applicable + *

            + * Please note that the name of the plugin is case-sensitive + * + * @param name Name of the plugin to check + * @return Plugin if it exists, otherwise null + */ + public Plugin getPlugin(String name); + + /** + * Gets a list of all currently loaded plugins + * + * @return Array of Plugins + */ + public Plugin[] getPlugins(); + + /** + * Checks if the given plugin is enabled or not + *

            + * Please note that the name of the plugin is case-sensitive. + * + * @param name Name of the plugin to check + * @return true if the plugin is enabled, otherwise false + */ + public boolean isPluginEnabled(String name); + + /** + * Checks if the given plugin is enabled or not + * + * @param plugin Plugin to check + * @return true if the plugin is enabled, otherwise false + */ + public boolean isPluginEnabled(Plugin plugin); + + /** + * Loads the plugin in the specified file + *

            + * File must be valid according to the current enabled Plugin interfaces + * + * @param file File containing the plugin to load + * @return The Plugin loaded, or null if it was invalid + * @throws InvalidPluginException Thrown when the specified file is not a + * valid plugin + * @throws InvalidDescriptionException Thrown when the specified file + * contains an invalid description + * @throws UnknownDependencyException If a required dependency could not + * be resolved + */ + public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException; + + /** + * Loads the plugins contained within the specified directory + * + * @param directory Directory to check for plugins + * @return A list of all plugins loaded + */ + public Plugin[] loadPlugins(File directory); + + /** + * Disables all the loaded plugins + */ + public void disablePlugins(); + + /** + * Disables and removes all plugins + */ + public void clearPlugins(); + + /** + * Calls an event with the given details + * + * @param event Event details + * @throws IllegalStateException Thrown when an asynchronous event is + * fired from synchronous code. + *

            + * Note: This is best-effort basis, and should not be used to test + * synchronized state. This is an indicator for flawed flow logic. + */ + public void callEvent(Event event) throws IllegalStateException; + + /** + * Registers all the events in the given listener class + * + * @param listener Listener to register + * @param plugin Plugin to register + */ + public void registerEvents(Listener listener, Plugin plugin); + + /** + * Registers the specified executor to the given event class + * + * @param event Event type to register + * @param listener Listener to register + * @param priority Priority to register this event at + * @param executor EventExecutor to register + * @param plugin Plugin to register + */ + public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin); + + /** + * Registers the specified executor to the given event class + * + * @param event Event type to register + * @param listener Listener to register + * @param priority Priority to register this event at + * @param executor EventExecutor to register + * @param plugin Plugin to register + * @param ignoreCancelled Whether to pass cancelled events or not + */ + public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled); + + /** + * Enables the specified plugin + *

            + * Attempting to enable a plugin that is already enabled will have no + * effect + * + * @param plugin Plugin to enable + */ + public void enablePlugin(Plugin plugin); + + /** + * Disables the specified plugin + *

            + * Attempting to disable a plugin that is not enabled will have no effect + * + * @param plugin Plugin to disable + */ + public void disablePlugin(Plugin plugin); + + /** + * Gets a {@link Permission} from its fully qualified name + * + * @param name Name of the permission + * @return Permission, or null if none + */ + public Permission getPermission(String name); + + /** + * Adds a {@link Permission} to this plugin manager. + *

            + * If a permission is already defined with the given name of the new + * permission, an exception will be thrown. + * + * @param perm Permission to add + * @throws IllegalArgumentException Thrown when a permission with the same + * name already exists + */ + public void addPermission(Permission perm); + + /** + * Removes a {@link Permission} registration from this plugin manager. + *

            + * If the specified permission does not exist in this plugin manager, + * nothing will happen. + *

            + * Removing a permission registration will not remove the + * permission from any {@link Permissible}s that have it. + * + * @param perm Permission to remove + */ + public void removePermission(Permission perm); + + /** + * Removes a {@link Permission} registration from this plugin manager. + *

            + * If the specified permission does not exist in this plugin manager, + * nothing will happen. + *

            + * Removing a permission registration will not remove the + * permission from any {@link Permissible}s that have it. + * + * @param name Permission to remove + */ + public void removePermission(String name); + + /** + * Gets the default permissions for the given op status + * + * @param op Which set of default permissions to get + * @return The default permissions + */ + public Set getDefaultPermissions(boolean op); + + /** + * Recalculates the defaults for the given {@link Permission}. + *

            + * This will have no effect if the specified permission is not registered + * here. + * + * @param perm Permission to recalculate + */ + public void recalculatePermissionDefaults(Permission perm); + + /** + * Subscribes the given Permissible for information about the requested + * Permission, by name. + *

            + * If the specified Permission changes in any form, the Permissible will + * be asked to recalculate. + * + * @param permission Permission to subscribe to + * @param permissible Permissible subscribing + */ + public void subscribeToPermission(String permission, Permissible permissible); + + /** + * Unsubscribes the given Permissible for information about the requested + * Permission, by name. + * + * @param permission Permission to unsubscribe from + * @param permissible Permissible subscribing + */ + public void unsubscribeFromPermission(String permission, Permissible permissible); + + /** + * Gets a set containing all subscribed {@link Permissible}s to the given + * permission, by name + * + * @param permission Permission to query for + * @return Set containing all subscribed permissions + */ + public Set getPermissionSubscriptions(String permission); + + /** + * Subscribes to the given Default permissions by operator status + *

            + * If the specified defaults change in any form, the Permissible will be + * asked to recalculate. + * + * @param op Default list to subscribe to + * @param permissible Permissible subscribing + */ + public void subscribeToDefaultPerms(boolean op, Permissible permissible); + + /** + * Unsubscribes from the given Default permissions by operator status + * + * @param op Default list to unsubscribe from + * @param permissible Permissible subscribing + */ + public void unsubscribeFromDefaultPerms(boolean op, Permissible permissible); + + /** + * Gets a set containing all subscribed {@link Permissible}s to the given + * default list, by op status + * + * @param op Default list to query for + * @return Set containing all subscribed permissions + */ + public Set getDefaultPermSubscriptions(boolean op); + + /** + * Gets a set of all registered permissions. + *

            + * This set is a copy and will not be modified live. + * + * @return Set containing all current registered permissions + */ + public Set getPermissions(); + + /** + * Returns whether or not timing code should be used for event calls + * + * @return True if event timings are to be used + */ + public boolean useTimings(); +} diff --git a/src/main/java/org/bukkit/plugin/RegisteredListener.java b/src/main/java/org/bukkit/plugin/RegisteredListener.java new file mode 100644 index 0000000..9dd0b7a --- /dev/null +++ b/src/main/java/org/bukkit/plugin/RegisteredListener.java @@ -0,0 +1,73 @@ +package org.bukkit.plugin; + +import org.bukkit.event.*; + +/** + * Stores relevant information for plugin listeners + */ +public class RegisteredListener { + private final Listener listener; + private final EventPriority priority; + private final Plugin plugin; + private final EventExecutor executor; + private final boolean ignoreCancelled; + + public RegisteredListener(final Listener listener, final EventExecutor executor, final EventPriority priority, final Plugin plugin, final boolean ignoreCancelled) { + this.listener = listener; + this.priority = priority; + this.plugin = plugin; + this.executor = executor; + this.ignoreCancelled = ignoreCancelled; + } + + /** + * Gets the listener for this registration + * + * @return Registered Listener + */ + public Listener getListener() { + return listener; + } + + /** + * Gets the plugin for this registration + * + * @return Registered Plugin + */ + public Plugin getPlugin() { + return plugin; + } + + /** + * Gets the priority for this registration + * + * @return Registered Priority + */ + public EventPriority getPriority() { + return priority; + } + + /** + * Calls the event executor + * + * @param event The event + * @throws EventException If an event handler throws an exception. + */ + public void callEvent(final Event event) throws EventException { + if (event instanceof Cancellable){ + if (((Cancellable) event).isCancelled() && isIgnoringCancelled()){ + return; + } + } + executor.execute(listener, event); + } + + /** + * Whether this listener accepts cancelled events + * + * @return True when ignoring cancelled events + */ + public boolean isIgnoringCancelled() { + return ignoreCancelled; + } +} diff --git a/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java b/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java new file mode 100644 index 0000000..ba3ff15 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java @@ -0,0 +1,46 @@ +package org.bukkit.plugin; + +/** + * A registered service provider. + * + * @param Service + */ +public class RegisteredServiceProvider implements Comparable> { + + private Class service; + private Plugin plugin; + private T provider; + private ServicePriority priority; + + public RegisteredServiceProvider(Class service, T provider, ServicePriority priority, Plugin plugin) { + + this.service = service; + this.plugin = plugin; + this.provider = provider; + this.priority = priority; + } + + public Class getService() { + return service; + } + + public Plugin getPlugin() { + return plugin; + } + + public T getProvider() { + return provider; + } + + public ServicePriority getPriority() { + return priority; + } + + public int compareTo(RegisteredServiceProvider other) { + if (priority.ordinal() == other.getPriority().ordinal()) { + return 0; + } else { + return priority.ordinal() < other.getPriority().ordinal() ? 1 : -1; + } + } +} diff --git a/src/main/java/org/bukkit/plugin/ServicePriority.java b/src/main/java/org/bukkit/plugin/ServicePriority.java new file mode 100644 index 0000000..4afe0fb --- /dev/null +++ b/src/main/java/org/bukkit/plugin/ServicePriority.java @@ -0,0 +1,12 @@ +package org.bukkit.plugin; + +/** + * Represents various priorities of a provider. + */ +public enum ServicePriority { + Lowest, + Low, + Normal, + High, + Highest +} diff --git a/src/main/java/org/bukkit/plugin/ServicesManager.java b/src/main/java/org/bukkit/plugin/ServicesManager.java new file mode 100644 index 0000000..5d45ffb --- /dev/null +++ b/src/main/java/org/bukkit/plugin/ServicesManager.java @@ -0,0 +1,106 @@ +package org.bukkit.plugin; + +import java.util.Collection; +import java.util.List; + +/** + * Manages services and service providers. Services are an interface + * specifying a list of methods that a provider must implement. Providers are + * implementations of these services. A provider can be queried from the + * services manager in order to use a service (if one is available). If + * multiple plugins register a service, then the service with the highest + * priority takes precedence. + */ +public interface ServicesManager { + + /** + * Register a provider of a service. + * + * @param Provider + * @param service service class + * @param provider provider to register + * @param plugin plugin with the provider + * @param priority priority of the provider + */ + public void register(Class service, T provider, Plugin plugin, ServicePriority priority); + + /** + * Unregister all the providers registered by a particular plugin. + * + * @param plugin The plugin + */ + public void unregisterAll(Plugin plugin); + + /** + * Unregister a particular provider for a particular service. + * + * @param service The service interface + * @param provider The service provider implementation + */ + public void unregister(Class service, Object provider); + + /** + * Unregister a particular provider. + * + * @param provider The service provider implementation + */ + public void unregister(Object provider); + + /** + * Queries for a provider. This may return if no provider has been + * registered for a service. The highest priority provider is returned. + * + * @param The service interface + * @param service The service interface + * @return provider or null + */ + public T load(Class service); + + /** + * Queries for a provider registration. This may return if no provider + * has been registered for a service. + * + * @param The service interface + * @param service The service interface + * @return provider registration or null + */ + public RegisteredServiceProvider getRegistration(Class service); + + /** + * Get registrations of providers for a plugin. + * + * @param plugin The plugin + * @return provider registration or null + */ + public List> getRegistrations(Plugin plugin); + + /** + * Get registrations of providers for a service. The returned list is + * unmodifiable. + * + * @param The service interface + * @param service The service interface + * @return list of registrations + */ + public Collection> getRegistrations(Class service); + + /** + * Get a list of known services. A service is known if it has registered + * providers for it. + * + * @return list of known services + */ + public Collection> getKnownServices(); + + /** + * Returns whether a provider has been registered for a service. Do not + * check this first only to call load(service) later, as that + * would be a non-thread safe situation. + * + * @param service + * @param service service to check + * @return whether there has been a registered provider + */ + public boolean isProvidedFor(Class service); + +} diff --git a/src/main/java/org/bukkit/plugin/SimplePluginManager.java b/src/main/java/org/bukkit/plugin/SimplePluginManager.java new file mode 100644 index 0000000..d2fe422 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/SimplePluginManager.java @@ -0,0 +1,730 @@ +package org.bukkit.plugin; + +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang.Validate; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.PluginCommandYamlParser; +import org.bukkit.command.SimpleCommandMap; +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.util.FileUtil; + +import com.google.common.collect.ImmutableSet; + +/** + * Handles all plugin management from the Server + */ +public final class SimplePluginManager implements PluginManager { + private final Server server; + private final Map fileAssociations = new HashMap(); + private final List plugins = new ArrayList(); + private final Map lookupNames = new HashMap(); + private static File updateDirectory = null; + private final SimpleCommandMap commandMap; + private final Map permissions = new HashMap(); + private final Map> defaultPerms = new LinkedHashMap>(); + private final Map> permSubs = new HashMap>(); + private final Map> defSubs = new HashMap>(); + private boolean useTimings = false; + + public SimplePluginManager(Server instance, SimpleCommandMap commandMap) { + server = instance; + this.commandMap = commandMap; + + defaultPerms.put(true, new HashSet()); + defaultPerms.put(false, new HashSet()); + } + + /** + * Registers the specified plugin loader + * + * @param loader Class name of the PluginLoader to register + * @throws IllegalArgumentException Thrown when the given Class is not a + * valid PluginLoader + */ + public void registerInterface(Class loader) throws IllegalArgumentException { + PluginLoader instance; + + if (PluginLoader.class.isAssignableFrom(loader)) { + Constructor constructor; + + try { + constructor = loader.getConstructor(Server.class); + instance = constructor.newInstance(server); + } catch (NoSuchMethodException ex) { + String className = loader.getName(); + + throw new IllegalArgumentException(String.format("Class %s does not have a public %s(Server) constructor", className, className), ex); + } catch (Exception ex) { + throw new IllegalArgumentException(String.format("Unexpected exception %s while attempting to construct a new instance of %s", ex.getClass().getName(), loader.getName()), ex); + } + } else { + throw new IllegalArgumentException(String.format("Class %s does not implement interface PluginLoader", loader.getName())); + } + + Pattern[] patterns = instance.getPluginFileFilters(); + + synchronized (this) { + for (Pattern pattern : patterns) { + fileAssociations.put(pattern, instance); + } + } + } + + /** + * Loads the plugins contained within the specified directory + * + * @param directory Directory to check for plugins + * @return A list of all plugins loaded + */ + public Plugin[] loadPlugins(File directory) { + Validate.notNull(directory, "Directory cannot be null"); + Validate.isTrue(directory.isDirectory(), "Directory must be a directory"); + + List result = new ArrayList(); + Set filters = fileAssociations.keySet(); + + if (!(server.getUpdateFolder().equals(""))) { + updateDirectory = new File(directory, server.getUpdateFolder()); + } + + Map plugins = new HashMap(); + Set loadedPlugins = new HashSet(); + Map> dependencies = new HashMap>(); + Map> softDependencies = new HashMap>(); + + // This is where it figures out all possible plugins + for (File file : directory.listFiles()) { + PluginLoader loader = null; + for (Pattern filter : filters) { + Matcher match = filter.matcher(file.getName()); + if (match.find()) { + loader = fileAssociations.get(filter); + } + } + + if (loader == null) continue; + + PluginDescriptionFile description = null; + try { + description = loader.getPluginDescription(file); + String name = description.getName(); + if (name.equalsIgnoreCase("bukkit") || name.equalsIgnoreCase("minecraft") || name.equalsIgnoreCase("mojang")) { + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': Restricted Name"); + continue; + } else if (description.rawName.indexOf(' ') != -1) { + server.getLogger().warning(String.format( + "Plugin `%s' uses the space-character (0x20) in its name `%s' - this is discouraged", + description.getFullName(), + description.rawName + )); + } + } catch (InvalidDescriptionException ex) { + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "'", ex); + continue; + } + + File replacedFile = plugins.put(description.getName(), file); + if (replacedFile != null) { + server.getLogger().severe(String.format( + "Ambiguous plugin name `%s' for files `%s' and `%s' in `%s'", + description.getName(), + file.getPath(), + replacedFile.getPath(), + directory.getPath() + )); + } + + Collection softDependencySet = description.getSoftDepend(); + if (softDependencySet != null && !softDependencySet.isEmpty()) { + if (softDependencies.containsKey(description.getName())) { + // Duplicates do not matter, they will be removed together if applicable + softDependencies.get(description.getName()).addAll(softDependencySet); + } else { + softDependencies.put(description.getName(), new LinkedList(softDependencySet)); + } + } + + Collection dependencySet = description.getDepend(); + if (dependencySet != null && !dependencySet.isEmpty()) { + dependencies.put(description.getName(), new LinkedList(dependencySet)); + } + + Collection loadBeforeSet = description.getLoadBefore(); + if (loadBeforeSet != null && !loadBeforeSet.isEmpty()) { + for (String loadBeforeTarget : loadBeforeSet) { + if (softDependencies.containsKey(loadBeforeTarget)) { + softDependencies.get(loadBeforeTarget).add(description.getName()); + } else { + // softDependencies is never iterated, so 'ghost' plugins aren't an issue + Collection shortSoftDependency = new LinkedList(); + shortSoftDependency.add(description.getName()); + softDependencies.put(loadBeforeTarget, shortSoftDependency); + } + } + } + } + + while (!plugins.isEmpty()) { + boolean missingDependency = true; + Iterator pluginIterator = plugins.keySet().iterator(); + + while (pluginIterator.hasNext()) { + String plugin = pluginIterator.next(); + + if (dependencies.containsKey(plugin)) { + Iterator dependencyIterator = dependencies.get(plugin).iterator(); + + while (dependencyIterator.hasNext()) { + String dependency = dependencyIterator.next(); + + // Dependency loaded + if (loadedPlugins.contains(dependency)) { + dependencyIterator.remove(); + + // We have a dependency not found + } else if (!plugins.containsKey(dependency)) { + missingDependency = false; + File file = plugins.get(plugin); + pluginIterator.remove(); + softDependencies.remove(plugin); + dependencies.remove(plugin); + + server.getLogger().log( + Level.SEVERE, + "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "'", + new UnknownDependencyException(dependency)); + break; + } + } + + if (dependencies.containsKey(plugin) && dependencies.get(plugin).isEmpty()) { + dependencies.remove(plugin); + } + } + if (softDependencies.containsKey(plugin)) { + Iterator softDependencyIterator = softDependencies.get(plugin).iterator(); + + while (softDependencyIterator.hasNext()) { + String softDependency = softDependencyIterator.next(); + + // Soft depend is no longer around + if (!plugins.containsKey(softDependency)) { + softDependencyIterator.remove(); + } + } + + if (softDependencies.get(plugin).isEmpty()) { + softDependencies.remove(plugin); + } + } + if (!(dependencies.containsKey(plugin) || softDependencies.containsKey(plugin)) && plugins.containsKey(plugin)) { + // We're clear to load, no more soft or hard dependencies left + File file = plugins.get(plugin); + pluginIterator.remove(); + missingDependency = false; + + try { + result.add(loadPlugin(file)); + loadedPlugins.add(plugin); + continue; + } catch (InvalidPluginException ex) { + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "'", ex); + } + } + } + + if (missingDependency) { + // We now iterate over plugins until something loads + // This loop will ignore soft dependencies + pluginIterator = plugins.keySet().iterator(); + + while (pluginIterator.hasNext()) { + String plugin = pluginIterator.next(); + + if (!dependencies.containsKey(plugin)) { + softDependencies.remove(plugin); + missingDependency = false; + File file = plugins.get(plugin); + pluginIterator.remove(); + + try { + result.add(loadPlugin(file)); + loadedPlugins.add(plugin); + break; + } catch (InvalidPluginException ex) { + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "'", ex); + } + } + } + // We have no plugins left without a depend + if (missingDependency) { + softDependencies.clear(); + dependencies.clear(); + Iterator failedPluginIterator = plugins.values().iterator(); + + while (failedPluginIterator.hasNext()) { + File file = failedPluginIterator.next(); + failedPluginIterator.remove(); + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': circular dependency detected"); + } + } + } + } + + return result.toArray(new Plugin[result.size()]); + } + + /** + * Loads the plugin in the specified file + *

            + * File must be valid according to the current enabled Plugin interfaces + * + * @param file File containing the plugin to load + * @return The Plugin loaded, or null if it was invalid + * @throws InvalidPluginException Thrown when the specified file is not a + * valid plugin + * @throws UnknownDependencyException If a required dependency could not + * be found + */ + public synchronized Plugin loadPlugin(File file) throws InvalidPluginException, UnknownDependencyException { + Validate.notNull(file, "File cannot be null"); + + checkUpdate(file); + + Set filters = fileAssociations.keySet(); + Plugin result = null; + + for (Pattern filter : filters) { + String name = file.getName(); + Matcher match = filter.matcher(name); + + if (match.find()) { + PluginLoader loader = fileAssociations.get(filter); + + result = loader.loadPlugin(file); + } + } + + if (result != null) { + plugins.add(result); + lookupNames.put(result.getDescription().getName(), result); + } + + return result; + } + + private void checkUpdate(File file) { + if (updateDirectory == null || !updateDirectory.isDirectory()) { + return; + } + + File updateFile = new File(updateDirectory, file.getName()); + if (updateFile.isFile() && FileUtil.copy(updateFile, file)) { + updateFile.delete(); + } + } + + /** + * Checks if the given plugin is loaded and returns it when applicable + *

            + * Please note that the name of the plugin is case-sensitive + * + * @param name Name of the plugin to check + * @return Plugin if it exists, otherwise null + */ + public synchronized Plugin getPlugin(String name) { + return lookupNames.get(name.replace(' ', '_')); + } + + public synchronized Plugin[] getPlugins() { + return plugins.toArray(new Plugin[0]); + } + + /** + * Checks if the given plugin is enabled or not + *

            + * Please note that the name of the plugin is case-sensitive. + * + * @param name Name of the plugin to check + * @return true if the plugin is enabled, otherwise false + */ + public boolean isPluginEnabled(String name) { + Plugin plugin = getPlugin(name); + + return isPluginEnabled(plugin); + } + + /** + * Checks if the given plugin is enabled or not + * + * @param plugin Plugin to check + * @return true if the plugin is enabled, otherwise false + */ + public boolean isPluginEnabled(Plugin plugin) { + if ((plugin != null) && (plugins.contains(plugin))) { + return plugin.isEnabled(); + } else { + return false; + } + } + + public void enablePlugin(final Plugin plugin) { + if (!plugin.isEnabled()) { + List pluginCommands = PluginCommandYamlParser.parse(plugin); + + if (!pluginCommands.isEmpty()) { + commandMap.registerAll(plugin.getDescription().getName(), pluginCommands); + } + + try { + plugin.getPluginLoader().enablePlugin(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while enabling " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + HandlerList.bakeAll(); + } + } + + public void disablePlugins() { + Plugin[] plugins = getPlugins(); + for (int i = plugins.length - 1; i >= 0; i--) { + disablePlugin(plugins[i]); + } + } + + public void disablePlugin(final Plugin plugin) { + if (plugin.isEnabled()) { + try { + plugin.getPluginLoader().disablePlugin(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while disabling " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + try { + server.getScheduler().cancelTasks(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while cancelling tasks for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + try { + server.getServicesManager().unregisterAll(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while unregistering services for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + try { + HandlerList.unregisterAll(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while unregistering events for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + try { + server.getMessenger().unregisterIncomingPluginChannel(plugin); + server.getMessenger().unregisterOutgoingPluginChannel(plugin); + } catch(Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while unregistering plugin channels for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + } + } + + public void clearPlugins() { + synchronized (this) { + disablePlugins(); + plugins.clear(); + lookupNames.clear(); + HandlerList.unregisterAll(); + fileAssociations.clear(); + permissions.clear(); + defaultPerms.get(true).clear(); + defaultPerms.get(false).clear(); + } + } + + /** + * Calls an event with the given details. + *

            + * This method only synchronizes when the event is not asynchronous. + * + * @param event Event details + */ + public void callEvent(Event event) { + if (event.isAsynchronous()) { + if (Thread.holdsLock(this)) { + throw new IllegalStateException(event.getEventName() + " cannot be triggered asynchronously from inside synchronized code."); + } + if (server.isPrimaryThread()) { + throw new IllegalStateException(event.getEventName() + " cannot be triggered asynchronously from primary server thread."); + } + fireEvent(event); + } else { + synchronized (this) { + fireEvent(event); + } + } + } + + private void fireEvent(Event event) { + HandlerList handlers = event.getHandlers(); + RegisteredListener[] listeners = handlers.getRegisteredListeners(); + + for (RegisteredListener registration : listeners) { + if (!registration.getPlugin().isEnabled()) { + continue; + } + + try { + registration.callEvent(event); + } catch (AuthorNagException ex) { + Plugin plugin = registration.getPlugin(); + + if (plugin.isNaggable()) { + plugin.setNaggable(false); + + server.getLogger().log(Level.SEVERE, String.format( + "Nag author(s): '%s' of '%s' about the following: %s", + plugin.getDescription().getAuthors(), + plugin.getDescription().getFullName(), + ex.getMessage() + )); + } + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Could not pass event " + event.getEventName() + " to " + registration.getPlugin().getDescription().getFullName(), ex); + } + } + } + + public void registerEvents(Listener listener, Plugin plugin) { + if (!plugin.isEnabled()) { + throw new IllegalPluginAccessException("Plugin attempted to register " + listener + " while not enabled"); + } + + for (Map.Entry, Set> entry : plugin.getPluginLoader().createRegisteredListeners(listener, plugin).entrySet()) { + getEventListeners(getRegistrationClass(entry.getKey())).registerAll(entry.getValue()); + } + + } + + public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin) { + registerEvent(event, listener, priority, executor, plugin, false); + } + + /** + * Registers the given event to the specified listener using a directly + * passed EventExecutor + * + * @param event Event class to register + * @param listener PlayerListener to register + * @param priority Priority of this event + * @param executor EventExecutor to register + * @param plugin Plugin to register + * @param ignoreCancelled Do not call executor if event was already + * cancelled + */ + public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) { + Validate.notNull(listener, "Listener cannot be null"); + Validate.notNull(priority, "Priority cannot be null"); + Validate.notNull(executor, "Executor cannot be null"); + Validate.notNull(plugin, "Plugin cannot be null"); + + if (!plugin.isEnabled()) { + throw new IllegalPluginAccessException("Plugin attempted to register " + event + " while not enabled"); + } + + if (useTimings) { + getEventListeners(event).register(new TimedRegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); + } else { + getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); + } + } + + private HandlerList getEventListeners(Class type) { + try { + Method method = getRegistrationClass(type).getDeclaredMethod("getHandlerList"); + method.setAccessible(true); + return (HandlerList) method.invoke(null); + } catch (Exception e) { + throw new IllegalPluginAccessException(e.toString()); + } + } + + private Class getRegistrationClass(Class clazz) { + try { + clazz.getDeclaredMethod("getHandlerList"); + return clazz; + } catch (NoSuchMethodException e) { + if (clazz.getSuperclass() != null + && !clazz.getSuperclass().equals(Event.class) + && Event.class.isAssignableFrom(clazz.getSuperclass())) { + return getRegistrationClass(clazz.getSuperclass().asSubclass(Event.class)); + } else { + throw new IllegalPluginAccessException("Unable to find handler list for event " + clazz.getName()); + } + } + } + + public Permission getPermission(String name) { + return permissions.get(name.toLowerCase()); + } + + public void addPermission(Permission perm) { + String name = perm.getName().toLowerCase(); + + if (permissions.containsKey(name)) { + throw new IllegalArgumentException("The permission " + name + " is already defined!"); + } + + permissions.put(name, perm); + calculatePermissionDefault(perm); + } + + public Set getDefaultPermissions(boolean op) { + return ImmutableSet.copyOf(defaultPerms.get(op)); + } + + public void removePermission(Permission perm) { + removePermission(perm.getName()); + } + + public void removePermission(String name) { + permissions.remove(name.toLowerCase()); + } + + public void recalculatePermissionDefaults(Permission perm) { + if (permissions.containsValue(perm)) { + defaultPerms.get(true).remove(perm); + defaultPerms.get(false).remove(perm); + + calculatePermissionDefault(perm); + } + } + + private void calculatePermissionDefault(Permission perm) { + if ((perm.getDefault() == PermissionDefault.OP) || (perm.getDefault() == PermissionDefault.TRUE)) { + defaultPerms.get(true).add(perm); + dirtyPermissibles(true); + } + if ((perm.getDefault() == PermissionDefault.NOT_OP) || (perm.getDefault() == PermissionDefault.TRUE)) { + defaultPerms.get(false).add(perm); + dirtyPermissibles(false); + } + } + + private void dirtyPermissibles(boolean op) { + Set permissibles = getDefaultPermSubscriptions(op); + + for (Permissible p : permissibles) { + p.recalculatePermissions(); + } + } + + public void subscribeToPermission(String permission, Permissible permissible) { + String name = permission.toLowerCase(); + Map map = permSubs.get(name); + + if (map == null) { + map = new WeakHashMap(); + permSubs.put(name, map); + } + + map.put(permissible, true); + } + + public void unsubscribeFromPermission(String permission, Permissible permissible) { + String name = permission.toLowerCase(); + Map map = permSubs.get(name); + + if (map != null) { + map.remove(permissible); + + if (map.isEmpty()) { + permSubs.remove(name); + } + } + } + + public Set getPermissionSubscriptions(String permission) { + String name = permission.toLowerCase(); + Map map = permSubs.get(name); + + if (map == null) { + return ImmutableSet.of(); + } else { + return ImmutableSet.copyOf(map.keySet()); + } + } + + public void subscribeToDefaultPerms(boolean op, Permissible permissible) { + Map map = defSubs.get(op); + + if (map == null) { + map = new WeakHashMap(); + defSubs.put(op, map); + } + + map.put(permissible, true); + } + + public void unsubscribeFromDefaultPerms(boolean op, Permissible permissible) { + Map map = defSubs.get(op); + + if (map != null) { + map.remove(permissible); + + if (map.isEmpty()) { + defSubs.remove(op); + } + } + } + + public Set getDefaultPermSubscriptions(boolean op) { + Map map = defSubs.get(op); + + if (map == null) { + return ImmutableSet.of(); + } else { + return ImmutableSet.copyOf(map.keySet()); + } + } + + public Set getPermissions() { + return new HashSet(permissions.values()); + } + + public boolean useTimings() { + return useTimings; + } + + /** + * Sets whether or not per event timing code should be used + * + * @param use True if per event timing code should be used + */ + public void useTimings(boolean use) { + useTimings = use; + } +} diff --git a/src/main/java/org/bukkit/plugin/SimpleServicesManager.java b/src/main/java/org/bukkit/plugin/SimpleServicesManager.java new file mode 100644 index 0000000..4e17711 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/SimpleServicesManager.java @@ -0,0 +1,306 @@ +package org.bukkit.plugin; + +import org.bukkit.Bukkit; +import org.bukkit.event.server.ServiceRegisterEvent; +import org.bukkit.event.server.ServiceUnregisterEvent; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +/** + * A simple services manager. + */ +public class SimpleServicesManager implements ServicesManager { + + /** + * Map of providers. + */ + private final Map, List>> providers = new HashMap, List>>(); + + /** + * Register a provider of a service. + * + * @param Provider + * @param service service class + * @param provider provider to register + * @param plugin plugin with the provider + * @param priority priority of the provider + */ + public void register(Class service, T provider, Plugin plugin, ServicePriority priority) { + RegisteredServiceProvider registeredProvider = null; + synchronized (providers) { + List> registered = providers.get(service); + if (registered == null) { + registered = new ArrayList>(); + providers.put(service, registered); + } + + registeredProvider = new RegisteredServiceProvider(service, provider, priority, plugin); + + // Insert the provider into the collection, much more efficient big O than sort + int position = Collections.binarySearch(registered, registeredProvider); + if (position < 0) { + registered.add(-(position + 1), registeredProvider); + } else { + registered.add(position, registeredProvider); + } + + } + Bukkit.getServer().getPluginManager().callEvent(new ServiceRegisterEvent(registeredProvider)); + } + + /** + * Unregister all the providers registered by a particular plugin. + * + * @param plugin The plugin + */ + public void unregisterAll(Plugin plugin) { + ArrayList unregisteredEvents = new ArrayList(); + synchronized (providers) { + Iterator, List>>> it = providers.entrySet().iterator(); + + try { + while (it.hasNext()) { + Map.Entry, List>> entry = it.next(); + Iterator> it2 = entry.getValue().iterator(); + + try { + // Removed entries that are from this plugin + + while (it2.hasNext()) { + RegisteredServiceProvider registered = it2.next(); + + if (registered.getPlugin().equals(plugin)) { + it2.remove(); + unregisteredEvents.add(new ServiceUnregisterEvent(registered)); + } + } + } catch (NoSuchElementException e) { // Why does Java suck + } + + // Get rid of the empty list + if (entry.getValue().size() == 0) { + it.remove(); + } + } + } catch (NoSuchElementException e) {} + } + for (ServiceUnregisterEvent event : unregisteredEvents) { + Bukkit.getServer().getPluginManager().callEvent(event); + } + } + + /** + * Unregister a particular provider for a particular service. + * + * @param service The service interface + * @param provider The service provider implementation + */ + public void unregister(Class service, Object provider) { + ArrayList unregisteredEvents = new ArrayList(); + synchronized (providers) { + Iterator, List>>> it = providers.entrySet().iterator(); + + try { + while (it.hasNext()) { + Map.Entry, List>> entry = it.next(); + + // We want a particular service + if (entry.getKey() != service) { + continue; + } + + Iterator> it2 = entry.getValue().iterator(); + + try { + // Removed entries that are from this plugin + + while (it2.hasNext()) { + RegisteredServiceProvider registered = it2.next(); + + if (registered.getProvider() == provider) { + it2.remove(); + unregisteredEvents.add(new ServiceUnregisterEvent(registered)); + } + } + } catch (NoSuchElementException e) { // Why does Java suck + } + + // Get rid of the empty list + if (entry.getValue().size() == 0) { + it.remove(); + } + } + } catch (NoSuchElementException e) {} + } + for (ServiceUnregisterEvent event : unregisteredEvents) { + Bukkit.getServer().getPluginManager().callEvent(event); + } + } + + /** + * Unregister a particular provider. + * + * @param provider The service provider implementation + */ + public void unregister(Object provider) { + ArrayList unregisteredEvents = new ArrayList(); + synchronized (providers) { + Iterator, List>>> it = providers.entrySet().iterator(); + + try { + while (it.hasNext()) { + Map.Entry, List>> entry = it.next(); + Iterator> it2 = entry.getValue().iterator(); + + try { + // Removed entries that are from this plugin + + while (it2.hasNext()) { + RegisteredServiceProvider registered = it2.next(); + + if (registered.getProvider().equals(provider)) { + it2.remove(); + unregisteredEvents.add(new ServiceUnregisterEvent(registered)); + } + } + } catch (NoSuchElementException e) { // Why does Java suck + } + + // Get rid of the empty list + if (entry.getValue().size() == 0) { + it.remove(); + } + } + } catch (NoSuchElementException e) {} + } + for (ServiceUnregisterEvent event : unregisteredEvents) { + Bukkit.getServer().getPluginManager().callEvent(event); + } + } + + /** + * Queries for a provider. This may return if no provider has been + * registered for a service. The highest priority provider is returned. + * + * @param The service interface + * @param service The service interface + * @return provider or null + */ + public T load(Class service) { + synchronized (providers) { + List> registered = providers.get(service); + + if (registered == null) { + return null; + } + + // This should not be null! + return service.cast(registered.get(0).getProvider()); + } + } + + /** + * Queries for a provider registration. This may return if no provider + * has been registered for a service. + * + * @param The service interface + * @param service The service interface + * @return provider registration or null + */ + @SuppressWarnings("unchecked") + public RegisteredServiceProvider getRegistration(Class service) { + synchronized (providers) { + List> registered = providers.get(service); + + if (registered == null) { + return null; + } + + // This should not be null! + return (RegisteredServiceProvider) registered.get(0); + } + } + + /** + * Get registrations of providers for a plugin. + * + * @param plugin The plugin + * @return provider registration or null + */ + public List> getRegistrations(Plugin plugin) { + ImmutableList.Builder> ret = ImmutableList.>builder(); + synchronized (providers) { + for (List> registered : providers.values()) { + for (RegisteredServiceProvider provider : registered) { + if (provider.getPlugin().equals(plugin)) { + ret.add(provider); + } + } + } + } + return ret.build(); + } + + /** + * Get registrations of providers for a service. The returned list is + * an unmodifiable copy. + * + * @param The service interface + * @param service The service interface + * @return a copy of the list of registrations + */ + @SuppressWarnings("unchecked") + public List> getRegistrations(Class service) { + ImmutableList.Builder> ret; + synchronized (providers) { + List> registered = providers.get(service); + + if (registered == null) { + return ImmutableList.>of(); + } + + ret = ImmutableList.>builder(); + + for (RegisteredServiceProvider provider : registered) { + ret.add((RegisteredServiceProvider) provider); + } + + } + return ret.build(); + } + + /** + * Get a list of known services. A service is known if it has registered + * providers for it. + * + * @return a copy of the set of known services + */ + public Set> getKnownServices() { + synchronized (providers) { + return ImmutableSet.>copyOf(providers.keySet()); + } + } + + /** + * Returns whether a provider has been registered for a service. + * + * @param service + * @param service service to check + * @return true if and only if there are registered providers + */ + public boolean isProvidedFor(Class service) { + synchronized (providers) { + return providers.containsKey(service); + } + } +} diff --git a/src/main/java/org/bukkit/plugin/TimedRegisteredListener.java b/src/main/java/org/bukkit/plugin/TimedRegisteredListener.java new file mode 100644 index 0000000..e09234c --- /dev/null +++ b/src/main/java/org/bukkit/plugin/TimedRegisteredListener.java @@ -0,0 +1,97 @@ +package org.bukkit.plugin; + +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +/** + * Extends RegisteredListener to include timing information + */ +public class TimedRegisteredListener extends RegisteredListener { + private int count; + private long totalTime; + private Class eventClass; + private boolean multiple = false; + + public TimedRegisteredListener(final Listener pluginListener, final EventExecutor eventExecutor, final EventPriority eventPriority, final Plugin registeredPlugin, final boolean listenCancelled) { + super(pluginListener, eventExecutor, eventPriority, registeredPlugin, listenCancelled); + } + + @Override + public void callEvent(Event event) throws EventException { + if (event.isAsynchronous()) { + super.callEvent(event); + return; + } + count++; + Class newEventClass = event.getClass(); + if (this.eventClass == null) { + this.eventClass = newEventClass; + } else if (!this.eventClass.equals(newEventClass)) { + multiple = true; + this.eventClass = getCommonSuperclass(newEventClass, this.eventClass).asSubclass(Event.class); + } + long start = System.nanoTime(); + super.callEvent(event); + totalTime += System.nanoTime() - start; + } + + private static Class getCommonSuperclass(Class class1, Class class2) { + while (!class1.isAssignableFrom(class2)) { + class1 = class1.getSuperclass(); + } + return class1; + } + + /** + * Resets the call count and total time for this listener + */ + public void reset() { + count = 0; + totalTime = 0; + } + + /** + * Gets the total times this listener has been called + * + * @return Times this listener has been called + */ + public int getCount() { + return count; + } + + /** + * Gets the total time calls to this listener have taken + * + * @return Total time for all calls of this listener + */ + public long getTotalTime() { + return totalTime; + } + + /** + * Gets the class of the events this listener handled. If it handled + * multiple classes of event, the closest shared superclass will be + * returned, such that for any event this listener has handled, + * this.getEventClass().isAssignableFrom(event.getClass()) + * and no class this.getEventClass().isAssignableFrom(clazz) + * && this.getEventClass() != clazz && + * event.getClass().isAssignableFrom(clazz) for all handled events. + * + * @return the event class handled by this RegisteredListener + */ + public Class getEventClass() { + return eventClass; + } + + /** + * Gets whether this listener has handled multiple events, such that for + * some two events, eventA.getClass() != eventB.getClass(). + * + * @return true if this listener has handled multiple events + */ + public boolean hasMultiple() { + return multiple; + } +} diff --git a/src/main/java/org/bukkit/plugin/UnknownDependencyException.java b/src/main/java/org/bukkit/plugin/UnknownDependencyException.java new file mode 100644 index 0000000..a80251e --- /dev/null +++ b/src/main/java/org/bukkit/plugin/UnknownDependencyException.java @@ -0,0 +1,46 @@ +package org.bukkit.plugin; + +/** + * Thrown when attempting to load an invalid Plugin file + */ +public class UnknownDependencyException extends RuntimeException { + + private static final long serialVersionUID = 5721389371901775895L; + + /** + * Constructs a new UnknownDependencyException based on the given + * Exception + * + * @param throwable Exception that triggered this Exception + */ + public UnknownDependencyException(final Throwable throwable) { + super(throwable); + } + + /** + * Constructs a new UnknownDependencyException with the given message + * + * @param message Brief message explaining the cause of the exception + */ + public UnknownDependencyException(final String message) { + super(message); + } + + /** + * Constructs a new UnknownDependencyException based on the given + * Exception + * + * @param message Brief message explaining the cause of the exception + * @param throwable Exception that triggered this Exception + */ + public UnknownDependencyException(final Throwable throwable, final String message) { + super(message, throwable); + } + + /** + * Constructs a new UnknownDependencyException + */ + public UnknownDependencyException() { + + } +} diff --git a/src/main/java/org/bukkit/plugin/java/JavaPlugin.java b/src/main/java/org/bukkit/plugin/java/JavaPlugin.java new file mode 100644 index 0000000..19893f3 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/java/JavaPlugin.java @@ -0,0 +1,546 @@ +package org.bukkit.plugin.java; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.commons.lang.Validate; +import org.bukkit.Server; +import org.bukkit.Warning.WarningState; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.AuthorNagException; +import org.bukkit.plugin.PluginAwareness; +import org.bukkit.plugin.PluginBase; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginLoader; +import org.bukkit.plugin.PluginLogger; + +import com.avaje.ebean.EbeanServer; +import com.avaje.ebean.EbeanServerFactory; +import com.avaje.ebean.config.DataSourceConfig; +import com.avaje.ebean.config.ServerConfig; +import com.avaje.ebeaninternal.api.SpiEbeanServer; +import com.avaje.ebeaninternal.server.ddl.DdlGenerator; +import com.google.common.base.Charsets; +import com.google.common.io.ByteStreams; + +/** + * Represents a Java plugin + */ +public abstract class JavaPlugin extends PluginBase { + private boolean isEnabled = false; + private PluginLoader loader = null; + private Server server = null; + private File file = null; + private PluginDescriptionFile description = null; + private File dataFolder = null; + private ClassLoader classLoader = null; + private boolean naggable = true; + private EbeanServer ebean = null; + private FileConfiguration newConfig = null; + private File configFile = null; + private PluginLogger logger = null; + + public JavaPlugin() { + final ClassLoader classLoader = this.getClass().getClassLoader(); + if (!(classLoader instanceof PluginClassLoader)) { + throw new IllegalStateException("JavaPlugin requires " + PluginClassLoader.class.getName()); + } + ((PluginClassLoader) classLoader).initialize(this); + } + + /** + * @deprecated This method is intended for unit testing purposes when the + * other {@linkplain #JavaPlugin(JavaPluginLoader, + * PluginDescriptionFile, File, File) constructor} cannot be used. + *

            + * Its existence may be temporary. + */ + @Deprecated + protected JavaPlugin(final PluginLoader loader, final Server server, final PluginDescriptionFile description, final File dataFolder, final File file) { + final ClassLoader classLoader = this.getClass().getClassLoader(); + if (classLoader instanceof PluginClassLoader) { + throw new IllegalStateException("Cannot use initialization constructor at runtime"); + } + init(loader, server, description, dataFolder, file, classLoader); + } + + protected JavaPlugin(final JavaPluginLoader loader, final PluginDescriptionFile description, final File dataFolder, final File file) { + final ClassLoader classLoader = this.getClass().getClassLoader(); + if (classLoader instanceof PluginClassLoader) { + throw new IllegalStateException("Cannot use initialization constructor at runtime"); + } + init(loader, loader.server, description, dataFolder, file, classLoader); + } + + /** + * Returns the folder that the plugin data's files are located in. The + * folder may not yet exist. + * + * @return The folder. + */ + @Override + public final File getDataFolder() { + return dataFolder; + } + + /** + * Gets the associated PluginLoader responsible for this plugin + * + * @return PluginLoader that controls this plugin + */ + @Override + public final PluginLoader getPluginLoader() { + return loader; + } + + /** + * Returns the Server instance currently running this plugin + * + * @return Server running this plugin + */ + @Override + public final Server getServer() { + return server; + } + + /** + * Returns a value indicating whether or not this plugin is currently + * enabled + * + * @return true if this plugin is enabled, otherwise false + */ + @Override + public final boolean isEnabled() { + return isEnabled; + } + + /** + * Returns the file which contains this plugin + * + * @return File containing this plugin + */ + protected File getFile() { + return file; + } + + /** + * Returns the plugin.yaml file containing the details for this plugin + * + * @return Contents of the plugin.yaml file + */ + @Override + public final PluginDescriptionFile getDescription() { + return description; + } + + @Override + public FileConfiguration getConfig() { + if (newConfig == null) { + reloadConfig(); + } + return newConfig; + } + + /** + * Provides a reader for a text file located inside the jar. The behavior + * of this method adheres to {@link PluginAwareness.Flags#UTF8}, or if not + * defined, uses UTF8 if {@link FileConfiguration#UTF8_OVERRIDE} is + * specified, or system default otherwise. + * + * @param file the filename of the resource to load + * @return null if {@link #getResource(String)} returns null + * @throws IllegalArgumentException if file is null + * @see ClassLoader#getResourceAsStream(String) + */ + @SuppressWarnings("deprecation") + protected final Reader getTextResource(String file) { + final InputStream in = getResource(file); + + return in == null ? null : new InputStreamReader(in, isStrictlyUTF8() || FileConfiguration.UTF8_OVERRIDE ? Charsets.UTF_8 : Charset.defaultCharset()); + } + + @SuppressWarnings("deprecation") + @Override + public void reloadConfig() { + newConfig = YamlConfiguration.loadConfiguration(configFile); + + final InputStream defConfigStream = getResource("config.yml"); + if (defConfigStream == null) { + return; + } + + final YamlConfiguration defConfig; + if (isStrictlyUTF8() || FileConfiguration.UTF8_OVERRIDE) { + defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream, Charsets.UTF_8)); + } else { + final byte[] contents; + defConfig = new YamlConfiguration(); + try { + contents = ByteStreams.toByteArray(defConfigStream); + } catch (final IOException e) { + getLogger().log(Level.SEVERE, "Unexpected failure reading config.yml", e); + return; + } + + final String text = new String(contents, Charset.defaultCharset()); + if (!text.equals(new String(contents, Charsets.UTF_8))) { + getLogger().warning("Default system encoding may have misread config.yml from plugin jar"); + } + + try { + defConfig.loadFromString(text); + } catch (final InvalidConfigurationException e) { + getLogger().log(Level.SEVERE, "Cannot load configuration from jar", e); + } + } + + newConfig.setDefaults(defConfig); + } + + private boolean isStrictlyUTF8() { + return getDescription().getAwareness().contains(PluginAwareness.Flags.UTF8); + } + + @Override + public void saveConfig() { + try { + getConfig().save(configFile); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Could not save config to " + configFile, ex); + } + } + + @Override + public void saveDefaultConfig() { + if (!configFile.exists()) { + saveResource("config.yml", false); + } + } + + @Override + public void saveResource(String resourcePath, boolean replace) { + if (resourcePath == null || resourcePath.equals("")) { + throw new IllegalArgumentException("ResourcePath cannot be null or empty"); + } + + resourcePath = resourcePath.replace('\\', '/'); + InputStream in = getResource(resourcePath); + if (in == null) { + throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + file); + } + + File outFile = new File(dataFolder, resourcePath); + int lastIndex = resourcePath.lastIndexOf('/'); + File outDir = new File(dataFolder, resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0)); + + if (!outDir.exists()) { + outDir.mkdirs(); + } + + try { + if (!outFile.exists() || replace) { + OutputStream out = new FileOutputStream(outFile); + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + out.close(); + in.close(); + } else { + logger.log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists."); + } + } catch (IOException ex) { + logger.log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex); + } + } + + @Override + public InputStream getResource(String filename) { + if (filename == null) { + throw new IllegalArgumentException("Filename cannot be null"); + } + + try { + URL url = getClassLoader().getResource(filename); + + if (url == null) { + return null; + } + + URLConnection connection = url.openConnection(); + connection.setUseCaches(false); + return connection.getInputStream(); + } catch (IOException ex) { + return null; + } + } + + /** + * Returns the ClassLoader which holds this plugin + * + * @return ClassLoader holding this plugin + */ + protected final ClassLoader getClassLoader() { + return classLoader; + } + + /** + * Sets the enabled state of this plugin + * + * @param enabled true if enabled, otherwise false + */ + protected final void setEnabled(final boolean enabled) { + if (isEnabled != enabled) { + isEnabled = enabled; + + if (isEnabled) { + onEnable(); + } else { + onDisable(); + } + } + } + + /** + * @deprecated This method is legacy and will be removed - it must be + * replaced by the specially provided constructor(s). + */ + @Deprecated + protected final void initialize(PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file, ClassLoader classLoader) { + if (server.getWarningState() == WarningState.OFF) { + return; + } + getLogger().log(Level.WARNING, getClass().getName() + " is already initialized", server.getWarningState() == WarningState.DEFAULT ? null : new AuthorNagException("Explicit initialization")); + } + + final void init(PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file, ClassLoader classLoader) { + this.loader = loader; + this.server = server; + this.file = file; + this.description = description; + this.dataFolder = dataFolder; + this.classLoader = classLoader; + this.configFile = new File(dataFolder, "config.yml"); + this.logger = new PluginLogger(this); + + if (description.isDatabaseEnabled()) { + ServerConfig db = new ServerConfig(); + + db.setDefaultServer(false); + db.setRegister(false); + db.setClasses(getDatabaseClasses()); + db.setName(description.getName()); + server.configureDbConfig(db); + + DataSourceConfig ds = db.getDataSourceConfig(); + + ds.setUrl(replaceDatabaseString(ds.getUrl())); + dataFolder.mkdirs(); + + ClassLoader previous = Thread.currentThread().getContextClassLoader(); + + Thread.currentThread().setContextClassLoader(classLoader); + ebean = EbeanServerFactory.create(db); + Thread.currentThread().setContextClassLoader(previous); + } + } + + /** + * Provides a list of all classes that should be persisted in the database + * + * @return List of Classes that are Ebeans + */ + public List> getDatabaseClasses() { + return new ArrayList>(); + } + + private String replaceDatabaseString(String input) { + input = input.replaceAll("\\{DIR\\}", dataFolder.getPath().replaceAll("\\\\", "/") + "/"); + input = input.replaceAll("\\{NAME\\}", description.getName().replaceAll("[^\\w_-]", "")); + return input; + } + + /** + * Gets the initialization status of this plugin + * + * @return true if this plugin is initialized, otherwise false + * @deprecated This method cannot return false, as {@link + * JavaPlugin} is now initialized in the constructor. + */ + @Deprecated + public final boolean isInitialized() { + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + return null; + } + + /** + * Gets the command with the given name, specific to this plugin. Commands + * need to be registered in the {@link PluginDescriptionFile#getCommands() + * PluginDescriptionFile} to exist at runtime. + * + * @param name name or alias of the command + * @return the plugin command if found, otherwise null + */ + public PluginCommand getCommand(String name) { + String alias = name.toLowerCase(); + PluginCommand command = getServer().getPluginCommand(alias); + + if (command == null || command.getPlugin() != this) { + command = getServer().getPluginCommand(description.getName().toLowerCase() + ":" + alias); + } + + if (command != null && command.getPlugin() == this) { + return command; + } else { + return null; + } + } + + @Override + public void onLoad() {} + + @Override + public void onDisable() {} + + @Override + public void onEnable() {} + + @Override + public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { + return null; + } + + @Override + public final boolean isNaggable() { + return naggable; + } + + @Override + public final void setNaggable(boolean canNag) { + this.naggable = canNag; + } + + @Override + public EbeanServer getDatabase() { + return ebean; + } + + protected void installDDL() { + SpiEbeanServer serv = (SpiEbeanServer) getDatabase(); + DdlGenerator gen = serv.getDdlGenerator(); + + gen.runScript(false, gen.generateCreateDdl()); + } + + protected void removeDDL() { + SpiEbeanServer serv = (SpiEbeanServer) getDatabase(); + DdlGenerator gen = serv.getDdlGenerator(); + + gen.runScript(true, gen.generateDropDdl()); + } + + @Override + public final Logger getLogger() { + return logger; + } + + @Override + public String toString() { + return description.getFullName(); + } + + /** + * This method provides fast access to the plugin that has {@link + * #getProvidingPlugin(Class) provided} the given plugin class, which is + * usually the plugin that implemented it. + *

            + * An exception to this would be if plugin's jar that contained the class + * does not extend the class, where the intended plugin would have + * resided in a different jar / classloader. + * + * @param clazz the class desired + * @return the plugin that provides and implements said class + * @throws IllegalArgumentException if clazz is null + * @throws IllegalArgumentException if clazz does not extend {@link + * JavaPlugin} + * @throws IllegalStateException if clazz was not provided by a plugin, + * for example, if called with + * JavaPlugin.getPlugin(JavaPlugin.class) + * @throws IllegalStateException if called from the static initializer for + * given JavaPlugin + * @throws ClassCastException if plugin that provided the class does not + * extend the class + */ + public static T getPlugin(Class clazz) { + Validate.notNull(clazz, "Null class cannot have a plugin"); + if (!JavaPlugin.class.isAssignableFrom(clazz)) { + throw new IllegalArgumentException(clazz + " does not extend " + JavaPlugin.class); + } + final ClassLoader cl = clazz.getClassLoader(); + if (!(cl instanceof PluginClassLoader)) { + throw new IllegalArgumentException(clazz + " is not initialized by " + PluginClassLoader.class); + } + JavaPlugin plugin = ((PluginClassLoader) cl).plugin; + if (plugin == null) { + throw new IllegalStateException("Cannot get plugin for " + clazz + " from a static initializer"); + } + return clazz.cast(plugin); + } + + /** + * This method provides fast access to the plugin that has provided the + * given class. + * + * @throws IllegalArgumentException if the class is not provided by a + * JavaPlugin + * @throws IllegalArgumentException if class is null + * @throws IllegalStateException if called from the static initializer for + * given JavaPlugin + */ + public static JavaPlugin getProvidingPlugin(Class clazz) { + Validate.notNull(clazz, "Null class cannot have a plugin"); + final ClassLoader cl = clazz.getClassLoader(); + if (!(cl instanceof PluginClassLoader)) { + throw new IllegalArgumentException(clazz + " is not provided by " + PluginClassLoader.class); + } + JavaPlugin plugin = ((PluginClassLoader) cl).plugin; + if (plugin == null) { + throw new IllegalStateException("Cannot get plugin for " + clazz + " from a static initializer"); + } + return plugin; + } +} diff --git a/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java b/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java new file mode 100644 index 0000000..b178c0d --- /dev/null +++ b/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java @@ -0,0 +1,365 @@ +package org.bukkit.plugin.java; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.logging.Level; +import java.util.regex.Pattern; + +import org.apache.commons.lang.Validate; +import org.bukkit.Server; +import org.bukkit.Warning; +import org.bukkit.Warning.WarningState; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.plugin.AuthorNagException; +import org.bukkit.plugin.EventExecutor; +import org.bukkit.plugin.InvalidDescriptionException; +import org.bukkit.plugin.InvalidPluginException; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginLoader; +import org.bukkit.plugin.RegisteredListener; +import org.bukkit.plugin.TimedRegisteredListener; +import org.bukkit.plugin.UnknownDependencyException; +import org.yaml.snakeyaml.error.YAMLException; + +/** + * Represents a Java plugin loader, allowing plugins in the form of .jar + */ +public final class JavaPluginLoader implements PluginLoader { + final Server server; + private final Pattern[] fileFilters = new Pattern[] { Pattern.compile("\\.jar$"), }; + private final Map> classes = new HashMap>(); + private final Map loaders = new LinkedHashMap(); + + /** + * This class was not meant to be constructed explicitly + */ + @Deprecated + public JavaPluginLoader(Server instance) { + Validate.notNull(instance, "Server cannot be null"); + server = instance; + } + + public Plugin loadPlugin(final File file) throws InvalidPluginException { + Validate.notNull(file, "File cannot be null"); + + if (!file.exists()) { + throw new InvalidPluginException(new FileNotFoundException(file.getPath() + " does not exist")); + } + + final PluginDescriptionFile description; + try { + description = getPluginDescription(file); + } catch (InvalidDescriptionException ex) { + throw new InvalidPluginException(ex); + } + + final File parentFile = file.getParentFile(); + final File dataFolder = new File(parentFile, description.getName()); + @SuppressWarnings("deprecation") + final File oldDataFolder = new File(parentFile, description.getRawName()); + + // Found old data folder + if (dataFolder.equals(oldDataFolder)) { + // They are equal -- nothing needs to be done! + } else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) { + server.getLogger().warning(String.format( + "While loading %s (%s) found old-data folder: `%s' next to the new one `%s'", + description.getFullName(), + file, + oldDataFolder, + dataFolder + )); + } else if (oldDataFolder.isDirectory() && !dataFolder.exists()) { + if (!oldDataFolder.renameTo(dataFolder)) { + throw new InvalidPluginException("Unable to rename old data folder: `" + oldDataFolder + "' to: `" + dataFolder + "'"); + } + server.getLogger().log(Level.INFO, String.format( + "While loading %s (%s) renamed data folder: `%s' to `%s'", + description.getFullName(), + file, + oldDataFolder, + dataFolder + )); + } + + if (dataFolder.exists() && !dataFolder.isDirectory()) { + throw new InvalidPluginException(String.format( + "Projected datafolder: `%s' for %s (%s) exists and is not a directory", + dataFolder, + description.getFullName(), + file + )); + } + + for (final String pluginName : description.getDepend()) { + if (loaders == null) { + throw new UnknownDependencyException(pluginName); + } + PluginClassLoader current = loaders.get(pluginName); + + if (current == null) { + throw new UnknownDependencyException(pluginName); + } + } + + final PluginClassLoader loader; + try { + loader = new PluginClassLoader(this, getClass().getClassLoader(), description, dataFolder, file); + } catch (InvalidPluginException ex) { + throw ex; + } catch (Throwable ex) { + throw new InvalidPluginException(ex); + } + + loaders.put(description.getName(), loader); + + return loader.plugin; + } + + public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException { + Validate.notNull(file, "File cannot be null"); + + JarFile jar = null; + InputStream stream = null; + + try { + jar = new JarFile(file); + JarEntry entry = jar.getJarEntry("plugin.yml"); + + if (entry == null) { + throw new InvalidDescriptionException(new FileNotFoundException("Jar does not contain plugin.yml")); + } + + stream = jar.getInputStream(entry); + + return new PluginDescriptionFile(stream); + + } catch (IOException ex) { + throw new InvalidDescriptionException(ex); + } catch (YAMLException ex) { + throw new InvalidDescriptionException(ex); + } finally { + if (jar != null) { + try { + jar.close(); + } catch (IOException e) { + } + } + if (stream != null) { + try { + stream.close(); + } catch (IOException e) { + } + } + } + } + + public Pattern[] getPluginFileFilters() { + return fileFilters.clone(); + } + + Class getClassByName(final String name) { + Class cachedClass = classes.get(name); + + if (cachedClass != null) { + return cachedClass; + } else { + for (String current : loaders.keySet()) { + PluginClassLoader loader = loaders.get(current); + + try { + cachedClass = loader.findClass(name, false); + } catch (ClassNotFoundException cnfe) {} + if (cachedClass != null) { + return cachedClass; + } + } + } + return null; + } + + void setClass(final String name, final Class clazz) { + if (!classes.containsKey(name)) { + classes.put(name, clazz); + + if (ConfigurationSerializable.class.isAssignableFrom(clazz)) { + Class serializable = clazz.asSubclass(ConfigurationSerializable.class); + ConfigurationSerialization.registerClass(serializable); + } + } + } + + private void removeClass(String name) { + Class clazz = classes.remove(name); + + try { + if ((clazz != null) && (ConfigurationSerializable.class.isAssignableFrom(clazz))) { + Class serializable = clazz.asSubclass(ConfigurationSerializable.class); + ConfigurationSerialization.unregisterClass(serializable); + } + } catch (NullPointerException ex) { + // Boggle! + // (Native methods throwing NPEs is not fun when you can't stop it before-hand) + } + } + + public Map, Set> createRegisteredListeners(Listener listener, final Plugin plugin) { + Validate.notNull(plugin, "Plugin can not be null"); + Validate.notNull(listener, "Listener can not be null"); + + boolean useTimings = server.getPluginManager().useTimings(); + Map, Set> ret = new HashMap, Set>(); + Set methods; + try { + Method[] publicMethods = listener.getClass().getMethods(); + methods = new HashSet(publicMethods.length, Float.MAX_VALUE); + for (Method method : publicMethods) { + methods.add(method); + } + for (Method method : listener.getClass().getDeclaredMethods()) { + methods.add(method); + } + } catch (NoClassDefFoundError e) { + plugin.getLogger().severe("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist."); + return ret; + } + + for (final Method method : methods) { + final EventHandler eh = method.getAnnotation(EventHandler.class); + if (eh == null) continue; + final Class checkClass; + if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) { + plugin.getLogger().severe(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass()); + continue; + } + final Class eventClass = checkClass.asSubclass(Event.class); + method.setAccessible(true); + Set eventSet = ret.get(eventClass); + if (eventSet == null) { + eventSet = new HashSet(); + ret.put(eventClass, eventSet); + } + + for (Class clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) { + // This loop checks for extending deprecated events + if (clazz.getAnnotation(Deprecated.class) != null) { + Warning warning = clazz.getAnnotation(Warning.class); + WarningState warningState = server.getWarningState(); + if (!warningState.printFor(warning)) { + break; + } + plugin.getLogger().log( + Level.WARNING, + String.format( + "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated." + + " \"%s\"; please notify the authors %s.", + plugin.getDescription().getFullName(), + clazz.getName(), + method.toGenericString(), + (warning != null && warning.reason().length() != 0) ? warning.reason() : "Server performance will be affected", + Arrays.toString(plugin.getDescription().getAuthors().toArray())), + warningState == WarningState.ON ? new AuthorNagException(null) : null); + break; + } + } + + EventExecutor executor = new EventExecutor() { + public void execute(Listener listener, Event event) throws EventException { + try { + if (!eventClass.isAssignableFrom(event.getClass())) { + return; + } + method.invoke(listener, event); + } catch (InvocationTargetException ex) { + throw new EventException(ex.getCause()); + } catch (Throwable t) { + throw new EventException(t); + } + } + }; + if (useTimings) { + eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); + } else { + eventSet.add(new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); + } + } + return ret; + } + + public void enablePlugin(final Plugin plugin) { + Validate.isTrue(plugin instanceof JavaPlugin, "Plugin is not associated with this PluginLoader"); + + if (!plugin.isEnabled()) { + plugin.getLogger().info("Enabling " + plugin.getDescription().getFullName()); + + JavaPlugin jPlugin = (JavaPlugin) plugin; + + String pluginName = jPlugin.getDescription().getName(); + + if (!loaders.containsKey(pluginName)) { + loaders.put(pluginName, (PluginClassLoader) jPlugin.getClassLoader()); + } + + try { + jPlugin.setEnabled(true); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred while enabling " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + // Perhaps abort here, rather than continue going, but as it stands, + // an abort is not possible the way it's currently written + server.getPluginManager().callEvent(new PluginEnableEvent(plugin)); + } + } + + public void disablePlugin(Plugin plugin) { + Validate.isTrue(plugin instanceof JavaPlugin, "Plugin is not associated with this PluginLoader"); + + if (plugin.isEnabled()) { + String message = String.format("Disabling %s", plugin.getDescription().getFullName()); + plugin.getLogger().info(message); + + server.getPluginManager().callEvent(new PluginDisableEvent(plugin)); + + JavaPlugin jPlugin = (JavaPlugin) plugin; + ClassLoader cloader = jPlugin.getClassLoader(); + + try { + jPlugin.setEnabled(false); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred while disabling " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + loaders.remove(jPlugin.getDescription().getName()); + + if (cloader instanceof PluginClassLoader) { + PluginClassLoader loader = (PluginClassLoader) cloader; + Set names = loader.getClasses(); + + for (String name : names) { + removeClass(name); + } + } + } + } +} diff --git a/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java b/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java new file mode 100644 index 0000000..13f8633 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java @@ -0,0 +1,106 @@ +package org.bukkit.plugin.java; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.InvalidPluginException; +import org.bukkit.plugin.PluginDescriptionFile; + +/** + * A ClassLoader for plugins, to allow shared classes across multiple plugins + */ +final class PluginClassLoader extends URLClassLoader { + private final JavaPluginLoader loader; + private final Map> classes = new HashMap>(); + private final PluginDescriptionFile description; + private final File dataFolder; + private final File file; + final JavaPlugin plugin; + private JavaPlugin pluginInit; + private IllegalStateException pluginState; + + PluginClassLoader(final JavaPluginLoader loader, final ClassLoader parent, final PluginDescriptionFile description, final File dataFolder, final File file) throws InvalidPluginException, MalformedURLException { + super(new URL[] {file.toURI().toURL()}, parent); + Validate.notNull(loader, "Loader cannot be null"); + + this.loader = loader; + this.description = description; + this.dataFolder = dataFolder; + this.file = file; + + try { + Class jarClass; + try { + jarClass = Class.forName(description.getMain(), true, this); + } catch (ClassNotFoundException ex) { + throw new InvalidPluginException("Cannot find main class `" + description.getMain() + "'", ex); + } + + Class pluginClass; + try { + pluginClass = jarClass.asSubclass(JavaPlugin.class); + } catch (ClassCastException ex) { + throw new InvalidPluginException("main class `" + description.getMain() + "' does not extend JavaPlugin", ex); + } + + plugin = pluginClass.newInstance(); + } catch (IllegalAccessException ex) { + throw new InvalidPluginException("No public constructor", ex); + } catch (InstantiationException ex) { + throw new InvalidPluginException("Abnormal plugin type", ex); + } + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + return findClass(name, true); + } + + Class findClass(String name, boolean checkGlobal) throws ClassNotFoundException { + if (name.startsWith("org.bukkit.") || name.startsWith("net.minecraft.")) { + throw new ClassNotFoundException(name); + } + Class result = classes.get(name); + + if (result == null) { + if (checkGlobal) { + result = loader.getClassByName(name); + } + + if (result == null) { + result = super.findClass(name); + + if (result != null) { + loader.setClass(name, result); + } + } + + classes.put(name, result); + } + + return result; + } + + Set getClasses() { + return classes.keySet(); + } + + synchronized void initialize(JavaPlugin javaPlugin) { + Validate.notNull(javaPlugin, "Initializing plugin cannot be null"); + Validate.isTrue(javaPlugin.getClass().getClassLoader() == this, "Cannot initialize plugin outside of this class loader"); + if (this.plugin != null || this.pluginInit != null) { + throw new IllegalArgumentException("Plugin already initialized!", pluginState); + } + + pluginState = new IllegalStateException("Initial initialization"); + this.pluginInit = javaPlugin; + + javaPlugin.init(loader, loader.server, description, dataFolder, file, this); + } +} diff --git a/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java b/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java new file mode 100644 index 0000000..80ef8a2 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java @@ -0,0 +1,15 @@ +package org.bukkit.plugin.messaging; + +/** + * Thrown if a Plugin Channel is too long. + */ +@SuppressWarnings("serial") +public class ChannelNameTooLongException extends RuntimeException { + public ChannelNameTooLongException() { + super("Attempted to send a Plugin Message to a channel that was too large. The maximum length a channel may be is " + Messenger.MAX_CHANNEL_SIZE + " chars."); + } + + public ChannelNameTooLongException(String channel) { + super("Attempted to send a Plugin Message to a channel that was too large. The maximum length a channel may be is " + Messenger.MAX_CHANNEL_SIZE + " chars (attempted " + channel.length() + " - '" + channel + "."); + } +} diff --git a/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java b/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java new file mode 100644 index 0000000..2266f17 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java @@ -0,0 +1,15 @@ +package org.bukkit.plugin.messaging; + +/** + * Thrown if a Plugin attempts to send a message on an unregistered channel. + */ +@SuppressWarnings("serial") +public class ChannelNotRegisteredException extends RuntimeException { + public ChannelNotRegisteredException() { + this("Attempted to send a plugin message through an unregistered channel."); + } + + public ChannelNotRegisteredException(String channel) { + super("Attempted to send a plugin message through the unregistered channel `" + channel + "'."); + } +} diff --git a/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java b/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java new file mode 100644 index 0000000..61af8c4 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java @@ -0,0 +1,23 @@ +package org.bukkit.plugin.messaging; + +/** + * Thrown if a Plugin Message is sent that is too large to be sent. + */ +@SuppressWarnings("serial") +public class MessageTooLargeException extends RuntimeException { + public MessageTooLargeException() { + this("Attempted to send a plugin message that was too large. The maximum length a plugin message may be is " + Messenger.MAX_MESSAGE_SIZE + " bytes."); + } + + public MessageTooLargeException(byte[] message) { + this(message.length); + } + + public MessageTooLargeException(int length) { + this("Attempted to send a plugin message that was too large. The maximum length a plugin message may be is " + Messenger.MAX_MESSAGE_SIZE + " bytes (tried to send one that is " + length + " bytes long)."); + } + + public MessageTooLargeException(String msg) { + super(msg); + } +} diff --git a/src/main/java/org/bukkit/plugin/messaging/Messenger.java b/src/main/java/org/bukkit/plugin/messaging/Messenger.java new file mode 100644 index 0000000..aa009fe --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/Messenger.java @@ -0,0 +1,216 @@ +package org.bukkit.plugin.messaging; + +import java.util.Set; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +/** + * A class responsible for managing the registrations of plugin channels and + * their listeners. + */ +public interface Messenger { + + /** + * Represents the largest size that an individual Plugin Message may be. + */ + public static final int MAX_MESSAGE_SIZE = 32766; + + /** + * Represents the largest size that a Plugin Channel may be. + */ + public static final int MAX_CHANNEL_SIZE = 16; + + /** + * Checks if the specified channel is a reserved name. + * + * @param channel Channel name to check. + * @return True if the channel is reserved, otherwise false. + * @throws IllegalArgumentException Thrown if channel is null. + */ + public boolean isReservedChannel(String channel); + + /** + * Registers the specific plugin to the requested outgoing plugin channel, + * allowing it to send messages through that channel to any clients. + * + * @param plugin Plugin that wishes to send messages through the channel. + * @param channel Channel to register. + * @throws IllegalArgumentException Thrown if plugin or channel is null. + */ + public void registerOutgoingPluginChannel(Plugin plugin, String channel); + + /** + * Unregisters the specific plugin from the requested outgoing plugin + * channel, no longer allowing it to send messages through that channel to + * any clients. + * + * @param plugin Plugin that no longer wishes to send messages through the + * channel. + * @param channel Channel to unregister. + * @throws IllegalArgumentException Thrown if plugin or channel is null. + */ + public void unregisterOutgoingPluginChannel(Plugin plugin, String channel); + + /** + * Unregisters the specific plugin from all outgoing plugin channels, no + * longer allowing it to send any plugin messages. + * + * @param plugin Plugin that no longer wishes to send plugin messages. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + public void unregisterOutgoingPluginChannel(Plugin plugin); + + /** + * Registers the specific plugin for listening on the requested incoming + * plugin channel, allowing it to act upon any plugin messages. + * + * @param plugin Plugin that wishes to register to this channel. + * @param channel Channel to register. + * @param listener Listener to receive messages on. + * @return The resulting registration that was made as a result of this + * method. + * @throws IllegalArgumentException Thrown if plugin, channel or listener + * is null, or the listener is already registered for this channel. + */ + public PluginMessageListenerRegistration registerIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener); + + /** + * Unregisters the specific plugin's listener from listening on the + * requested incoming plugin channel, no longer allowing it to act upon + * any plugin messages. + * + * @param plugin Plugin that wishes to unregister from this channel. + * @param channel Channel to unregister. + * @param listener Listener to stop receiving messages on. + * @throws IllegalArgumentException Thrown if plugin, channel or listener + * is null. + */ + public void unregisterIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener); + + /** + * Unregisters the specific plugin from listening on the requested + * incoming plugin channel, no longer allowing it to act upon any plugin + * messages. + * + * @param plugin Plugin that wishes to unregister from this channel. + * @param channel Channel to unregister. + * @throws IllegalArgumentException Thrown if plugin or channel is null. + */ + public void unregisterIncomingPluginChannel(Plugin plugin, String channel); + + /** + * Unregisters the specific plugin from listening on all plugin channels + * through all listeners. + * + * @param plugin Plugin that wishes to unregister from this channel. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + public void unregisterIncomingPluginChannel(Plugin plugin); + + /** + * Gets a set containing all the outgoing plugin channels. + * + * @return List of all registered outgoing plugin channels. + */ + public Set getOutgoingChannels(); + + /** + * Gets a set containing all the outgoing plugin channels that the + * specified plugin is registered to. + * + * @param plugin Plugin to retrieve channels for. + * @return List of all registered outgoing plugin channels that a plugin + * is registered to. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + public Set getOutgoingChannels(Plugin plugin); + + /** + * Gets a set containing all the incoming plugin channels. + * + * @return List of all registered incoming plugin channels. + */ + public Set getIncomingChannels(); + + /** + * Gets a set containing all the incoming plugin channels that the + * specified plugin is registered for. + * + * @param plugin Plugin to retrieve channels for. + * @return List of all registered incoming plugin channels that the plugin + * is registered for. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + public Set getIncomingChannels(Plugin plugin); + + /** + * Gets a set containing all the incoming plugin channel registrations + * that the specified plugin has. + * + * @param plugin Plugin to retrieve registrations for. + * @return List of all registrations that the plugin has. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + public Set getIncomingChannelRegistrations(Plugin plugin); + + /** + * Gets a set containing all the incoming plugin channel registrations + * that are on the requested channel. + * + * @param channel Channel to retrieve registrations for. + * @return List of all registrations that are on the channel. + * @throws IllegalArgumentException Thrown if channel is null. + */ + public Set getIncomingChannelRegistrations(String channel); + + /** + * Gets a set containing all the incoming plugin channel registrations + * that the specified plugin has on the requested channel. + * + * @param plugin Plugin to retrieve registrations for. + * @param channel Channel to filter registrations by. + * @return List of all registrations that the plugin has. + * @throws IllegalArgumentException Thrown if plugin or channel is null. + */ + public Set getIncomingChannelRegistrations(Plugin plugin, String channel); + + /** + * Checks if the specified plugin message listener registration is valid. + *

            + * A registration is considered valid if it has not be unregistered and + * that the plugin is still enabled. + * + * @param registration Registration to check. + * @return True if the registration is valid, otherwise false. + */ + public boolean isRegistrationValid(PluginMessageListenerRegistration registration); + + /** + * Checks if the specified plugin has registered to receive incoming + * messages through the requested channel. + * + * @param plugin Plugin to check registration for. + * @param channel Channel to test for. + * @return True if the channel is registered, else false. + */ + public boolean isIncomingChannelRegistered(Plugin plugin, String channel); + + /** + * Checks if the specified plugin has registered to send outgoing messages + * through the requested channel. + * + * @param plugin Plugin to check registration for. + * @param channel Channel to test for. + * @return True if the channel is registered, else false. + */ + public boolean isOutgoingChannelRegistered(Plugin plugin, String channel); + + /** + * Dispatches the specified incoming message to any registered listeners. + * + * @param source Source of the message. + * @param channel Channel that the message was sent by. + * @param message Raw payload of the message. + */ + public void dispatchIncomingMessage(Player source, String channel, byte[] message); +} diff --git a/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java b/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java new file mode 100644 index 0000000..3d7ec2e --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java @@ -0,0 +1,17 @@ +package org.bukkit.plugin.messaging; + +/** + * Represents the different directions a plugin channel may go. + */ +public enum PluginChannelDirection { + + /** + * The plugin channel is being sent to the server from a client. + */ + INCOMING, + + /** + * The plugin channel is being sent to a client from the server. + */ + OUTGOING +} diff --git a/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java b/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java new file mode 100644 index 0000000..f1aa080 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java @@ -0,0 +1,20 @@ +package org.bukkit.plugin.messaging; + +import org.bukkit.entity.Player; + +/** + * A listener for a specific Plugin Channel, which will receive notifications + * of messages sent from a client. + */ +public interface PluginMessageListener { + + /** + * A method that will be thrown when a PluginMessageSource sends a plugin + * message on a registered channel. + * + * @param channel Channel that the message was sent through. + * @param player Source of the message. + * @param message The raw message that was sent. + */ + public void onPluginMessageReceived(String channel, Player player, byte[] message); +} diff --git a/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java b/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java new file mode 100644 index 0000000..29929bf --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java @@ -0,0 +1,104 @@ +package org.bukkit.plugin.messaging; + +import org.bukkit.plugin.Plugin; + +/** + * Contains information about a {@link Plugin}s registration to a plugin + * channel. + */ +public final class PluginMessageListenerRegistration { + private final Messenger messenger; + private final Plugin plugin; + private final String channel; + private final PluginMessageListener listener; + + public PluginMessageListenerRegistration(Messenger messenger, Plugin plugin, String channel, PluginMessageListener listener) { + if (messenger == null) { + throw new IllegalArgumentException("Messenger cannot be null!"); + } + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + if (channel == null) { + throw new IllegalArgumentException("Channel cannot be null!"); + } + if (listener == null) { + throw new IllegalArgumentException("Listener cannot be null!"); + } + + this.messenger = messenger; + this.plugin = plugin; + this.channel = channel; + this.listener = listener; + } + + /** + * Gets the plugin channel that this registration is about. + * + * @return Plugin channel. + */ + public String getChannel() { + return channel; + } + + /** + * Gets the registered listener described by this registration. + * + * @return Registered listener. + */ + public PluginMessageListener getListener() { + return listener; + } + + /** + * Gets the plugin that this registration is for. + * + * @return Registered plugin. + */ + public Plugin getPlugin() { + return plugin; + } + + /** + * Checks if this registration is still valid. + * + * @return True if this registration is still valid, otherwise false. + */ + public boolean isValid() { + return messenger.isRegistrationValid(this); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PluginMessageListenerRegistration other = (PluginMessageListenerRegistration) obj; + if (this.messenger != other.messenger && (this.messenger == null || !this.messenger.equals(other.messenger))) { + return false; + } + if (this.plugin != other.plugin && (this.plugin == null || !this.plugin.equals(other.plugin))) { + return false; + } + if ((this.channel == null) ? (other.channel != null) : !this.channel.equals(other.channel)) { + return false; + } + if (this.listener != other.listener && (this.listener == null || !this.listener.equals(other.listener))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 53 * hash + (this.messenger != null ? this.messenger.hashCode() : 0); + hash = 53 * hash + (this.plugin != null ? this.plugin.hashCode() : 0); + hash = 53 * hash + (this.channel != null ? this.channel.hashCode() : 0); + hash = 53 * hash + (this.listener != null ? this.listener.hashCode() : 0); + return hash; + } +} diff --git a/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java b/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java new file mode 100644 index 0000000..e5c5916 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java @@ -0,0 +1,38 @@ +package org.bukkit.plugin.messaging; + +import java.util.Set; +import org.bukkit.plugin.Plugin; + +/** + * Represents a possible recipient for a Plugin Message. + */ +public interface PluginMessageRecipient { + /** + * Sends this recipient a Plugin Message on the specified outgoing + * channel. + *

            + * The message may not be larger than {@link Messenger#MAX_MESSAGE_SIZE} + * bytes, and the plugin must be registered to send messages on the + * specified channel. + * + * @param source The plugin that sent this message. + * @param channel The channel to send this message on. + * @param message The raw message to send. + * @throws IllegalArgumentException Thrown if the source plugin is + * disabled. + * @throws IllegalArgumentException Thrown if source, channel or message + * is null. + * @throws MessageTooLargeException Thrown if the message is too big. + * @throws ChannelNotRegisteredException Thrown if the channel is not + * registered for this plugin. + */ + public void sendPluginMessage(Plugin source, String channel, byte[] message); + + /** + * Gets a set containing all the Plugin Channels that this client is + * listening on. + * + * @return Set containing all the channels that this client may accept. + */ + public Set getListeningPluginChannels(); +} diff --git a/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java b/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java new file mode 100644 index 0000000..0221f04 --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java @@ -0,0 +1,16 @@ +package org.bukkit.plugin.messaging; + +/** + * Thrown if a plugin attempts to register for a reserved channel (such as + * "REGISTER") + */ +@SuppressWarnings("serial") +public class ReservedChannelException extends RuntimeException { + public ReservedChannelException() { + this("Attempted to register for a reserved channel name."); + } + + public ReservedChannelException(String name) { + super("Attempted to register for a reserved channel name ('" + name + "')"); + } +} diff --git a/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java b/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java new file mode 100644 index 0000000..a906f8d --- /dev/null +++ b/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java @@ -0,0 +1,481 @@ +package org.bukkit.plugin.messaging; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSet.Builder; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +/** + * Standard implementation to {@link Messenger} + */ +public class StandardMessenger implements Messenger { + private final Map> incomingByChannel = new HashMap>(); + private final Map> incomingByPlugin = new HashMap>(); + private final Map> outgoingByChannel = new HashMap>(); + private final Map> outgoingByPlugin = new HashMap>(); + private final Object incomingLock = new Object(); + private final Object outgoingLock = new Object(); + + private void addToOutgoing(Plugin plugin, String channel) { + synchronized (outgoingLock) { + Set plugins = outgoingByChannel.get(channel); + Set channels = outgoingByPlugin.get(plugin); + + if (plugins == null) { + plugins = new HashSet(); + outgoingByChannel.put(channel, plugins); + } + + if (channels == null) { + channels = new HashSet(); + outgoingByPlugin.put(plugin, channels); + } + + plugins.add(plugin); + channels.add(channel); + } + } + + private void removeFromOutgoing(Plugin plugin, String channel) { + synchronized (outgoingLock) { + Set plugins = outgoingByChannel.get(channel); + Set channels = outgoingByPlugin.get(plugin); + + if (plugins != null) { + plugins.remove(plugin); + + if (plugins.isEmpty()) { + outgoingByChannel.remove(channel); + } + } + + if (channels != null) { + channels.remove(channel); + + if (channels.isEmpty()) { + outgoingByChannel.remove(channel); + } + } + } + } + + private void removeFromOutgoing(Plugin plugin) { + synchronized (outgoingLock) { + Set channels = outgoingByPlugin.get(plugin); + + if (channels != null) { + String[] toRemove = channels.toArray(new String[0]); + + outgoingByPlugin.remove(plugin); + + for (String channel : toRemove) { + removeFromOutgoing(plugin, channel); + } + } + } + } + + private void addToIncoming(PluginMessageListenerRegistration registration) { + synchronized (incomingLock) { + Set registrations = incomingByChannel.get(registration.getChannel()); + + if (registrations == null) { + registrations = new HashSet(); + incomingByChannel.put(registration.getChannel(), registrations); + } else { + if (registrations.contains(registration)) { + throw new IllegalArgumentException("This registration already exists"); + } + } + + registrations.add(registration); + + registrations = incomingByPlugin.get(registration.getPlugin()); + + if (registrations == null) { + registrations = new HashSet(); + incomingByPlugin.put(registration.getPlugin(), registrations); + } else { + if (registrations.contains(registration)) { + throw new IllegalArgumentException("This registration already exists"); + } + } + + registrations.add(registration); + } + } + + private void removeFromIncoming(PluginMessageListenerRegistration registration) { + synchronized (incomingLock) { + Set registrations = incomingByChannel.get(registration.getChannel()); + + if (registrations != null) { + registrations.remove(registration); + + if (registrations.isEmpty()) { + incomingByChannel.remove(registration.getChannel()); + } + } + + registrations = incomingByPlugin.get(registration.getPlugin()); + + if (registrations != null) { + registrations.remove(registration); + + if (registrations.isEmpty()) { + incomingByPlugin.remove(registration.getPlugin()); + } + } + } + } + + private void removeFromIncoming(Plugin plugin, String channel) { + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + PluginMessageListenerRegistration[] toRemove = registrations.toArray(new PluginMessageListenerRegistration[0]); + + for (PluginMessageListenerRegistration registration : toRemove) { + if (registration.getChannel().equals(channel)) { + removeFromIncoming(registration); + } + } + } + } + } + + private void removeFromIncoming(Plugin plugin) { + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + PluginMessageListenerRegistration[] toRemove = registrations.toArray(new PluginMessageListenerRegistration[0]); + + incomingByPlugin.remove(plugin); + + for (PluginMessageListenerRegistration registration : toRemove) { + removeFromIncoming(registration); + } + } + } + } + + public boolean isReservedChannel(String channel) { + validateChannel(channel); + + return channel.equals("REGISTER") || channel.equals("UNREGISTER"); + } + + public void registerOutgoingPluginChannel(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + if (isReservedChannel(channel)) { + throw new ReservedChannelException(channel); + } + + addToOutgoing(plugin, channel); + } + + public void unregisterOutgoingPluginChannel(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + removeFromOutgoing(plugin, channel); + } + + public void unregisterOutgoingPluginChannel(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + removeFromOutgoing(plugin); + } + + public PluginMessageListenerRegistration registerIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + if (isReservedChannel(channel)) { + throw new ReservedChannelException(channel); + } + if (listener == null) { + throw new IllegalArgumentException("Listener cannot be null"); + } + + PluginMessageListenerRegistration result = new PluginMessageListenerRegistration(this, plugin, channel, listener); + + addToIncoming(result); + + return result; + } + + public void unregisterIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + if (listener == null) { + throw new IllegalArgumentException("Listener cannot be null"); + } + validateChannel(channel); + + removeFromIncoming(new PluginMessageListenerRegistration(this, plugin, channel, listener)); + } + + public void unregisterIncomingPluginChannel(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + removeFromIncoming(plugin, channel); + } + + public void unregisterIncomingPluginChannel(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + removeFromIncoming(plugin); + } + + public Set getOutgoingChannels() { + synchronized (outgoingLock) { + Set keys = outgoingByChannel.keySet(); + return ImmutableSet.copyOf(keys); + } + } + + public Set getOutgoingChannels(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + synchronized (outgoingLock) { + Set channels = outgoingByPlugin.get(plugin); + + if (channels != null) { + return ImmutableSet.copyOf(channels); + } else { + return ImmutableSet.of(); + } + } + } + + public Set getIncomingChannels() { + synchronized (incomingLock) { + Set keys = incomingByChannel.keySet(); + return ImmutableSet.copyOf(keys); + } + } + + public Set getIncomingChannels(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + Builder builder = ImmutableSet.builder(); + + for (PluginMessageListenerRegistration registration : registrations) { + builder.add(registration.getChannel()); + } + + return builder.build(); + } else { + return ImmutableSet.of(); + } + } + } + + public Set getIncomingChannelRegistrations(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + return ImmutableSet.copyOf(registrations); + } else { + return ImmutableSet.of(); + } + } + } + + public Set getIncomingChannelRegistrations(String channel) { + validateChannel(channel); + + synchronized (incomingLock) { + Set registrations = incomingByChannel.get(channel); + + if (registrations != null) { + return ImmutableSet.copyOf(registrations); + } else { + return ImmutableSet.of(); + } + } + } + + public Set getIncomingChannelRegistrations(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + Builder builder = ImmutableSet.builder(); + + for (PluginMessageListenerRegistration registration : registrations) { + if (registration.getChannel().equals(channel)) { + builder.add(registration); + } + } + + return builder.build(); + } else { + return ImmutableSet.of(); + } + } + } + + public boolean isRegistrationValid(PluginMessageListenerRegistration registration) { + if (registration == null) { + throw new IllegalArgumentException("Registration cannot be null"); + } + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(registration.getPlugin()); + + if (registrations != null) { + return registrations.contains(registration); + } + + return false; + } + } + + public boolean isIncomingChannelRegistered(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + for (PluginMessageListenerRegistration registration : registrations) { + if (registration.getChannel().equals(channel)) { + return true; + } + } + } + + return false; + } + } + + public boolean isOutgoingChannelRegistered(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + synchronized (outgoingLock) { + Set channels = outgoingByPlugin.get(plugin); + + if (channels != null) { + return channels.contains(channel); + } + + return false; + } + } + + public void dispatchIncomingMessage(Player source, String channel, byte[] message) { + if (source == null) { + throw new IllegalArgumentException("Player source cannot be null"); + } + if (message == null) { + throw new IllegalArgumentException("Message cannot be null"); + } + validateChannel(channel); + + Set registrations = getIncomingChannelRegistrations(channel); + + for (PluginMessageListenerRegistration registration : registrations) { + registration.getListener().onPluginMessageReceived(channel, source, message); + } + } + + /** + * Validates a Plugin Channel name. + * + * @param channel Channel name to validate. + */ + public static void validateChannel(String channel) { + if (channel == null) { + throw new IllegalArgumentException("Channel cannot be null"); + } + if (channel.length() > Messenger.MAX_CHANNEL_SIZE) { + throw new ChannelNameTooLongException(channel); + } + } + + /** + * Validates the input of a Plugin Message, ensuring the arguments are all + * valid. + * + * @param messenger Messenger to use for validation. + * @param source Source plugin of the Message. + * @param channel Plugin Channel to send the message by. + * @param message Raw message payload to send. + * @throws IllegalArgumentException Thrown if the source plugin is + * disabled. + * @throws IllegalArgumentException Thrown if source, channel or message + * is null. + * @throws MessageTooLargeException Thrown if the message is too big. + * @throws ChannelNameTooLongException Thrown if the channel name is too + * long. + * @throws ChannelNotRegisteredException Thrown if the channel is not + * registered for this plugin. + */ + public static void validatePluginMessage(Messenger messenger, Plugin source, String channel, byte[] message) { + if (messenger == null) { + throw new IllegalArgumentException("Messenger cannot be null"); + } + if (source == null) { + throw new IllegalArgumentException("Plugin source cannot be null"); + } + if (!source.isEnabled()) { + throw new IllegalArgumentException("Plugin must be enabled to send messages"); + } + if (message == null) { + throw new IllegalArgumentException("Message cannot be null"); + } + if (!messenger.isOutgoingChannelRegistered(source, channel)) { + throw new ChannelNotRegisteredException(channel); + } + if (message.length > Messenger.MAX_MESSAGE_SIZE) { + throw new MessageTooLargeException(message); + } + validateChannel(channel); + } +} diff --git a/src/main/java/org/bukkit/potion/Potion.java b/src/main/java/org/bukkit/potion/Potion.java new file mode 100644 index 0000000..a358c29 --- /dev/null +++ b/src/main/java/org/bukkit/potion/Potion.java @@ -0,0 +1,442 @@ +package org.bukkit.potion; + +import java.util.Collection; + +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.ItemStack; + +import com.google.common.collect.ImmutableList; + +/** + * Represents a minecraft potion + */ +public class Potion { + private boolean extended = false; + private boolean splash = false; + private int level = 1; + private int name = -1; + private PotionType type; + + /** + * Construct a new potion of the given type. Unless the type is {@link + * PotionType#WATER}, it will be level one, without extended duration. + * Don't use this constructor to create a no-effect potion other than + * water bottle. + * + * @param type The potion type + * @see #Potion(int) + */ + public Potion(PotionType type) { + this.type = type; + if (type != null) { + this.name = type.getDamageValue(); + } + if (type == null || type == PotionType.WATER) { + this.level = 0; + } + } + + /** + * @deprecated In favour of {@link #Potion(PotionType, int)} + */ + @SuppressWarnings("javadoc") + @Deprecated + public Potion(PotionType type, Tier tier) { + this(type, tier == Tier.TWO ? 2 : 1); + Validate.notNull(type, "Type cannot be null"); + } + + /** + * @deprecated In favour of {@link #Potion(PotionType, int, boolean)} + */ + @SuppressWarnings("javadoc") + @Deprecated + public Potion(PotionType type, Tier tier, boolean splash) { + this(type, tier == Tier.TWO ? 2 : 1, splash); + } + + /** + * @deprecated In favour of {@link #Potion(PotionType, int, boolean, + * boolean)} + */ + @SuppressWarnings("javadoc") + @Deprecated + public Potion(PotionType type, Tier tier, boolean splash, boolean extended) { + this(type, tier, splash); + this.extended = extended; + } + + /** + * Create a new potion of the given type and level. + * + * @param type The type of potion. + * @param level The potion's level. + */ + public Potion(PotionType type, int level) { + this(type); + Validate.notNull(type, "Type cannot be null"); + Validate.isTrue(type != PotionType.WATER, "Water bottles don't have a level!"); + Validate.isTrue(level > 0 && level < 3, "Level must be 1 or 2"); + this.level = level; + } + + /** + * Create a new potion of the given type and level. + * + * @param type The type of potion. + * @param level The potion's level. + * @param splash Whether it is a splash potion. + * @deprecated In favour of using {@link #Potion(PotionType)} with {@link + * #splash()}. + */ + @Deprecated + public Potion(PotionType type, int level, boolean splash) { + this(type, level); + this.splash = splash; + } + + /** + * Create a new potion of the given type and level. + * + * @param type The type of potion. + * @param level The potion's level. + * @param splash Whether it is a splash potion. + * @param extended Whether it has an extended duration. + * @deprecated In favour of using {@link #Potion(PotionType)} with {@link + * #extend()} and possibly {@link #splash()}. + */ + @Deprecated + public Potion(PotionType type, int level, boolean splash, boolean extended) { + this(type, level, splash); + this.extended = extended; + } + + /** + * Create a potion with a specific name. + * + * @param name The name index (0-63) + */ + public Potion(int name) { + this(PotionType.getByDamageValue(name & POTION_BIT)); + this.name = name & NAME_BIT; + if ((name & POTION_BIT) == 0) { + // If it's 0 it would've become PotionType.WATER, but it should actually be mundane potion + this.type = null; + } + } + + /** + * Chain this to the constructor to make the potion a splash potion. + * + * @return The potion. + */ + public Potion splash() { + setSplash(true); + return this; + } + + /** + * Chain this to the constructor to extend the potion's duration. + * + * @return The potion. + */ + public Potion extend() { + setHasExtendedDuration(true); + return this; + } + + /** + * Applies the effects of this potion to the given {@link ItemStack}. The + * ItemStack must be a potion. + * + * @param to The itemstack to apply to + */ + public void apply(ItemStack to) { + Validate.notNull(to, "itemstack cannot be null"); + Validate.isTrue(to.getType() == Material.POTION, "given itemstack is not a potion"); + to.setDurability(toDamageValue()); + } + + /** + * Applies the effects that would be applied by this potion to the given + * {@link LivingEntity}. + * + * @see LivingEntity#addPotionEffects(Collection) + * @param to The entity to apply the effects to + */ + public void apply(LivingEntity to) { + Validate.notNull(to, "entity cannot be null"); + to.addPotionEffects(getEffects()); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + Potion other = (Potion) obj; + return extended == other.extended && splash == other.splash && level == other.level && type == other.type; + } + + /** + * Returns a collection of {@link PotionEffect}s that this {@link Potion} + * would confer upon a {@link LivingEntity}. + * + * @see PotionBrewer#getEffectsFromDamage(int) + * @see Potion#toDamageValue() + * @return The effects that this potion applies + */ + public Collection getEffects() { + if (type == null) return ImmutableList.of(); + return getBrewer().getEffectsFromDamage(toDamageValue()); + } + + /** + * Returns the level of this potion. + * + * @return The level of this potion + */ + public int getLevel() { + return level; + } + + /** + * Returns the {@link Tier} of this potion. + * + * @return The tier of this potion + */ + @Deprecated + public Tier getTier() { + return level == 2 ? Tier.TWO : Tier.ONE; + } + + /** + * Returns the {@link PotionType} of this potion. + * + * @return The type of this potion + */ + public PotionType getType() { + return type; + } + + /** + * Returns whether this potion has an extended duration. + * + * @return Whether this potion has extended duration + */ + public boolean hasExtendedDuration() { + return extended; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = prime + level; + result = prime * result + (extended ? 1231 : 1237); + result = prime * result + (splash ? 1231 : 1237); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + /** + * Returns whether this potion is a splash potion. + * + * @return Whether this is a splash potion + */ + public boolean isSplash() { + return splash; + } + + /** + * Set whether this potion has extended duration. This will cause the + * potion to have roughly 8/3 more duration than a regular potion. + * + * @param isExtended Whether the potion should have extended duration + */ + public void setHasExtendedDuration(boolean isExtended) { + Validate.isTrue(type == null || !type.isInstant(), "Instant potions cannot be extended"); + extended = isExtended; + } + + /** + * Sets whether this potion is a splash potion. Splash potions can be + * thrown for a radius effect. + * + * @param isSplash Whether this is a splash potion + */ + public void setSplash(boolean isSplash) { + splash = isSplash; + } + + /** + * Sets the {@link Tier} of this potion. + * + * @param tier The new tier of this potion + * @deprecated In favour of {@link #setLevel(int)} + */ + @Deprecated + public void setTier(Tier tier) { + Validate.notNull(tier, "tier cannot be null"); + this.level = (tier == Tier.TWO ? 2 : 1); + } + + /** + * Sets the {@link PotionType} of this potion. + * + * @param type The new type of this potion + */ + public void setType(PotionType type) { + this.type = type; + } + + /** + * Sets the level of this potion. + * + * @param level The new level of this potion + */ + public void setLevel(int level) { + Validate.notNull(this.type, "No-effect potions don't have a level."); + int max = type.getMaxLevel(); + Validate.isTrue(level > 0 && level <= max, "Level must be " + (max == 1 ? "" : "between 1 and ") + max + " for this potion"); + this.level = level; + } + + /** + * Converts this potion to a valid potion damage short, usable for potion + * item stacks. + * + * @return The damage value of this potion + * @deprecated Magic value + */ + @Deprecated + public short toDamageValue() { + short damage; + if (type == PotionType.WATER) { + return 0; + } else if (type == null) { + // Without this, mundanePotion.toDamageValue() would return 0 + damage = (short) (name == 0 ? 8192 : name); + } else { + damage = (short) (level - 1); + damage <<= TIER_SHIFT; + damage |= (short) type.getDamageValue(); + } + if (splash) { + damage |= SPLASH_BIT; + } + if (extended) { + damage |= EXTENDED_BIT; + } + return damage; + } + + /** + * Converts this potion to an {@link ItemStack} with the specified amount + * and a correct damage value. + * + * @param amount The amount of the ItemStack + * @return The created ItemStack + */ + public ItemStack toItemStack(int amount) { + return new ItemStack(Material.POTION, amount, toDamageValue()); + } + + @Deprecated + public enum Tier { + ONE(0), + TWO(0x20); + + private int damageBit; + + Tier(int bit) { + damageBit = bit; + } + + public int getDamageBit() { + return damageBit; + } + + public static Tier getByDamageBit(int damageBit) { + for (Tier tier : Tier.values()) { + if (tier.damageBit == damageBit) + return tier; + } + return null; + } + } + + private static PotionBrewer brewer; + + private static final int EXTENDED_BIT = 0x40; + private static final int POTION_BIT = 0xF; + private static final int SPLASH_BIT = 0x4000; + private static final int TIER_BIT = 0x20; + private static final int TIER_SHIFT = 5; + private static final int NAME_BIT = 0x3F; + + /** + * + * @deprecated Magic value + */ + @Deprecated + public static Potion fromDamage(int damage) { + PotionType type = PotionType.getByDamageValue(damage & POTION_BIT); + Potion potion; + if (type == null || (type == PotionType.WATER && damage != 0)) { + potion = new Potion(damage & NAME_BIT); + } else { + int level = (damage & TIER_BIT) >> TIER_SHIFT; + level++; + potion = new Potion(type, level); + } + if ((damage & SPLASH_BIT) > 0) { + potion = potion.splash(); + } + if ((damage & EXTENDED_BIT) > 0) { + potion = potion.extend(); + } + return potion; + } + + public static Potion fromItemStack(ItemStack item) { + Validate.notNull(item, "item cannot be null"); + if (item.getType() != Material.POTION) + throw new IllegalArgumentException("item is not a potion"); + return fromDamage(item.getDurability()); + } + + /** + * Returns an instance of {@link PotionBrewer}. + * + * @return An instance of PotionBrewer + */ + public static PotionBrewer getBrewer() { + return brewer; + } + + /** + * Sets the current instance of {@link PotionBrewer}. Generally not to be + * used from within a plugin. + * + * @param other The new PotionBrewer + */ + public static void setPotionBrewer(PotionBrewer other) { + if (brewer != null) + throw new IllegalArgumentException("brewer can only be set internally"); + brewer = other; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public int getNameId() { + return name; + } +} \ No newline at end of file diff --git a/src/main/java/org/bukkit/potion/PotionBrewer.java b/src/main/java/org/bukkit/potion/PotionBrewer.java new file mode 100644 index 0000000..5275517 --- /dev/null +++ b/src/main/java/org/bukkit/potion/PotionBrewer.java @@ -0,0 +1,31 @@ +package org.bukkit.potion; + +import java.util.Collection; + +/** + * Represents a brewer that can create {@link PotionEffect}s. + */ +public interface PotionBrewer { + + /** + * Creates a {@link PotionEffect} from the given {@link PotionEffectType}, + * applying duration modifiers and checks. + * + * @param potion The type of potion + * @param duration The duration in ticks + * @param amplifier The amplifier of the effect + * @return The resulting potion effect + */ + public PotionEffect createEffect(PotionEffectType potion, int duration, int amplifier); + + /** + * Returns a collection of {@link PotionEffect} that would be applied from + * a potion with the given data value. + * + * @param damage The data value of the potion + * @return The list of effects + * @deprecated Magic value + */ + @Deprecated + public Collection getEffectsFromDamage(int damage); +} diff --git a/src/main/java/org/bukkit/potion/PotionEffect.java b/src/main/java/org/bukkit/potion/PotionEffect.java new file mode 100644 index 0000000..24ee19d --- /dev/null +++ b/src/main/java/org/bukkit/potion/PotionEffect.java @@ -0,0 +1,179 @@ +package org.bukkit.potion; + +import java.util.Map; +import java.util.NoSuchElementException; + +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.entity.LivingEntity; + +import com.google.common.collect.ImmutableMap; + +/** + * Represents a potion effect, that can be added to a {@link LivingEntity}. A + * potion effect has a duration that it will last for, an amplifier that will + * enhance its effects, and a {@link PotionEffectType}, that represents its + * effect on an entity. + */ +@SerializableAs("PotionEffect") +public class PotionEffect implements ConfigurationSerializable { + private static final String AMPLIFIER = "amplifier"; + private static final String DURATION = "duration"; + private static final String TYPE = "effect"; + private static final String AMBIENT = "ambient"; + private final int amplifier; + private final int duration; + private final PotionEffectType type; + private final boolean ambient; + + /** + * Creates a potion effect. + * + * @param type effect type + * @param duration measured in ticks, see {@link + * PotionEffect#getDuration()} + * @param amplifier the amplifier, see {@link PotionEffect#getAmplifier()} + * @param ambient the ambient status, see {@link PotionEffect#isAmbient()} + */ + public PotionEffect(PotionEffectType type, int duration, int amplifier, boolean ambient) { + Validate.notNull(type, "effect type cannot be null"); + this.type = type; + this.duration = duration; + this.amplifier = amplifier; + this.ambient = ambient; + } + + /** + * Creates a potion effect. Assumes ambient is true. + * + * @param type Effect type + * @param duration measured in ticks + * @param amplifier the amplifier for the effect + * @see PotionEffect#PotionEffect(PotionEffectType, int, int, boolean) + */ + public PotionEffect(PotionEffectType type, int duration, int amplifier) { + this(type, duration, amplifier, true); + } + + /** + * Constructor for deserialization. + * + * @param map the map to deserialize from + */ + public PotionEffect(Map map) { + this(getEffectType(map), getInt(map, DURATION), getInt(map, AMPLIFIER), getBool(map, AMBIENT)); + } + + private static PotionEffectType getEffectType(Map map) { + int type = getInt(map, TYPE); + PotionEffectType effect = PotionEffectType.getById(type); + if (effect != null) { + return effect; + } + throw new NoSuchElementException(map + " does not contain " + TYPE); + } + + private static int getInt(Map map, Object key) { + Object num = map.get(key); + if (num instanceof Integer) { + return (Integer) num; + } + throw new NoSuchElementException(map + " does not contain " + key); + } + + private static boolean getBool(Map map, Object key) { + Object bool = map.get(key); + if (bool instanceof Boolean) { + return (Boolean) bool; + } + throw new NoSuchElementException(map + " does not contain " + key); + } + + public Map serialize() { + return ImmutableMap.of( + TYPE, type.getId(), + DURATION, duration, + AMPLIFIER, amplifier, + AMBIENT, ambient + ); + } + + /** + * Attempts to add the effect represented by this object to the given + * {@link LivingEntity}. + * + * @see LivingEntity#addPotionEffect(PotionEffect) + * @param entity The entity to add this effect to + * @return Whether the effect could be added + */ + public boolean apply(LivingEntity entity) { + return entity.addPotionEffect(this); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof PotionEffect)) { + return false; + } + PotionEffect that = (PotionEffect) obj; + return this.type.equals(that.type) && this.ambient == that.ambient && this.amplifier == that.amplifier && this.duration == that.duration; + } + + /** + * Returns the amplifier of this effect. A higher amplifier means the + * potion effect happens more often over its duration and in some cases + * has more effect on its target. + * + * @return The effect amplifier + */ + public int getAmplifier() { + return amplifier; + } + + /** + * Returns the duration (in ticks) that this effect will run for when + * applied to a {@link LivingEntity}. + * + * @return The duration of the effect + */ + public int getDuration() { + return duration; + } + + /** + * Returns the {@link PotionEffectType} of this effect. + * + * @return The potion type of this effect + */ + public PotionEffectType getType() { + return type; + } + + /** + * Makes potion effect produce more, translucent, particles. + * + * @return if this effect is ambient + */ + public boolean isAmbient() { + return ambient; + } + + @Override + public int hashCode() { + int hash = 1; + hash = hash * 31 + type.hashCode(); + hash = hash * 31 + amplifier; + hash = hash * 31 + duration; + hash ^= 0x22222222 >> (ambient ? 1 : -1); + return hash; + } + + @Override + public String toString() { + return type.getName() + (ambient ? ":(" : ":") + duration + "t-x" + amplifier + (ambient ? ")" : ""); + } +} diff --git a/src/main/java/org/bukkit/potion/PotionEffectType.java b/src/main/java/org/bukkit/potion/PotionEffectType.java new file mode 100644 index 0000000..4919d59 --- /dev/null +++ b/src/main/java/org/bukkit/potion/PotionEffectType.java @@ -0,0 +1,269 @@ +package org.bukkit.potion; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.Validate; + +/** + * Represents a type of potion and its effect on an entity. + */ +public abstract class PotionEffectType { + /** + * Increases movement speed. + */ + public static final PotionEffectType SPEED = new PotionEffectTypeWrapper(1); + + /** + * Decreases movement speed. + */ + public static final PotionEffectType SLOW = new PotionEffectTypeWrapper(2); + + /** + * Increases dig speed. + */ + public static final PotionEffectType FAST_DIGGING = new PotionEffectTypeWrapper(3); + + /** + * Decreases dig speed. + */ + public static final PotionEffectType SLOW_DIGGING = new PotionEffectTypeWrapper(4); + + /** + * Increases damage dealt. + */ + public static final PotionEffectType INCREASE_DAMAGE = new PotionEffectTypeWrapper(5); + + /** + * Heals an entity. + */ + public static final PotionEffectType HEAL = new PotionEffectTypeWrapper(6); + + /** + * Hurts an entity. + */ + public static final PotionEffectType HARM = new PotionEffectTypeWrapper(7); + + /** + * Increases jump height. + */ + public static final PotionEffectType JUMP = new PotionEffectTypeWrapper(8); + + /** + * Warps vision on the client. + */ + public static final PotionEffectType CONFUSION = new PotionEffectTypeWrapper(9); + + /** + * Regenerates health. + */ + public static final PotionEffectType REGENERATION = new PotionEffectTypeWrapper(10); + + /** + * Decreases damage dealt to an entity. + */ + public static final PotionEffectType DAMAGE_RESISTANCE = new PotionEffectTypeWrapper(11); + + /** + * Stops fire damage. + */ + public static final PotionEffectType FIRE_RESISTANCE = new PotionEffectTypeWrapper(12); + + /** + * Allows breathing underwater. + */ + public static final PotionEffectType WATER_BREATHING = new PotionEffectTypeWrapper(13); + + /** + * Grants invisibility. + */ + public static final PotionEffectType INVISIBILITY = new PotionEffectTypeWrapper(14); + + /** + * Blinds an entity. + */ + public static final PotionEffectType BLINDNESS = new PotionEffectTypeWrapper(15); + + /** + * Allows an entity to see in the dark. + */ + public static final PotionEffectType NIGHT_VISION = new PotionEffectTypeWrapper(16); + + /** + * Increases hunger. + */ + public static final PotionEffectType HUNGER = new PotionEffectTypeWrapper(17); + + /** + * Decreases damage dealt by an entity. + */ + public static final PotionEffectType WEAKNESS = new PotionEffectTypeWrapper(18); + + /** + * Deals damage to an entity over time. + */ + public static final PotionEffectType POISON = new PotionEffectTypeWrapper(19); + + /** + * Deals damage to an entity over time and gives the health to the + * shooter. + */ + public static final PotionEffectType WITHER = new PotionEffectTypeWrapper(20); + + /** + * Increases the maximum health of an entity. + */ + public static final PotionEffectType HEALTH_BOOST = new PotionEffectTypeWrapper(21); + + /** + * Increases the maximum health of an entity with health that cannot be + * regenerated, but is refilled every 30 seconds. + */ + public static final PotionEffectType ABSORPTION = new PotionEffectTypeWrapper(22); + + /** + * Increases the food level of an entity each tick. + */ + public static final PotionEffectType SATURATION = new PotionEffectTypeWrapper(23); + + private final int id; + + protected PotionEffectType(int id) { + this.id = id; + } + + /** + * Creates a PotionEffect from this PotionEffectType, applying duration + * modifiers and checks. + * + * @see PotionBrewer#createEffect(PotionEffectType, int, int) + * @param duration time in ticks + * @param amplifier the effect's amplifier + * @return a resulting potion effect + */ + public PotionEffect createEffect(int duration, int amplifier) { + return Potion.getBrewer().createEffect(this, duration, amplifier); + } + + /** + * Returns the duration modifier applied to effects of this type. + * + * @return duration modifier + */ + public abstract double getDurationModifier(); + + /** + * Returns the unique ID of this type. + * + * @return Unique ID + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Returns the name of this effect type. + * + * @return The name of this effect type + */ + public abstract String getName(); + + /** + * Returns whether the effect of this type happens once, immediately. + * + * @return whether this type is normally instant + */ + public abstract boolean isInstant(); + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof PotionEffectType)) { + return false; + } + final PotionEffectType other = (PotionEffectType) obj; + if (this.id != other.id) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return id; + } + + @Override + public String toString() { + return "PotionEffectType[" + id + ", " + getName() + "]"; + } + + private static final PotionEffectType[] byId = new PotionEffectType[24]; + private static final Map byName = new HashMap(); + // will break on updates. + private static boolean acceptingNew = true; + + /** + * Gets the effect type specified by the unique id. + * + * @param id Unique ID to fetch + * @return Resulting type, or null if not found. + * @deprecated Magic value + */ + @Deprecated + public static PotionEffectType getById(int id) { + if (id >= byId.length || id < 0) + return null; + return byId[id]; + } + + /** + * Gets the effect type specified by the given name. + * + * @param name Name of PotionEffectType to fetch + * @return Resulting PotionEffectType, or null if not found. + */ + public static PotionEffectType getByName(String name) { + Validate.notNull(name, "name cannot be null"); + return byName.get(name.toLowerCase()); + } + + /** + * Registers an effect type with the given object. + *

            + * Generally not to be used from within a plugin. + * + * @param type PotionType to register + */ + public static void registerPotionEffectType(PotionEffectType type) { + if (byId[type.id] != null || byName.containsKey(type.getName().toLowerCase())) { + throw new IllegalArgumentException("Cannot set already-set type"); + } else if (!acceptingNew) { + throw new IllegalStateException( + "No longer accepting new potion effect types (can only be done by the server implementation)"); + } + + byId[type.id] = type; + byName.put(type.getName().toLowerCase(), type); + } + + /** + * Stops accepting any effect type registrations. + */ + public static void stopAcceptingRegistrations() { + acceptingNew = false; + } + + /** + * Returns an array of all the registered {@link PotionEffectType}s. + * + * @return Array of types. + */ + public static PotionEffectType[] values() { + return byId.clone(); + } +} diff --git a/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java b/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java new file mode 100644 index 0000000..5db1ce8 --- /dev/null +++ b/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java @@ -0,0 +1,31 @@ +package org.bukkit.potion; + +public class PotionEffectTypeWrapper extends PotionEffectType { + protected PotionEffectTypeWrapper(int id) { + super(id); + } + + @Override + public double getDurationModifier() { + return getType().getDurationModifier(); + } + + @Override + public String getName() { + return getType().getName(); + } + + /** + * Get the potion type bound to this wrapper. + * + * @return The potion effect type + */ + public PotionEffectType getType() { + return PotionEffectType.getById(getId()); + } + + @Override + public boolean isInstant() { + return getType().isInstant(); + } +} diff --git a/src/main/java/org/bukkit/potion/PotionType.java b/src/main/java/org/bukkit/potion/PotionType.java new file mode 100644 index 0000000..a02b6a8 --- /dev/null +++ b/src/main/java/org/bukkit/potion/PotionType.java @@ -0,0 +1,71 @@ +package org.bukkit.potion; + +public enum PotionType { + WATER(0, null, 0), + REGEN(1, PotionEffectType.REGENERATION, 2), + SPEED(2, PotionEffectType.SPEED, 2), + FIRE_RESISTANCE(3, PotionEffectType.FIRE_RESISTANCE, 1), + POISON(4, PotionEffectType.POISON, 2), + INSTANT_HEAL(5, PotionEffectType.HEAL, 2), + NIGHT_VISION(6, PotionEffectType.NIGHT_VISION, 1), + WEAKNESS(8, PotionEffectType.WEAKNESS, 1), + STRENGTH(9, PotionEffectType.INCREASE_DAMAGE, 2), + SLOWNESS(10, PotionEffectType.SLOW, 1), + INSTANT_DAMAGE(12, PotionEffectType.HARM, 2), + WATER_BREATHING(13, PotionEffectType.WATER_BREATHING, 1), + INVISIBILITY(14, PotionEffectType.INVISIBILITY, 1), + ; + + private final int damageValue, maxLevel; + private final PotionEffectType effect; + + PotionType(int damageValue, PotionEffectType effect, int maxLevel) { + this.damageValue = damageValue; + this.effect = effect; + this.maxLevel = maxLevel; + } + + public PotionEffectType getEffectType() { + return effect; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public int getDamageValue() { + return damageValue; + } + + public int getMaxLevel() { + return maxLevel; + } + + public boolean isInstant() { + return effect == null ? true : effect.isInstant(); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + public static PotionType getByDamageValue(int damage) { + for (PotionType type : PotionType.values()) { + if (type.damageValue == damage) + return type; + } + return null; + } + + public static PotionType getByEffect(PotionEffectType effectType) { + if (effectType == null) + return WATER; + for (PotionType type : PotionType.values()) { + if (effectType.equals(type.effect)) + return type; + } + return null; + } +} diff --git a/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java b/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java new file mode 100644 index 0000000..e713c0d --- /dev/null +++ b/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java @@ -0,0 +1,13 @@ +package org.bukkit.projectiles; + +import org.bukkit.block.Block; + +public interface BlockProjectileSource extends ProjectileSource { + + /** + * Gets the block this projectile source belongs to. + * + * @return Block for the projectile source + */ + public Block getBlock(); +} diff --git a/src/main/java/org/bukkit/projectiles/ProjectileSource.java b/src/main/java/org/bukkit/projectiles/ProjectileSource.java new file mode 100644 index 0000000..afad8d7 --- /dev/null +++ b/src/main/java/org/bukkit/projectiles/ProjectileSource.java @@ -0,0 +1,28 @@ +package org.bukkit.projectiles; + +import org.bukkit.entity.Projectile; +import org.bukkit.util.Vector; + +/** + * Represents a valid source of a projectile. + */ +public interface ProjectileSource { + + /** + * Launches a {@link Projectile} from the ProjectileSource. + * + * @param projectile class of the projectile to launch + * @return the launched projectile + */ + public T launchProjectile(Class projectile); + + /** + * Launches a {@link Projectile} from the ProjectileSource with an + * initial velocity. + * + * @param projectile class of the projectile to launch + * @param velocity the velocity with which to launch + * @return the launched projectile + */ + public T launchProjectile(Class projectile, Vector velocity); +} diff --git a/src/main/java/org/bukkit/scheduler/BukkitRunnable.java b/src/main/java/org/bukkit/scheduler/BukkitRunnable.java new file mode 100644 index 0000000..0351944 --- /dev/null +++ b/src/main/java/org/bukkit/scheduler/BukkitRunnable.java @@ -0,0 +1,149 @@ +package org.bukkit.scheduler; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +/** + * This class is provided as an easy way to handle scheduling tasks. + */ +public abstract class BukkitRunnable implements Runnable { + private int taskId = -1; + + /** + * Attempts to cancel this task. + * + * @throws IllegalStateException if task was not scheduled yet + */ + public synchronized void cancel() throws IllegalStateException { + Bukkit.getScheduler().cancelTask(getTaskId()); + } + + /** + * Schedules this in the Bukkit scheduler to run on next tick. + * + * @param plugin the reference to the plugin scheduling task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTask(Plugin, Runnable) + */ + public synchronized BukkitTask runTask(Plugin plugin) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTask(plugin, this)); + } + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Schedules this in the Bukkit scheduler to run asynchronously. + * + * @param plugin the reference to the plugin scheduling task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskAsynchronously(Plugin, Runnable) + */ + public synchronized BukkitTask runTaskAsynchronously(Plugin plugin) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskAsynchronously(plugin, this)); + } + + /** + * Schedules this to run after the specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskLater(Plugin, Runnable, long) + */ + public synchronized BukkitTask runTaskLater(Plugin plugin, long delay) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskLater(plugin, this, delay)); + } + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Schedules this to run asynchronously after the specified number of + * server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskLaterAsynchronously(Plugin, Runnable, long) + */ + public synchronized BukkitTask runTaskLaterAsynchronously(Plugin plugin, long delay) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, this, delay)); + } + + /** + * Schedules this to repeatedly run until cancelled, starting after the + * specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param delay the ticks to wait before running the task + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskTimer(Plugin, Runnable, long, long) + */ + public synchronized BukkitTask runTaskTimer(Plugin plugin, long delay, long period) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskTimer(plugin, this, delay, period)); + } + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Schedules this to repeatedly run asynchronously until cancelled, + * starting after the specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param delay the ticks to wait before running the task for the first + * time + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskTimerAsynchronously(Plugin, Runnable, long, + * long) + */ + public synchronized BukkitTask runTaskTimerAsynchronously(Plugin plugin, long delay, long period) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, this, delay, period)); + } + + /** + * Gets the task id for this runnable. + * + * @return the task id that this runnable was scheduled as + * @throws IllegalStateException if task was not scheduled yet + */ + public synchronized int getTaskId() throws IllegalStateException { + final int id = taskId; + if (id == -1) { + throw new IllegalStateException("Not scheduled yet"); + } + return id; + } + + private void checkState() { + if (taskId != -1) { + throw new IllegalStateException("Already scheduled as " + taskId); + } + } + + private BukkitTask setupId(final BukkitTask task) { + this.taskId = task.getTaskId(); + return task; + } +} diff --git a/src/main/java/org/bukkit/scheduler/BukkitScheduler.java b/src/main/java/org/bukkit/scheduler/BukkitScheduler.java new file mode 100644 index 0000000..44d94f0 --- /dev/null +++ b/src/main/java/org/bukkit/scheduler/BukkitScheduler.java @@ -0,0 +1,265 @@ +package org.bukkit.scheduler; + +import org.bukkit.plugin.Plugin; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import java.util.List; + +public interface BukkitScheduler { + + /** + * Schedules a once off task to occur after a delay. + *

            + * This task will be executed by the main server thread. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing task + * @return Task id number (-1 if scheduling failed) + */ + public int scheduleSyncDelayedTask(Plugin plugin, Runnable task, long delay); + + /** + * Schedules a once off task to occur as soon as possible. + *

            + * This task will be executed by the main server thread. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @return Task id number (-1 if scheduling failed) + */ + public int scheduleSyncDelayedTask(Plugin plugin, Runnable task); + + /** + * Schedules a repeating task. + *

            + * This task will be executed by the main server thread. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing first repeat + * @param period Period in server ticks of the task + * @return Task id number (-1 if scheduling failed) + */ + public int scheduleSyncRepeatingTask(Plugin plugin, Runnable task, long delay, long period); + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Schedules a once off task to occur after a delay. This task will be + * executed by a thread managed by the scheduler. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing task + * @return Task id number (-1 if scheduling failed) + * @deprecated This name is misleading, as it does not schedule "a sync" + * task, but rather, "an async" task + */ + @Deprecated + public int scheduleAsyncDelayedTask(Plugin plugin, Runnable task, long delay); + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Schedules a once off task to occur as soon as possible. This task will + * be executed by a thread managed by the scheduler. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @return Task id number (-1 if scheduling failed) + * @deprecated This name is misleading, as it does not schedule "a sync" + * task, but rather, "an async" task + */ + @Deprecated + public int scheduleAsyncDelayedTask(Plugin plugin, Runnable task); + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Schedules a repeating task. This task will be executed by a thread + * managed by the scheduler. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing first repeat + * @param period Period in server ticks of the task + * @return Task id number (-1 if scheduling failed) + * @deprecated This name is misleading, as it does not schedule "a sync" + * task, but rather, "an async" task + */ + @Deprecated + public int scheduleAsyncRepeatingTask(Plugin plugin, Runnable task, long delay, long period); + + /** + * Calls a method on the main thread and returns a Future object. This + * task will be executed by the main server thread. + *

              + *
            • Note: The Future.get() methods must NOT be called from the main + * thread. + *
            • Note2: There is at least an average of 10ms latency until the + * isDone() method returns true. + *
            + * @param The callable's return type + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @return Future Future object related to the task + */ + public Future callSyncMethod(Plugin plugin, Callable task); + + /** + * Removes task from scheduler. + * + * @param taskId Id number of task to be removed + */ + public void cancelTask(int taskId); + + /** + * Removes all tasks associated with a particular plugin from the + * scheduler. + * + * @param plugin Owner of tasks to be removed + */ + public void cancelTasks(Plugin plugin); + + /** + * Removes all tasks from the scheduler. + */ + public void cancelAllTasks(); + + /** + * Check if the task currently running. + *

            + * A repeating task might not be running currently, but will be running in + * the future. A task that has finished, and does not repeat, will not be + * running ever again. + *

            + * Explicitly, a task is running if there exists a thread for it, and that + * thread is alive. + * + * @param taskId The task to check. + *

            + * @return If the task is currently running. + */ + public boolean isCurrentlyRunning(int taskId); + + /** + * Check if the task queued to be run later. + *

            + * If a repeating task is currently running, it might not be queued now + * but could be in the future. A task that is not queued, and not running, + * will not be queued again. + * + * @param taskId The task to check. + *

            + * @return If the task is queued to be run. + */ + public boolean isQueued(int taskId); + + /** + * Returns a list of all active workers. + *

            + * This list contains asynch tasks that are being executed by separate + * threads. + * + * @return Active workers + */ + public List getActiveWorkers(); + + /** + * Returns a list of all pending tasks. The ordering of the tasks is not + * related to their order of execution. + * + * @return Active workers + */ + public List getPendingTasks(); + + /** + * Returns a task that will run on the next server tick. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + public BukkitTask runTask(Plugin plugin, Runnable task) throws IllegalArgumentException; + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Returns a task that will run asynchronously. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + public BukkitTask runTaskAsynchronously(Plugin plugin, Runnable task) throws IllegalArgumentException; + + /** + * Returns a task that will run after the specified number of server + * ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + public BukkitTask runTaskLater(Plugin plugin, Runnable task, long delay) throws IllegalArgumentException; + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Returns a task that will run asynchronously after the specified number + * of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable task, long delay) throws IllegalArgumentException; + + /** + * Returns a task that will repeatedly run until cancelled, starting after + * the specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + public BukkitTask runTaskTimer(Plugin plugin, Runnable task, long delay, long period) throws IllegalArgumentException; + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

            + * Returns a task that will repeatedly run asynchronously until cancelled, + * starting after the specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task for the first + * time + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable task, long delay, long period) throws IllegalArgumentException; +} diff --git a/src/main/java/org/bukkit/scheduler/BukkitTask.java b/src/main/java/org/bukkit/scheduler/BukkitTask.java new file mode 100644 index 0000000..e447e64 --- /dev/null +++ b/src/main/java/org/bukkit/scheduler/BukkitTask.java @@ -0,0 +1,35 @@ +package org.bukkit.scheduler; + +import org.bukkit.plugin.Plugin; + +/** + * Represents a task being executed by the scheduler + */ +public interface BukkitTask { + + /** + * Returns the taskId for the task. + * + * @return Task id number + */ + public int getTaskId(); + + /** + * Returns the Plugin that owns this task. + * + * @return The Plugin that owns the task + */ + public Plugin getOwner(); + + /** + * Returns true if the Task is a sync task. + * + * @return true if the task is run by main thread + */ + public boolean isSync(); + + /** + * Will attempt to cancel this task. + */ + public void cancel(); +} diff --git a/src/main/java/org/bukkit/scheduler/BukkitWorker.java b/src/main/java/org/bukkit/scheduler/BukkitWorker.java new file mode 100644 index 0000000..fe1afbd --- /dev/null +++ b/src/main/java/org/bukkit/scheduler/BukkitWorker.java @@ -0,0 +1,34 @@ +package org.bukkit.scheduler; + +import org.bukkit.plugin.Plugin; + +/** + * Represents a worker thread for the scheduler. This gives information about + * the Thread object for the task, owner of the task and the taskId. + *

            + * Workers are used to execute async tasks. + */ +public interface BukkitWorker { + + /** + * Returns the taskId for the task being executed by this worker. + * + * @return Task id number + */ + public int getTaskId(); + + /** + * Returns the Plugin that owns this task. + * + * @return The Plugin that owns the task + */ + public Plugin getOwner(); + + /** + * Returns the thread for the worker. + * + * @return The Thread object for the worker + */ + public Thread getThread(); + +} diff --git a/src/main/java/org/bukkit/scoreboard/Criterias.java b/src/main/java/org/bukkit/scoreboard/Criterias.java new file mode 100644 index 0000000..cd81c87 --- /dev/null +++ b/src/main/java/org/bukkit/scoreboard/Criterias.java @@ -0,0 +1,20 @@ +package org.bukkit.scoreboard; + +/** + * Criteria names which trigger an objective to be modified by actions in-game + */ +public class Criterias { + public static final String HEALTH; + public static final String PLAYER_KILLS; + public static final String TOTAL_KILLS; + public static final String DEATHS; + + static { + HEALTH="health"; + PLAYER_KILLS="playerKillCount"; + TOTAL_KILLS="totalKillCount"; + DEATHS="deathCount"; + } + + private Criterias() {} +} diff --git a/src/main/java/org/bukkit/scoreboard/DisplaySlot.java b/src/main/java/org/bukkit/scoreboard/DisplaySlot.java new file mode 100644 index 0000000..5d58a18 --- /dev/null +++ b/src/main/java/org/bukkit/scoreboard/DisplaySlot.java @@ -0,0 +1,10 @@ +package org.bukkit.scoreboard; + +/** + * Locations for displaying objectives to the player + */ +public enum DisplaySlot { + BELOW_NAME, + PLAYER_LIST, + SIDEBAR; +} diff --git a/src/main/java/org/bukkit/scoreboard/Objective.java b/src/main/java/org/bukkit/scoreboard/Objective.java new file mode 100644 index 0000000..321aac7 --- /dev/null +++ b/src/main/java/org/bukkit/scoreboard/Objective.java @@ -0,0 +1,110 @@ +package org.bukkit.scoreboard; + +import org.bukkit.OfflinePlayer; + +/** + * An objective on a scoreboard that can show scores specific to entries. This + * objective is only relevant to the display of the associated {@link + * #getScoreboard() scoreboard}. + */ +public interface Objective { + + /** + * Gets the name of this Objective + * + * @return this objective'ss name + * @throws IllegalStateException if this objective has been unregistered + */ + String getName() throws IllegalStateException; + + /** + * Gets the name displayed to players for this objective + * + * @return this objective's display name + * @throws IllegalStateException if this objective has been unregistered + */ + String getDisplayName() throws IllegalStateException; + + /** + * Sets the name displayed to players for this objective. + * + * @param displayName Display name to set + * @throws IllegalStateException if this objective has been unregistered + * @throws IllegalArgumentException if displayName is null + * @throws IllegalArgumentException if displayName is longer than 32 + * characters. + */ + void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException; + + /** + * Gets the criteria this objective tracks. + * + * @return this objective's criteria + * @throws IllegalStateException if this objective has been unregistered + */ + String getCriteria() throws IllegalStateException; + + /** + * Gets if the objective's scores can be modified directly by a plugin. + * + * @return true if scores are modifiable + * @throws IllegalStateException if this objective has been unregistered + * @see Criterias#HEALTH + */ + boolean isModifiable() throws IllegalStateException; + + /** + * Gets the scoreboard to which this objective is attached. + * + * @return Owning scoreboard, or null if it has been {@link #unregister() + * unregistered} + */ + Scoreboard getScoreboard(); + + /** + * Unregisters this objective from the {@link Scoreboard scoreboard.} + * + * @throws IllegalStateException if this objective has been unregistered + */ + void unregister() throws IllegalStateException; + + /** + * Sets this objective to display on the specified slot for the + * scoreboard, removing it from any other display slot. + * + * @param slot display slot to change, or null to not display + * @throws IllegalStateException if this objective has been unregistered + */ + void setDisplaySlot(DisplaySlot slot) throws IllegalStateException; + + /** + * Gets the display slot this objective is displayed at. + * + * @return the display slot for this objective, or null if not displayed + * @throws IllegalStateException if this objective has been unregistered + */ + DisplaySlot getDisplaySlot() throws IllegalStateException; + + /** + * Gets a player's Score for an Objective on this Scoreboard + * + * @param player Player for the Score + * @return Score tracking the Objective and player specified + * @throws IllegalArgumentException if player is null + * @throws IllegalStateException if this objective has been unregistered + * @deprecated Scoreboards can contain entries that aren't players + * @see #getScore(String) + */ + @Deprecated + Score getScore(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException; + + /** + * Gets an entry's Score for an Objective on this Scoreboard. + * + * @param entry Entry for the Score + * @return Score tracking the Objective and entry specified + * @throws IllegalArgumentException if entry is null + * @throws IllegalStateException if this objective has been unregistered + */ + Score getScore(String entry) throws IllegalArgumentException, IllegalStateException; +} diff --git a/src/main/java/org/bukkit/scoreboard/Score.java b/src/main/java/org/bukkit/scoreboard/Score.java new file mode 100644 index 0000000..4c10346 --- /dev/null +++ b/src/main/java/org/bukkit/scoreboard/Score.java @@ -0,0 +1,61 @@ +package org.bukkit.scoreboard; + +import org.bukkit.OfflinePlayer; + +/** + * A score entry for an {@link #getEntry() entry} on an {@link + * #getObjective() objective}. Changing this will not affect any other + * objective or scoreboard. + */ +public interface Score { + + /** + * Gets the OfflinePlayer being tracked by this Score + * + * @return this Score's tracked player + * @deprecated Scoreboards can contain entries that aren't players + * @see #getEntry() + */ + @Deprecated + OfflinePlayer getPlayer(); + + /** + * Gets the entry being tracked by this Score + * + * @return this Score's tracked entry + */ + String getEntry(); + + /** + * Gets the Objective being tracked by this Score + * + * @return this Score's tracked objective + */ + Objective getObjective(); + + /** + * Gets the current score + * + * @return the current score + * @throws IllegalStateException if the associated objective has been + * unregistered + */ + int getScore() throws IllegalStateException; + + /** + * Sets the current score. + * + * @param score New score + * @throws IllegalStateException if the associated objective has been + * unregistered + */ + void setScore(int score) throws IllegalStateException; + + /** + * Gets the scoreboard for the associated objective. + * + * @return the owning objective's scoreboard, or null if it has been + * {@link Objective#unregister() unregistered} + */ + Scoreboard getScoreboard(); +} diff --git a/src/main/java/org/bukkit/scoreboard/Scoreboard.java b/src/main/java/org/bukkit/scoreboard/Scoreboard.java new file mode 100644 index 0000000..d244a7f --- /dev/null +++ b/src/main/java/org/bukkit/scoreboard/Scoreboard.java @@ -0,0 +1,159 @@ +package org.bukkit.scoreboard; + +import java.util.Set; + +import org.bukkit.OfflinePlayer; + +/** + * A scoreboard + */ +public interface Scoreboard { + + /** + * Registers an Objective on this Scoreboard + * + * @param name Name of the Objective + * @param criteria Criteria for the Objective + * @return The registered Objective + * @throws IllegalArgumentException if name is null + * @throws IllegalArgumentException if criteria is null + * @throws IllegalArgumentException if an objective by that name already + * exists + */ + Objective registerNewObjective(String name, String criteria) throws IllegalArgumentException; + + /** + * Gets an Objective on this Scoreboard by name + * + * @param name Name of the Objective + * @return the Objective or null if it does not exist + * @throws IllegalArgumentException if name is null + */ + Objective getObjective(String name) throws IllegalArgumentException; + + /** + * Gets all Objectives of a Criteria on the Scoreboard + * + * @param criteria Criteria to search by + * @return an immutable set of Objectives using the specified Criteria + */ + Set getObjectivesByCriteria(String criteria) throws IllegalArgumentException; + + /** + * Gets all Objectives on this Scoreboard + * + * @return An immutable set of all Objectives on this Scoreboard + */ + Set getObjectives(); + + /** + * Gets the Objective currently displayed in a DisplaySlot on this + * Scoreboard + * + * @param slot The DisplaySlot + * @return the Objective currently displayed or null if nothing is + * displayed in that DisplaySlot + * @throws IllegalArgumentException if slot is null + */ + Objective getObjective(DisplaySlot slot) throws IllegalArgumentException; + + /** + * Gets all scores for a player on this Scoreboard + * + * @param player the player whose scores are being retrieved + * @return immutable set of all scores tracked for the player + * @throws IllegalArgumentException if player is null + * @deprecated Scoreboards can contain entries that aren't players + * @see #getScores(String) + */ + @Deprecated + Set getScores(OfflinePlayer player) throws IllegalArgumentException; + + /** + * Gets all scores for an entry on this Scoreboard + * + * @param entry the entry whose scores are being retrieved + * @return immutable set of all scores tracked for the entry + * @throws IllegalArgumentException if entry is null + */ + Set getScores(String entry) throws IllegalArgumentException; + + /** + * Removes all scores for a player on this Scoreboard + * + * @param player the player to drop all current scores for + * @throws IllegalArgumentException if player is null + * @deprecated Scoreboards can contain entries that aren't players + * @see #resetScores(String) + */ + @Deprecated + void resetScores(OfflinePlayer player) throws IllegalArgumentException; + + /** + * Removes all scores for an entry on this Scoreboard + * + * @param entry the entry to drop all current scores for + * @throws IllegalArgumentException if entry is null + */ + void resetScores(String entry) throws IllegalArgumentException; + + /** + * Gets a player's Team on this Scoreboard + * + * @param player the player to search for + * @return the player's Team or null if the player is not on a team + * @throws IllegalArgumentException if player is null + */ + Team getPlayerTeam(OfflinePlayer player) throws IllegalArgumentException; + + /** + * Gets a Team by name on this Scoreboard + * + * @param teamName Team name + * @return the matching Team or null if no matches + * @throws IllegalArgumentException if teamName is null + */ + Team getTeam(String teamName) throws IllegalArgumentException; + + /** + * Gets all teams on this Scoreboard + * + * @return an immutable set of Teams + */ + Set getTeams(); + + /** + * Registers a Team on this Scoreboard + * + * @param name Team name + * @return registered Team + * @throws IllegalArgumentException if name is null + * @throws IllegalArgumentException if team by that name already exists + */ + Team registerNewTeam(String name) throws IllegalArgumentException; + + /** + * Gets all players tracked by this Scoreboard + * + * @return immutable set of all tracked players + * @deprecated Scoreboards can contain entries that aren't players + * @see #getEntries() + */ + @Deprecated + Set getPlayers(); + + /** + * Gets all entries tracked by this Scoreboard + * + * @return immutable set of all tracked entries + */ + Set getEntries(); + + /** + * Clears any objective in the specified slot. + * + * @param slot the slot to remove objectives + * @throws IllegalArgumentException if slot is null + */ + void clearSlot(DisplaySlot slot) throws IllegalArgumentException; +} diff --git a/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java b/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java new file mode 100644 index 0000000..00b67a1 --- /dev/null +++ b/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java @@ -0,0 +1,29 @@ +package org.bukkit.scoreboard; + +import java.lang.ref.WeakReference; + +/** + * Manager of Scoreboards + */ +public interface ScoreboardManager { + + /** + * Gets the primary Scoreboard controlled by the server. + *

            + * This Scoreboard is saved by the server, is affected by the /scoreboard + * command, and is the scoreboard shown by default to players. + * + * @return the default sever scoreboard + */ + Scoreboard getMainScoreboard(); + + /** + * Gets a new Scoreboard to be tracked by the server. This scoreboard will + * be tracked as long as a reference is kept, either by a player or by a + * plugin. + * + * @return the registered Scoreboard + * @see WeakReference + */ + Scoreboard getNewScoreboard(); +} diff --git a/src/main/java/org/bukkit/scoreboard/Team.java b/src/main/java/org/bukkit/scoreboard/Team.java new file mode 100644 index 0000000..50c6f76 --- /dev/null +++ b/src/main/java/org/bukkit/scoreboard/Team.java @@ -0,0 +1,174 @@ +package org.bukkit.scoreboard; + +import java.util.Set; + +import org.bukkit.OfflinePlayer; +import org.bukkit.potion.PotionEffectType; + +/** + * A team on a scoreboard that has a common display theme and other + * properties. This team is only relevant to the display of the associated + * {@link #getScoreboard() scoreboard}. + */ +public interface Team { + + /** + * Gets the name of this Team + * + * @return Objective name + * @throws IllegalStateException if this team has been unregistered + */ + String getName() throws IllegalStateException; + + /** + * Gets the name displayed to players for this team + * + * @return Team display name + * @throws IllegalStateException if this team has been unregistered + */ + String getDisplayName() throws IllegalStateException; + + /** + * Sets the name displayed to players for this team + * + * @param displayName New display name + * @throws IllegalArgumentException if displayName is longer than 32 + * characters. + * @throws IllegalStateException if this team has been unregistered + */ + void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException; + + /** + * Gets the prefix prepended to the display of players on this team. + * + * @return Team prefix + * @throws IllegalStateException if this team has been unregistered + */ + String getPrefix() throws IllegalStateException; + + /** + * Sets the prefix prepended to the display of players on this team. + * + * @param prefix New prefix + * @throws IllegalArgumentException if prefix is null + * @throws IllegalArgumentException if prefix is longer than 16 + * characters + * @throws IllegalStateException if this team has been unregistered + */ + void setPrefix(String prefix) throws IllegalStateException, IllegalArgumentException; + + /** + * Gets the suffix appended to the display of players on this team. + * + * @return the team's current suffix + * @throws IllegalStateException if this team has been unregistered + */ + String getSuffix() throws IllegalStateException; + + /** + * Sets the suffix appended to the display of players on this team. + * + * @param suffix the new suffix for this team. + * @throws IllegalArgumentException if suffix is null + * @throws IllegalArgumentException if suffix is longer than 16 + * characters + * @throws IllegalStateException if this team has been unregistered + */ + void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException; + + /** + * Gets the team friendly fire state + * + * @return true if friendly fire is enabled + * @throws IllegalStateException if this team has been unregistered + */ + boolean allowFriendlyFire() throws IllegalStateException; + + /** + * Sets the team friendly fire state + * + * @param enabled true if friendly fire is to be allowed + * @throws IllegalStateException if this team has been unregistered + */ + void setAllowFriendlyFire(boolean enabled) throws IllegalStateException; + + /** + * Gets the team's ability to see {@link PotionEffectType#INVISIBILITY + * invisible} teammates. + * + * @return true if team members can see invisible members + * @throws IllegalStateException if this team has been unregistered + */ + boolean canSeeFriendlyInvisibles() throws IllegalStateException; + + /** + * Sets the team's ability to see {@link PotionEffectType#INVISIBILITY + * invisible} teammates. + * + * @param enabled true if invisible teammates are to be visible + * @throws IllegalStateException if this team has been unregistered + */ + void setCanSeeFriendlyInvisibles(boolean enabled) throws IllegalStateException; + + /** + * Gets the Set of players on the team + * + * @return players on the team + * @throws IllegalStateException if this team has been unregistered + */ + Set getPlayers() throws IllegalStateException; + + /** + * Gets the size of the team + * + * @return number of players on the team + * @throws IllegalStateException if this team has been unregistered + */ + int getSize() throws IllegalStateException; + + /** + * Gets the Scoreboard to which this team is attached + * + * @return Owning scoreboard, or null if this team has been {@link + * #unregister() unregistered} + */ + Scoreboard getScoreboard(); + + /** + * This puts the specified player onto this team for the scoreboard. + *

            + * This will remove the player from any other team on the scoreboard. + * + * @param player the player to add + * @throws IllegalArgumentException if player is null + * @throws IllegalStateException if this team has been unregistered + */ + void addPlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException; + + /** + * Removes the player from this team. + * + * @param player the player to remove + * @return if the player was on this team + * @throws IllegalArgumentException if player is null + * @throws IllegalStateException if this team has been unregistered + */ + boolean removePlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException; + + /** + * Unregisters this team from the Scoreboard + * + * @throws IllegalStateException if this team has been unregistered + */ + void unregister() throws IllegalStateException; + + /** + * Checks to see if the specified player is a member of this team. + * + * @param player the player to search for + * @return true if the player is a member of this team + * @throws IllegalArgumentException if player is null + * @throws IllegalStateException if this team has been unregistered + */ + boolean hasPlayer(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException; +} diff --git a/src/main/java/org/bukkit/util/BlockIterator.java b/src/main/java/org/bukkit/util/BlockIterator.java new file mode 100644 index 0000000..5c85778 --- /dev/null +++ b/src/main/java/org/bukkit/util/BlockIterator.java @@ -0,0 +1,357 @@ +package org.bukkit.util; + +import static org.bukkit.util.NumberConversions.*; + +import org.bukkit.World; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.LivingEntity; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * This class performs ray tracing and iterates along blocks on a line + */ +public class BlockIterator implements Iterator { + + private final World world; + private final int maxDistance; + + private static final int gridSize = 1 << 24; + + private boolean end = false; + + private Block[] blockQueue = new Block[3]; + private int currentBlock = 0; + private int currentDistance = 0; + private int maxDistanceInt; + + private int secondError; + private int thirdError; + + private int secondStep; + private int thirdStep; + + private BlockFace mainFace; + private BlockFace secondFace; + private BlockFace thirdFace; + + /** + * Constructs the BlockIterator + * + * @param world The world to use for tracing + * @param start A Vector giving the initial location for the trace + * @param direction A Vector pointing in the direction for the trace + * @param yOffset The trace begins vertically offset from the start vector + * by this value + * @param maxDistance This is the maximum distance in blocks for the + * trace. Setting this value above 140 may lead to problems with + * unloaded chunks. A value of 0 indicates no limit + * + */ + public BlockIterator(World world, Vector start, Vector direction, double yOffset, int maxDistance) { + this.world = world; + this.maxDistance = maxDistance; + + Vector startClone = start.clone(); + + startClone.setY(startClone.getY() + yOffset); + + currentDistance = 0; + + double mainDirection = 0; + double secondDirection = 0; + double thirdDirection = 0; + + double mainPosition = 0; + double secondPosition = 0; + double thirdPosition = 0; + + Block startBlock = this.world.getBlockAt(floor(startClone.getX()), floor(startClone.getY()), floor(startClone.getZ())); + + if (getXLength(direction) > mainDirection) { + mainFace = getXFace(direction); + mainDirection = getXLength(direction); + mainPosition = getXPosition(direction, startClone, startBlock); + + secondFace = getYFace(direction); + secondDirection = getYLength(direction); + secondPosition = getYPosition(direction, startClone, startBlock); + + thirdFace = getZFace(direction); + thirdDirection = getZLength(direction); + thirdPosition = getZPosition(direction, startClone, startBlock); + } + if (getYLength(direction) > mainDirection) { + mainFace = getYFace(direction); + mainDirection = getYLength(direction); + mainPosition = getYPosition(direction, startClone, startBlock); + + secondFace = getZFace(direction); + secondDirection = getZLength(direction); + secondPosition = getZPosition(direction, startClone, startBlock); + + thirdFace = getXFace(direction); + thirdDirection = getXLength(direction); + thirdPosition = getXPosition(direction, startClone, startBlock); + } + if (getZLength(direction) > mainDirection) { + mainFace = getZFace(direction); + mainDirection = getZLength(direction); + mainPosition = getZPosition(direction, startClone, startBlock); + + secondFace = getXFace(direction); + secondDirection = getXLength(direction); + secondPosition = getXPosition(direction, startClone, startBlock); + + thirdFace = getYFace(direction); + thirdDirection = getYLength(direction); + thirdPosition = getYPosition(direction, startClone, startBlock); + } + + // trace line backwards to find intercept with plane perpendicular to the main axis + + double d = mainPosition / mainDirection; // how far to hit face behind + double secondd = secondPosition - secondDirection * d; + double thirdd = thirdPosition - thirdDirection * d; + + // Guarantee that the ray will pass though the start block. + // It is possible that it would miss due to rounding + // This should only move the ray by 1 grid position + secondError = floor(secondd * gridSize); + secondStep = round(secondDirection / mainDirection * gridSize); + thirdError = floor(thirdd * gridSize); + thirdStep = round(thirdDirection / mainDirection * gridSize); + + if (secondError + secondStep <= 0) { + secondError = -secondStep + 1; + } + + if (thirdError + thirdStep <= 0) { + thirdError = -thirdStep + 1; + } + + Block lastBlock; + + lastBlock = startBlock.getRelative(mainFace.getOppositeFace()); + + if (secondError < 0) { + secondError += gridSize; + lastBlock = lastBlock.getRelative(secondFace.getOppositeFace()); + } + + if (thirdError < 0) { + thirdError += gridSize; + lastBlock = lastBlock.getRelative(thirdFace.getOppositeFace()); + } + + // This means that when the variables are positive, it means that the coord=1 boundary has been crossed + secondError -= gridSize; + thirdError -= gridSize; + + blockQueue[0] = lastBlock; + currentBlock = -1; + + scan(); + + boolean startBlockFound = false; + + for (int cnt = currentBlock; cnt >= 0; cnt--) { + if (blockEquals(blockQueue[cnt], startBlock)) { + currentBlock = cnt; + startBlockFound = true; + break; + } + } + + if (!startBlockFound) { + throw new IllegalStateException("Start block missed in BlockIterator"); + } + + // Calculate the number of planes passed to give max distance + maxDistanceInt = round(maxDistance / (Math.sqrt(mainDirection * mainDirection + secondDirection * secondDirection + thirdDirection * thirdDirection) / mainDirection)); + + } + + private boolean blockEquals(Block a, Block b) { + return a.getX() == b.getX() && a.getY() == b.getY() && a.getZ() == b.getZ(); + } + + private BlockFace getXFace(Vector direction) { + return ((direction.getX() > 0) ? BlockFace.EAST : BlockFace.WEST); + } + + private BlockFace getYFace(Vector direction) { + return ((direction.getY() > 0) ? BlockFace.UP : BlockFace.DOWN); + } + + private BlockFace getZFace(Vector direction) { + return ((direction.getZ() > 0) ? BlockFace.SOUTH : BlockFace.NORTH); + } + + private double getXLength(Vector direction) { + return Math.abs(direction.getX()); + } + + private double getYLength(Vector direction) { + return Math.abs(direction.getY()); + } + + private double getZLength(Vector direction) { + return Math.abs(direction.getZ()); + } + + private double getPosition(double direction, double position, int blockPosition) { + return direction > 0 ? (position - blockPosition) : (blockPosition + 1 - position); + } + + private double getXPosition(Vector direction, Vector position, Block block) { + return getPosition(direction.getX(), position.getX(), block.getX()); + } + + private double getYPosition(Vector direction, Vector position, Block block) { + return getPosition(direction.getY(), position.getY(), block.getY()); + } + + private double getZPosition(Vector direction, Vector position, Block block) { + return getPosition(direction.getZ(), position.getZ(), block.getZ()); + } + + /** + * Constructs the BlockIterator + * + * @param loc The location for the start of the ray trace + * @param yOffset The trace begins vertically offset from the start vector + * by this value + * @param maxDistance This is the maximum distance in blocks for the + * trace. Setting this value above 140 may lead to problems with + * unloaded chunks. A value of 0 indicates no limit + */ + public BlockIterator(Location loc, double yOffset, int maxDistance) { + this(loc.getWorld(), loc.toVector(), loc.getDirection(), yOffset, maxDistance); + } + + /** + * Constructs the BlockIterator. + * + * @param loc The location for the start of the ray trace + * @param yOffset The trace begins vertically offset from the start vector + * by this value + */ + + public BlockIterator(Location loc, double yOffset) { + this(loc.getWorld(), loc.toVector(), loc.getDirection(), yOffset, 0); + } + + /** + * Constructs the BlockIterator. + * + * @param loc The location for the start of the ray trace + */ + + public BlockIterator(Location loc) { + this(loc, 0D); + } + + /** + * Constructs the BlockIterator. + * + * @param entity Information from the entity is used to set up the trace + * @param maxDistance This is the maximum distance in blocks for the + * trace. Setting this value above 140 may lead to problems with + * unloaded chunks. A value of 0 indicates no limit + */ + + public BlockIterator(LivingEntity entity, int maxDistance) { + this(entity.getLocation(), entity.getEyeHeight(), maxDistance); + } + + /** + * Constructs the BlockIterator. + * + * @param entity Information from the entity is used to set up the trace + */ + + public BlockIterator(LivingEntity entity) { + this(entity, 0); + } + + /** + * Returns true if the iteration has more elements + */ + + public boolean hasNext() { + scan(); + return currentBlock != -1; + } + + /** + * Returns the next Block in the trace + * + * @return the next Block in the trace + */ + + public Block next() { + scan(); + if (currentBlock <= -1) { + throw new NoSuchElementException(); + } else { + return blockQueue[currentBlock--]; + } + } + + public void remove() { + throw new UnsupportedOperationException("[BlockIterator] doesn't support block removal"); + } + + private void scan() { + if (currentBlock >= 0) { + return; + } + if (maxDistance != 0 && currentDistance > maxDistanceInt) { + end = true; + return; + } + if (end) { + return; + } + + currentDistance++; + + secondError += secondStep; + thirdError += thirdStep; + + if (secondError > 0 && thirdError > 0) { + blockQueue[2] = blockQueue[0].getRelative(mainFace); + if (((long) secondStep) * ((long) thirdError) < ((long) thirdStep) * ((long) secondError)) { + blockQueue[1] = blockQueue[2].getRelative(secondFace); + blockQueue[0] = blockQueue[1].getRelative(thirdFace); + } else { + blockQueue[1] = blockQueue[2].getRelative(thirdFace); + blockQueue[0] = blockQueue[1].getRelative(secondFace); + } + thirdError -= gridSize; + secondError -= gridSize; + currentBlock = 2; + return; + } else if (secondError > 0) { + blockQueue[1] = blockQueue[0].getRelative(mainFace); + blockQueue[0] = blockQueue[1].getRelative(secondFace); + secondError -= gridSize; + currentBlock = 1; + return; + } else if (thirdError > 0) { + blockQueue[1] = blockQueue[0].getRelative(mainFace); + blockQueue[0] = blockQueue[1].getRelative(thirdFace); + thirdError -= gridSize; + currentBlock = 1; + return; + } else { + blockQueue[0] = blockQueue[0].getRelative(mainFace); + currentBlock = 0; + return; + } + } +} diff --git a/src/main/java/org/bukkit/util/BlockVector.java b/src/main/java/org/bukkit/util/BlockVector.java new file mode 100644 index 0000000..bdf8f6d --- /dev/null +++ b/src/main/java/org/bukkit/util/BlockVector.java @@ -0,0 +1,128 @@ +package org.bukkit.util; + +import java.util.Map; +import org.bukkit.configuration.serialization.SerializableAs; + +/** + * A vector with a hash function that floors the X, Y, Z components, a la + * BlockVector in WorldEdit. BlockVectors can be used in hash sets and + * hash maps. Be aware that BlockVectors are mutable, but it is important + * that BlockVectors are never changed once put into a hash set or hash map. + */ +@SerializableAs("BlockVector") +public class BlockVector extends Vector { + + /** + * Construct the vector with all components as 0. + */ + public BlockVector() { + this.x = 0; + this.y = 0; + this.z = 0; + } + + /** + * Construct the vector with another vector. + * + * @param vec The other vector. + */ + public BlockVector(Vector vec) { + this.x = vec.getX(); + this.y = vec.getY(); + this.z = vec.getZ(); + } + + /** + * Construct the vector with provided integer components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public BlockVector(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Construct the vector with provided double components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public BlockVector(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Construct the vector with provided float components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public BlockVector(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Checks if another object is equivalent. + * + * @param obj The other object + * @return whether the other object is equivalent + */ + @Override + public boolean equals(Object obj) { + if (!(obj instanceof BlockVector)) { + return false; + } + BlockVector other = (BlockVector) obj; + + return (int) other.getX() == (int) this.x && (int) other.getY() == (int) this.y && (int) other.getZ() == (int) this.z; + + } + + /** + * Returns a hash code for this vector. + * + * @return hash code + */ + @Override + public int hashCode() { + return (Integer.valueOf((int) x).hashCode() >> 13) ^ (Integer.valueOf((int) y).hashCode() >> 7) ^ Integer.valueOf((int) z).hashCode(); + } + + /** + * Get a new block vector. + * + * @return vector + */ + @Override + public BlockVector clone() { + return (BlockVector) super.clone(); + } + + public static BlockVector deserialize(Map args) { + double x = 0; + double y = 0; + double z = 0; + + if (args.containsKey("x")) { + x = (Double) args.get("x"); + } + if (args.containsKey("y")) { + y = (Double) args.get("y"); + } + if (args.containsKey("z")) { + z = (Double) args.get("z"); + } + + return new BlockVector(x, y, z); + } +} diff --git a/src/main/java/org/bukkit/util/CachedServerIcon.java b/src/main/java/org/bukkit/util/CachedServerIcon.java new file mode 100644 index 0000000..5ca863b --- /dev/null +++ b/src/main/java/org/bukkit/util/CachedServerIcon.java @@ -0,0 +1,15 @@ +package org.bukkit.util; + +import org.bukkit.Server; +import org.bukkit.event.server.ServerListPingEvent; + +/** + * This is a cached version of a server-icon. It's internal representation + * and implementation is undefined. + * + * @see Server#getServerIcon() + * @see Server#loadServerIcon(java.awt.image.BufferedImage) + * @see Server#loadServerIcon(java.io.File) + * @see ServerListPingEvent#setServerIcon(CachedServerIcon) + */ +public interface CachedServerIcon {} diff --git a/src/main/java/org/bukkit/util/ChatPaginator.java b/src/main/java/org/bukkit/util/ChatPaginator.java new file mode 100644 index 0000000..24802d1 --- /dev/null +++ b/src/main/java/org/bukkit/util/ChatPaginator.java @@ -0,0 +1,169 @@ +package org.bukkit.util; + +import org.bukkit.ChatColor; + +import java.util.LinkedList; +import java.util.List; + +/** + * The ChatPaginator takes a raw string of arbitrary length and breaks it down + * into an array of strings appropriate for displaying on the Minecraft player + * console. + */ +public class ChatPaginator { + public static final int GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH = 55; // Will never wrap, even with the largest characters + public static final int AVERAGE_CHAT_PAGE_WIDTH = 65; // Will typically not wrap using an average character distribution + public static final int UNBOUNDED_PAGE_WIDTH = Integer.MAX_VALUE; + public static final int OPEN_CHAT_PAGE_HEIGHT = 20; // The height of an expanded chat window + public static final int CLOSED_CHAT_PAGE_HEIGHT = 10; // The height of the default chat window + public static final int UNBOUNDED_PAGE_HEIGHT = Integer.MAX_VALUE; + + /** + * Breaks a raw string up into pages using the default width and height. + * + * @param unpaginatedString The raw string to break. + * @param pageNumber The page number to fetch. + * @return A single chat page. + */ + public static ChatPage paginate(String unpaginatedString, int pageNumber) { + return paginate(unpaginatedString, pageNumber, GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH, CLOSED_CHAT_PAGE_HEIGHT); + } + + /** + * Breaks a raw string up into pages using a provided width and height. + * + * @param unpaginatedString The raw string to break. + * @param pageNumber The page number to fetch. + * @param lineLength The desired width of a chat line. + * @param pageHeight The desired number of lines in a page. + * @return A single chat page. + */ + public static ChatPage paginate(String unpaginatedString, int pageNumber, int lineLength, int pageHeight) { + String[] lines = wordWrap(unpaginatedString, lineLength); + + int totalPages = lines.length / pageHeight + (lines.length % pageHeight == 0 ? 0 : 1); + int actualPageNumber = pageNumber <= totalPages ? pageNumber : totalPages; + + int from = (actualPageNumber - 1) * pageHeight; + int to = from + pageHeight <= lines.length ? from + pageHeight : lines.length; + String[] selectedLines = Java15Compat.Arrays_copyOfRange(lines, from, to); + + return new ChatPage(selectedLines, actualPageNumber, totalPages); + } + + /** + * Breaks a raw string up into a series of lines. Words are wrapped using + * spaces as decimeters and the newline character is respected. + * + * @param rawString The raw string to break. + * @param lineLength The length of a line of text. + * @return An array of word-wrapped lines. + */ + public static String[] wordWrap(String rawString, int lineLength) { + // A null string is a single line + if (rawString == null) { + return new String[] {""}; + } + + // A string shorter than the lineWidth is a single line + if (rawString.length() <= lineLength && !rawString.contains("\n")) { + return new String[] {rawString}; + } + + char[] rawChars = (rawString + ' ').toCharArray(); // add a trailing space to trigger pagination + StringBuilder word = new StringBuilder(); + StringBuilder line = new StringBuilder(); + List lines = new LinkedList(); + int lineColorChars = 0; + + for (int i = 0; i < rawChars.length; i++) { + char c = rawChars[i]; + + // skip chat color modifiers + if (c == ChatColor.COLOR_CHAR) { + word.append(ChatColor.getByChar(rawChars[i + 1])); + lineColorChars += 2; + i++; // Eat the next character as we have already processed it + continue; + } + + if (c == ' ' || c == '\n') { + if (line.length() == 0 && word.length() > lineLength) { // special case: extremely long word begins a line + for (String partialWord : word.toString().split("(?<=\\G.{" + lineLength + "})")) { + lines.add(partialWord); + } + } else if (line.length() + word.length() - lineColorChars == lineLength) { // Line exactly the correct length...newline + line.append(word); + lines.add(line.toString()); + line = new StringBuilder(); + lineColorChars = 0; + } else if (line.length() + 1 + word.length() - lineColorChars > lineLength) { // Line too long...break the line + for (String partialWord : word.toString().split("(?<=\\G.{" + lineLength + "})")) { + lines.add(line.toString()); + line = new StringBuilder(partialWord); + } + lineColorChars = 0; + } else { + if (line.length() > 0) { + line.append(' '); + } + line.append(word); + } + word = new StringBuilder(); + + if (c == '\n') { // Newline forces the line to flush + lines.add(line.toString()); + line = new StringBuilder(); + } + } else { + word.append(c); + } + } + + if(line.length() > 0) { // Only add the last line if there is anything to add + lines.add(line.toString()); + } + + // Iterate over the wrapped lines, applying the last color from one line to the beginning of the next + if (lines.get(0).length() == 0 || lines.get(0).charAt(0) != ChatColor.COLOR_CHAR) { + lines.set(0, ChatColor.WHITE + lines.get(0)); + } + for (int i = 1; i < lines.size(); i++) { + final String pLine = lines.get(i-1); + final String subLine = lines.get(i); + + char color = pLine.charAt(pLine.lastIndexOf(ChatColor.COLOR_CHAR) + 1); + if (subLine.length() == 0 || subLine.charAt(0) != ChatColor.COLOR_CHAR) { + lines.set(i, ChatColor.getByChar(color) + subLine); + } + } + + return lines.toArray(new String[lines.size()]); + } + + public static class ChatPage { + + private String[] lines; + private int pageNumber; + private int totalPages; + + public ChatPage(String[] lines, int pageNumber, int totalPages) { + this.lines = lines; + this.pageNumber = pageNumber; + this.totalPages = totalPages; + } + + public int getPageNumber() { + return pageNumber; + } + + public int getTotalPages() { + return totalPages; + } + + public String[] getLines() { + + return lines; + } + } +} diff --git a/src/main/java/org/bukkit/util/FileUtil.java b/src/main/java/org/bukkit/util/FileUtil.java new file mode 100644 index 0000000..7cabf4c --- /dev/null +++ b/src/main/java/org/bukkit/util/FileUtil.java @@ -0,0 +1,57 @@ +package org.bukkit.util; + +import java.nio.channels.FileChannel; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * Class containing file utilities + */ +public class FileUtil { + + /** + * This method copies one file to another location + * + * @param inFile the source filename + * @param outFile the target filename + * @return true on success + */ + public static boolean copy(File inFile, File outFile) { + if (!inFile.exists()) { + return false; + } + + FileChannel in = null; + FileChannel out = null; + + try { + in = new FileInputStream(inFile).getChannel(); + out = new FileOutputStream(outFile).getChannel(); + + long pos = 0; + long size = in.size(); + + while (pos < size) { + pos += in.transferTo(pos, 10 * 1024 * 1024, out); + } + } catch (IOException ioe) { + return false; + } finally { + try { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } catch (IOException ioe) { + return false; + } + } + + return true; + + } +} diff --git a/src/main/java/org/bukkit/util/Java15Compat.java b/src/main/java/org/bukkit/util/Java15Compat.java new file mode 100644 index 0000000..c119742 --- /dev/null +++ b/src/main/java/org/bukkit/util/Java15Compat.java @@ -0,0 +1,21 @@ +package org.bukkit.util; + +import java.lang.reflect.Array; + +public class Java15Compat { + @SuppressWarnings("unchecked") + public static T[] Arrays_copyOfRange(T[] original, int start, int end) { + if (original.length >= start && 0 <= start) { + if (start <= end) { + int length = end - start; + int copyLength = Math.min(length, original.length - start); + T[] copy = (T[]) Array.newInstance(original.getClass().getComponentType(), length); + + System.arraycopy(original, start, copy, 0, copyLength); + return copy; + } + throw new IllegalArgumentException(); + } + throw new ArrayIndexOutOfBoundsException(); + } +} diff --git a/src/main/java/org/bukkit/util/NumberConversions.java b/src/main/java/org/bukkit/util/NumberConversions.java new file mode 100644 index 0000000..29f81d0 --- /dev/null +++ b/src/main/java/org/bukkit/util/NumberConversions.java @@ -0,0 +1,104 @@ +package org.bukkit.util; + +/** + * Utils for casting number types to other number types + */ +public final class NumberConversions { + private NumberConversions() {} + + public static int floor(double num) { + final int floor = (int) num; + return floor == num ? floor : floor - (int) (Double.doubleToRawLongBits(num) >>> 63); + } + + public static int ceil(final double num) { + final int floor = (int) num; + return floor == num ? floor : floor + (int) (~Double.doubleToRawLongBits(num) >>> 63); + } + + public static int round(double num) { + return floor(num + 0.5d); + } + + public static double square(double num) { + return num * num; + } + + public static int toInt(Object object) { + if (object instanceof Number) { + return ((Number) object).intValue(); + } + + try { + return Integer.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static float toFloat(Object object) { + if (object instanceof Number) { + return ((Number) object).floatValue(); + } + + try { + return Float.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static double toDouble(Object object) { + if (object instanceof Number) { + return ((Number) object).doubleValue(); + } + + try { + return Double.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static long toLong(Object object) { + if (object instanceof Number) { + return ((Number) object).longValue(); + } + + try { + return Long.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static short toShort(Object object) { + if (object instanceof Number) { + return ((Number) object).shortValue(); + } + + try { + return Short.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } + + public static byte toByte(Object object) { + if (object instanceof Number) { + return ((Number) object).byteValue(); + } + + try { + return Byte.valueOf(object.toString()); + } catch (NumberFormatException e) { + } catch (NullPointerException e) { + } + return 0; + } +} diff --git a/src/main/java/org/bukkit/util/StringUtil.java b/src/main/java/org/bukkit/util/StringUtil.java new file mode 100644 index 0000000..4a8753f --- /dev/null +++ b/src/main/java/org/bukkit/util/StringUtil.java @@ -0,0 +1,57 @@ +package org.bukkit.util; + +import java.util.Collection; +import org.apache.commons.lang.Validate; + +public class StringUtil { + + /** + * Copies all elements from the iterable collection of originals to the + * collection provided. + * + * @param token String to search for + * @param originals An iterable collection of strings to filter. + * @param collection The collection to add matches to + * @return the collection provided that would have the elements copied + * into + * @throws UnsupportedOperationException if the collection is immutable + * and originals contains a string which starts with the specified + * search string. + * @throws IllegalArgumentException if any parameter is is null + * @throws IllegalArgumentException if originals contains a null element. + * Note: the collection may be modified before this is thrown + */ + public static > T copyPartialMatches(final String token, final Iterable originals, final T collection) throws UnsupportedOperationException, IllegalArgumentException { + Validate.notNull(token, "Search token cannot be null"); + Validate.notNull(collection, "Collection cannot be null"); + Validate.notNull(originals, "Originals cannot be null"); + + for (String string : originals) { + if (startsWithIgnoreCase(string, token)) { + collection.add(string); + } + } + + return collection; + } + + /** + * This method uses a region to check case-insensitive equality. This + * means the internal array does not need to be copied like a + * toLowerCase() call would. + * + * @param string String to check + * @param prefix Prefix of string to compare + * @return true if provided string starts with, ignoring case, the prefix + * provided + * @throws NullPointerException if prefix is null + * @throws IllegalArgumentException if string is null + */ + public static boolean startsWithIgnoreCase(final String string, final String prefix) throws IllegalArgumentException, NullPointerException { + Validate.notNull(string, "Cannot check a null string for a match"); + if (string.length() < prefix.length()) { + return false; + } + return string.regionMatches(true, 0, prefix, 0, prefix.length()); + } +} diff --git a/src/main/java/org/bukkit/util/Vector.java b/src/main/java/org/bukkit/util/Vector.java new file mode 100644 index 0000000..61116ea --- /dev/null +++ b/src/main/java/org/bukkit/util/Vector.java @@ -0,0 +1,667 @@ +package org.bukkit.util; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Random; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; + +/** + * Represents a mutable vector. Because the components of Vectors are mutable, + * storing Vectors long term may be dangerous if passing code modifies the + * Vector later. If you want to keep around a Vector, it may be wise to call + * clone() in order to get a copy. + */ +@SerializableAs("Vector") +public class Vector implements Cloneable, ConfigurationSerializable { + private static final long serialVersionUID = -2657651106777219169L; + + private static Random random = new Random(); + + /** + * Threshold for fuzzy equals(). + */ + private static final double epsilon = 0.000001; + + protected double x; + protected double y; + protected double z; + + /** + * Construct the vector with all components as 0. + */ + public Vector() { + this.x = 0; + this.y = 0; + this.z = 0; + } + + /** + * Construct the vector with provided integer components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public Vector(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Construct the vector with provided double components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public Vector(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Construct the vector with provided float components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public Vector(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Adds a vector to this one + * + * @param vec The other vector + * @return the same vector + */ + public Vector add(Vector vec) { + x += vec.x; + y += vec.y; + z += vec.z; + return this; + } + + /** + * Subtracts a vector from this one. + * + * @param vec The other vector + * @return the same vector + */ + public Vector subtract(Vector vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + return this; + } + + /** + * Multiplies the vector by another. + * + * @param vec The other vector + * @return the same vector + */ + public Vector multiply(Vector vec) { + x *= vec.x; + y *= vec.y; + z *= vec.z; + return this; + } + + /** + * Divides the vector by another. + * + * @param vec The other vector + * @return the same vector + */ + public Vector divide(Vector vec) { + x /= vec.x; + y /= vec.y; + z /= vec.z; + return this; + } + + /** + * Copies another vector + * + * @param vec The other vector + * @return the same vector + */ + public Vector copy(Vector vec) { + x = vec.x; + y = vec.y; + z = vec.z; + return this; + } + + /** + * Gets the magnitude of the vector, defined as sqrt(x^2+y^2+z^2). The + * value of this method is not cached and uses a costly square-root + * function, so do not repeatedly call this method to get the vector's + * magnitude. NaN will be returned if the inner result of the sqrt() + * function overflows, which will be caused if the length is too long. + * + * @return the magnitude + */ + public double length() { + return Math.sqrt(NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z)); + } + + /** + * Gets the magnitude of the vector squared. + * + * @return the magnitude + */ + public double lengthSquared() { + return NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z); + } + + /** + * Get the distance between this vector and another. The value of this + * method is not cached and uses a costly square-root function, so do not + * repeatedly call this method to get the vector's magnitude. NaN will be + * returned if the inner result of the sqrt() function overflows, which + * will be caused if the distance is too long. + * + * @param o The other vector + * @return the distance + */ + public double distance(Vector o) { + return Math.sqrt(NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z)); + } + + /** + * Get the squared distance between this vector and another. + * + * @param o The other vector + * @return the distance + */ + public double distanceSquared(Vector o) { + return NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z); + } + + /** + * Gets the angle between this vector and another in radians. + * + * @param other The other vector + * @return angle in radians + */ + public float angle(Vector other) { + double dot = dot(other) / (length() * other.length()); + + return (float) Math.acos(dot); + } + + /** + * Sets this vector to the midpoint between this vector and another. + * + * @param other The other vector + * @return this same vector (now a midpoint) + */ + public Vector midpoint(Vector other) { + x = (x + other.x) / 2; + y = (y + other.y) / 2; + z = (z + other.z) / 2; + return this; + } + + /** + * Gets a new midpoint vector between this vector and another. + * + * @param other The other vector + * @return a new midpoint vector + */ + public Vector getMidpoint(Vector other) { + double x = (this.x + other.x) / 2; + double y = (this.y + other.y) / 2; + double z = (this.z + other.z) / 2; + return new Vector(x, y, z); + } + + /** + * Performs scalar multiplication, multiplying all components with a + * scalar. + * + * @param m The factor + * @return the same vector + */ + public Vector multiply(int m) { + x *= m; + y *= m; + z *= m; + return this; + } + + /** + * Performs scalar multiplication, multiplying all components with a + * scalar. + * + * @param m The factor + * @return the same vector + */ + public Vector multiply(double m) { + x *= m; + y *= m; + z *= m; + return this; + } + + /** + * Performs scalar multiplication, multiplying all components with a + * scalar. + * + * @param m The factor + * @return the same vector + */ + public Vector multiply(float m) { + x *= m; + y *= m; + z *= m; + return this; + } + + /** + * Calculates the dot product of this vector with another. The dot product + * is defined as x1*x2+y1*y2+z1*z2. The returned value is a scalar. + * + * @param other The other vector + * @return dot product + */ + public double dot(Vector other) { + return x * other.x + y * other.y + z * other.z; + } + + /** + * Calculates the cross product of this vector with another. The cross + * product is defined as: + *

              + *
            • x = y1 * z2 - y2 * z1 + *
            • y = z1 * x2 - z2 * x1 + *
            • z = x1 * y2 - x2 * y1 + *
            + * + * @param o The other vector + * @return the same vector + */ + public Vector crossProduct(Vector o) { + double newX = y * o.z - o.y * z; + double newY = z * o.x - o.z * x; + double newZ = x * o.y - o.x * y; + + x = newX; + y = newY; + z = newZ; + return this; + } + + /** + * Converts this vector to a unit vector (a vector with length of 1). + * + * @return the same vector + */ + public Vector normalize() { + double length = length(); + + x /= length; + y /= length; + z /= length; + + return this; + } + + /** + * Zero this vector's components. + * + * @return the same vector + */ + public Vector zero() { + x = 0; + y = 0; + z = 0; + return this; + } + + /** + * Returns whether this vector is in an axis-aligned bounding box. + *

            + * The minimum and maximum vectors given must be truly the minimum and + * maximum X, Y and Z components. + * + * @param min Minimum vector + * @param max Maximum vector + * @return whether this vector is in the AABB + */ + public boolean isInAABB(Vector min, Vector max) { + return x >= min.x && x <= max.x && y >= min.y && y <= max.y && z >= min.z && z <= max.z; + } + + /** + * Returns whether this vector is within a sphere. + * + * @param origin Sphere origin. + * @param radius Sphere radius + * @return whether this vector is in the sphere + */ + public boolean isInSphere(Vector origin, double radius) { + return (NumberConversions.square(origin.x - x) + NumberConversions.square(origin.y - y) + NumberConversions.square(origin.z - z)) <= NumberConversions.square(radius); + } + + /** + * Gets the X component. + * + * @return The X component. + */ + public double getX() { + return x; + } + + /** + * Gets the floored value of the X component, indicating the block that + * this vector is contained with. + * + * @return block X + */ + public int getBlockX() { + return NumberConversions.floor(x); + } + + /** + * Gets the Y component. + * + * @return The Y component. + */ + public double getY() { + return y; + } + + /** + * Gets the floored value of the Y component, indicating the block that + * this vector is contained with. + * + * @return block y + */ + public int getBlockY() { + return NumberConversions.floor(y); + } + + /** + * Gets the Z component. + * + * @return The Z component. + */ + public double getZ() { + return z; + } + + /** + * Gets the floored value of the Z component, indicating the block that + * this vector is contained with. + * + * @return block z + */ + public int getBlockZ() { + return NumberConversions.floor(z); + } + + /** + * Set the X component. + * + * @param x The new X component. + * @return This vector. + */ + public Vector setX(int x) { + this.x = x; + return this; + } + + /** + * Set the X component. + * + * @param x The new X component. + * @return This vector. + */ + public Vector setX(double x) { + this.x = x; + return this; + } + + /** + * Set the X component. + * + * @param x The new X component. + * @return This vector. + */ + public Vector setX(float x) { + this.x = x; + return this; + } + + /** + * Set the Y component. + * + * @param y The new Y component. + * @return This vector. + */ + public Vector setY(int y) { + this.y = y; + return this; + } + + /** + * Set the Y component. + * + * @param y The new Y component. + * @return This vector. + */ + public Vector setY(double y) { + this.y = y; + return this; + } + + /** + * Set the Y component. + * + * @param y The new Y component. + * @return This vector. + */ + public Vector setY(float y) { + this.y = y; + return this; + } + + /** + * Set the Z component. + * + * @param z The new Z component. + * @return This vector. + */ + public Vector setZ(int z) { + this.z = z; + return this; + } + + /** + * Set the Z component. + * + * @param z The new Z component. + * @return This vector. + */ + public Vector setZ(double z) { + this.z = z; + return this; + } + + /** + * Set the Z component. + * + * @param z The new Z component. + * @return This vector. + */ + public Vector setZ(float z) { + this.z = z; + return this; + } + + /** + * Checks to see if two objects are equal. + *

            + * Only two Vectors can ever return true. This method uses a fuzzy match + * to account for floating point errors. The epsilon can be retrieved + * with epsilon. + */ + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Vector)) { + return false; + } + + Vector other = (Vector) obj; + + return Math.abs(x - other.x) < epsilon && Math.abs(y - other.y) < epsilon && Math.abs(z - other.z) < epsilon && (this.getClass().equals(obj.getClass())); + } + + /** + * Returns a hash code for this vector + * + * @return hash code + */ + @Override + public int hashCode() { + int hash = 7; + + hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32)); + hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32)); + hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32)); + return hash; + } + + /** + * Get a new vector. + * + * @return vector + */ + @Override + public Vector clone() { + try { + return (Vector) super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } + + /** + * Returns this vector's components as x,y,z. + */ + @Override + public String toString() { + return x + "," + y + "," + z; + } + + /** + * Gets a Location version of this vector with yaw and pitch being 0. + * + * @param world The world to link the location to. + * @return the location + */ + public Location toLocation(World world) { + return new Location(world, x, y, z); + } + + /** + * Gets a Location version of this vector. + * + * @param world The world to link the location to. + * @param yaw The desired yaw. + * @param pitch The desired pitch. + * @return the location + */ + public Location toLocation(World world, float yaw, float pitch) { + return new Location(world, x, y, z, yaw, pitch); + } + + /** + * Get the block vector of this vector. + * + * @return A block vector. + */ + public BlockVector toBlockVector() { + return new BlockVector(x, y, z); + } + + /** + * Get the threshold used for equals(). + * + * @return The epsilon. + */ + public static double getEpsilon() { + return epsilon; + } + + /** + * Gets the minimum components of two vectors. + * + * @param v1 The first vector. + * @param v2 The second vector. + * @return minimum + */ + public static Vector getMinimum(Vector v1, Vector v2) { + return new Vector(Math.min(v1.x, v2.x), Math.min(v1.y, v2.y), Math.min(v1.z, v2.z)); + } + + /** + * Gets the maximum components of two vectors. + * + * @param v1 The first vector. + * @param v2 The second vector. + * @return maximum + */ + public static Vector getMaximum(Vector v1, Vector v2) { + return new Vector(Math.max(v1.x, v2.x), Math.max(v1.y, v2.y), Math.max(v1.z, v2.z)); + } + + /** + * Gets a random vector with components having a random value between 0 + * and 1. + * + * @return A random vector. + */ + public static Vector getRandom() { + return new Vector(random.nextDouble(), random.nextDouble(), random.nextDouble()); + } + + public Map serialize() { + Map result = new LinkedHashMap(); + + result.put("x", getX()); + result.put("y", getY()); + result.put("z", getZ()); + + return result; + } + + public static Vector deserialize(Map args) { + double x = 0; + double y = 0; + double z = 0; + + if (args.containsKey("x")) { + x = (Double) args.get("x"); + } + if (args.containsKey("y")) { + y = (Double) args.get("y"); + } + if (args.containsKey("z")) { + z = (Double) args.get("z"); + } + + return new Vector(x, y, z); + } +} diff --git a/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java b/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java new file mode 100644 index 0000000..d4b2825 --- /dev/null +++ b/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java @@ -0,0 +1,63 @@ +package org.bukkit.util.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +/** + * This class is designed to be used in conjunction with the {@link + * ConfigurationSerializable} API. It translates objects back to their + * original implementation after being serialized by {@link + * BukkitObjectInputStream}. + *

            + * Behavior of implementations extending this class is not guaranteed across + * future versions. + */ +public class BukkitObjectInputStream extends ObjectInputStream { + + /** + * Constructor provided to mirror super functionality. + * + * @throws IOException + * @throws SecurityException + * @see ObjectInputStream#ObjectInputStream() + */ + protected BukkitObjectInputStream() throws IOException, SecurityException { + super(); + super.enableResolveObject(true); + } + + /** + * Object input stream decoration constructor. + * + * @param in + * @throws IOException + * @see ObjectInputStream#ObjectInputStream(InputStream) + */ + public BukkitObjectInputStream(InputStream in) throws IOException { + super(in); + super.enableResolveObject(true); + } + + @Override + protected Object resolveObject(Object obj) throws IOException { + if (obj instanceof Wrapper) { + try { + (obj = ConfigurationSerialization.deserializeObject(((Wrapper) obj).map)).getClass(); // NPE + } catch (Throwable ex) { + throw newIOException("Failed to deserialize object", ex); + } + } + + return super.resolveObject(obj); + } + + private static IOException newIOException(String string, Throwable cause) { + IOException exception = new IOException(string); + exception.initCause(cause); + return exception; + } +} diff --git a/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java b/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java new file mode 100644 index 0000000..c11e202 --- /dev/null +++ b/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java @@ -0,0 +1,53 @@ +package org.bukkit.util.io; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.io.Serializable; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +/** + * This class is designed to be used in conjunction with the {@link + * ConfigurationSerializable} API. It translates objects to an internal + * implementation for later deserialization using {@link + * BukkitObjectInputStream}. + *

            + * Behavior of implementations extending this class is not guaranteed across + * future versions. + */ +public class BukkitObjectOutputStream extends ObjectOutputStream { + + /** + * Constructor provided to mirror super functionality. + * + * @throws IOException + * @throws SecurityException + * @see ObjectOutputStream#ObjectOutputStream() + */ + protected BukkitObjectOutputStream() throws IOException, SecurityException { + super(); + super.enableReplaceObject(true); + } + + /** + * Object output stream decoration constructor. + * + * @param out + * @throws IOException + * @see ObjectOutputStream#ObjectOutputStream(OutputStream) + */ + public BukkitObjectOutputStream(OutputStream out) throws IOException { + super(out); + super.enableReplaceObject(true); + } + + @Override + protected Object replaceObject(Object obj) throws IOException { + if (!(obj instanceof Serializable) && (obj instanceof ConfigurationSerializable)) { + obj = Wrapper.newWrapper((ConfigurationSerializable) obj); + } + + return super.replaceObject(obj); + } +} diff --git a/src/main/java/org/bukkit/util/io/Wrapper.java b/src/main/java/org/bukkit/util/io/Wrapper.java new file mode 100644 index 0000000..e45605b --- /dev/null +++ b/src/main/java/org/bukkit/util/io/Wrapper.java @@ -0,0 +1,23 @@ +package org.bukkit.util.io; + +import java.io.Serializable; +import java.util.Map; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +import com.google.common.collect.ImmutableMap; + +class Wrapper & Serializable> implements Serializable { + private static final long serialVersionUID = -986209235411767547L; + + final T map; + + static Wrapper> newWrapper(ConfigurationSerializable obj) { + return new Wrapper>(ImmutableMap.builder().put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(obj.getClass())).putAll(obj.serialize()).build()); + } + + private Wrapper(T map) { + this.map = map; + } +} diff --git a/src/main/java/org/bukkit/util/noise/NoiseGenerator.java b/src/main/java/org/bukkit/util/noise/NoiseGenerator.java new file mode 100644 index 0000000..72c92f3 --- /dev/null +++ b/src/main/java/org/bukkit/util/noise/NoiseGenerator.java @@ -0,0 +1,176 @@ +package org.bukkit.util.noise; + +/** + * Base class for all noise generators + */ +public abstract class NoiseGenerator { + protected final int perm[] = new int[512]; + protected double offsetX; + protected double offsetY; + protected double offsetZ; + + /** + * Speedy floor, faster than (int)Math.floor(x) + * + * @param x Value to floor + * @return Floored value + */ + public static int floor(double x) { + return x >= 0 ? (int) x : (int) x - 1; + } + + protected static double fade(double x) { + return x * x * x * (x * (x * 6 - 15) + 10); + } + + protected static double lerp(double x, double y, double z) { + return y + x * (z - y); + } + + protected static double grad(int hash, double x, double y, double z) { + hash &= 15; + double u = hash < 8 ? x : y; + double v = hash < 4 ? y : hash == 12 || hash == 14 ? x : z; + return ((hash & 1) == 0 ? u : -u) + ((hash & 2) == 0 ? v : -v); + } + + /** + * Computes and returns the 1D noise for the given coordinate in 1D space + * + * @param x X coordinate + * @return Noise at given location, from range -1 to 1 + */ + public double noise(double x) { + return noise(x, 0, 0); + } + + /** + * Computes and returns the 2D noise for the given coordinates in 2D space + * + * @param x X coordinate + * @param y Y coordinate + * @return Noise at given location, from range -1 to 1 + */ + public double noise(double x, double y) { + return noise(x, y, 0); + } + + /** + * Computes and returns the 3D noise for the given coordinates in 3D space + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return Noise at given location, from range -1 to 1 + */ + public abstract double noise(double x, double y, double z); + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, int octaves, double frequency, double amplitude) { + return noise(x, 0, 0, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, int octaves, double frequency, double amplitude, boolean normalized) { + return noise(x, 0, 0, octaves, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, int octaves, double frequency, double amplitude) { + return noise(x, y, 0, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, int octaves, double frequency, double amplitude, boolean normalized) { + return noise(x, y, 0, octaves, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double z, int octaves, double frequency, double amplitude) { + return noise(x, y, z, octaves, frequency, amplitude, false); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double z, int octaves, double frequency, double amplitude, boolean normalized) { + double result = 0; + double amp = 1; + double freq = 1; + double max = 0; + + for (int i = 0; i < octaves; i++) { + result += noise(x * freq, y * freq, z * freq) * amp; + max += amp; + freq *= frequency; + amp *= amplitude; + } + + if (normalized) { + result /= max; + } + + return result; + } +} diff --git a/src/main/java/org/bukkit/util/noise/OctaveGenerator.java b/src/main/java/org/bukkit/util/noise/OctaveGenerator.java new file mode 100644 index 0000000..a87304b --- /dev/null +++ b/src/main/java/org/bukkit/util/noise/OctaveGenerator.java @@ -0,0 +1,199 @@ +package org.bukkit.util.noise; + +/** + * Creates noise using unbiased octaves + */ +public abstract class OctaveGenerator { + protected final NoiseGenerator[] octaves; + protected double xScale = 1; + protected double yScale = 1; + protected double zScale = 1; + + protected OctaveGenerator(NoiseGenerator[] octaves) { + this.octaves = octaves; + } + + /** + * Sets the scale used for all coordinates passed to this generator. + *

            + * This is the equivalent to setting each coordinate to the specified + * value. + * + * @param scale New value to scale each coordinate by + */ + public void setScale(double scale) { + setXScale(scale); + setYScale(scale); + setZScale(scale); + } + + /** + * Gets the scale used for each X-coordinates passed + * + * @return X scale + */ + public double getXScale() { + return xScale; + } + + /** + * Sets the scale used for each X-coordinates passed + * + * @param scale New X scale + */ + public void setXScale(double scale) { + xScale = scale; + } + + /** + * Gets the scale used for each Y-coordinates passed + * + * @return Y scale + */ + public double getYScale() { + return yScale; + } + + /** + * Sets the scale used for each Y-coordinates passed + * + * @param scale New Y scale + */ + public void setYScale(double scale) { + yScale = scale; + } + + /** + * Gets the scale used for each Z-coordinates passed + * + * @return Z scale + */ + public double getZScale() { + return zScale; + } + + /** + * Sets the scale used for each Z-coordinates passed + * + * @param scale New Z scale + */ + public void setZScale(double scale) { + zScale = scale; + } + + /** + * Gets a clone of the individual octaves used within this generator + * + * @return Clone of the individual octaves + */ + public NoiseGenerator[] getOctaves() { + return octaves.clone(); + } + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double frequency, double amplitude) { + return noise(x, 0, 0, frequency, amplitude); + } + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double frequency, double amplitude, boolean normalized) { + return noise(x, 0, 0, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double frequency, double amplitude) { + return noise(x, y, 0, frequency, amplitude); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double frequency, double amplitude, boolean normalized) { + return noise(x, y, 0, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double z, double frequency, double amplitude) { + return noise(x, y, z, frequency, amplitude, false); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double z, double frequency, double amplitude, boolean normalized) { + double result = 0; + double amp = 1; + double freq = 1; + double max = 0; + + x *= xScale; + y *= yScale; + z *= zScale; + + for (NoiseGenerator octave : octaves) { + result += octave.noise(x * freq, y * freq, z * freq) * amp; + max += amp; + freq *= frequency; + amp *= amplitude; + } + + if (normalized) { + result /= max; + } + + return result; + } +} diff --git a/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java b/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java new file mode 100644 index 0000000..5e034c1 --- /dev/null +++ b/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java @@ -0,0 +1,217 @@ +package org.bukkit.util.noise; + +import java.util.Random; +import org.bukkit.World; + +/** + * Generates noise using the "classic" perlin generator + * + * @see SimplexNoiseGenerator "Improved" and faster version with slighly + * different results + */ +public class PerlinNoiseGenerator extends NoiseGenerator { + protected static final int grad3[][] = {{1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, + {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, + {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1}}; + private static final PerlinNoiseGenerator instance = new PerlinNoiseGenerator(); + + protected PerlinNoiseGenerator() { + int p[] = {151, 160, 137, 91, 90, 15, 131, 13, 201, + 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, + 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, + 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, + 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, + 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, + 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, + 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, + 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, + 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, + 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, + 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, + 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, + 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, + 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, + 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, + 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, + 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}; + + for (int i = 0; i < 512; i++) { + perm[i] = p[i & 255]; + } + } + + /** + * Creates a seeded perlin noise generator for the given world + * + * @param world World to construct this generator for + */ + public PerlinNoiseGenerator(World world) { + this(new Random(world.getSeed())); + } + + /** + * Creates a seeded perlin noise generator for the given seed + * + * @param seed Seed to construct this generator for + */ + public PerlinNoiseGenerator(long seed) { + this(new Random(seed)); + } + + /** + * Creates a seeded perlin noise generator with the given Random + * + * @param rand Random to construct with + */ + public PerlinNoiseGenerator(Random rand) { + offsetX = rand.nextDouble() * 256; + offsetY = rand.nextDouble() * 256; + offsetZ = rand.nextDouble() * 256; + + for (int i = 0; i < 256; i++) { + perm[i] = rand.nextInt(256); + } + + for (int i = 0; i < 256; i++) { + int pos = rand.nextInt(256 - i) + i; + int old = perm[i]; + + perm[i] = perm[pos]; + perm[pos] = old; + perm[i + 256] = perm[i]; + } + } + + /** + * Computes and returns the 1D unseeded perlin noise for the given + * coordinates in 1D space + * + * @param x X coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x) { + return instance.noise(x); + } + + /** + * Computes and returns the 2D unseeded perlin noise for the given + * coordinates in 2D space + * + * @param x X coordinate + * @param y Y coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x, double y) { + return instance.noise(x, y); + } + + /** + * Computes and returns the 3D unseeded perlin noise for the given + * coordinates in 3D space + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x, double y, double z) { + return instance.noise(x, y, z); + } + + /** + * Gets the singleton unseeded instance of this generator + * + * @return Singleton + */ + public static PerlinNoiseGenerator getInstance() { + return instance; + } + + @Override + public double noise(double x, double y, double z) { + x += offsetX; + y += offsetY; + z += offsetZ; + + int floorX = floor(x); + int floorY = floor(y); + int floorZ = floor(z); + + // Find unit cube containing the point + int X = floorX & 255; + int Y = floorY & 255; + int Z = floorZ & 255; + + // Get relative xyz coordinates of the point within the cube + x -= floorX; + y -= floorY; + z -= floorZ; + + // Compute fade curves for xyz + double fX = fade(x); + double fY = fade(y); + double fZ = fade(z); + + // Hash coordinates of the cube corners + int A = perm[X] + Y; + int AA = perm[A] + Z; + int AB = perm[A + 1] + Z; + int B = perm[X + 1] + Y; + int BA = perm[B] + Z; + int BB = perm[B + 1] + Z; + + return lerp(fZ, lerp(fY, lerp(fX, grad(perm[AA], x, y, z), + grad(perm[BA], x - 1, y, z)), + lerp(fX, grad(perm[AB], x, y - 1, z), + grad(perm[BB], x - 1, y - 1, z))), + lerp(fY, lerp(fX, grad(perm[AA + 1], x, y, z - 1), + grad(perm[BA + 1], x - 1, y, z - 1)), + lerp(fX, grad(perm[AB + 1], x, y - 1, z - 1), + grad(perm[BB + 1], x - 1, y - 1, z - 1)))); + } + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, int octaves, double frequency, double amplitude) { + return instance.noise(x, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, double y, int octaves, double frequency, double amplitude) { + return instance.noise(x, y, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, double y, double z, int octaves, double frequency, double amplitude) { + return instance.noise(x, y, z, octaves, frequency, amplitude); + } +} diff --git a/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java b/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java new file mode 100644 index 0000000..55b7ad7 --- /dev/null +++ b/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java @@ -0,0 +1,50 @@ +package org.bukkit.util.noise; + +import java.util.Random; +import org.bukkit.World; + +/** + * Creates perlin noise through unbiased octaves + */ +public class PerlinOctaveGenerator extends OctaveGenerator { + + /** + * Creates a perlin octave generator for the given world + * + * @param world World to construct this generator for + * @param octaves Amount of octaves to create + */ + public PerlinOctaveGenerator(World world, int octaves) { + this(new Random(world.getSeed()), octaves); + } + + /** + * Creates a perlin octave generator for the given world + * + * @param seed Seed to construct this generator for + * @param octaves Amount of octaves to create + */ + public PerlinOctaveGenerator(long seed, int octaves) { + this(new Random(seed), octaves); + } + + /** + * Creates a perlin octave generator for the given {@link Random} + * + * @param rand Random object to construct this generator for + * @param octaves Amount of octaves to create + */ + public PerlinOctaveGenerator(Random rand, int octaves) { + super(createOctaves(rand, octaves)); + } + + private static NoiseGenerator[] createOctaves(Random rand, int octaves) { + NoiseGenerator[] result = new NoiseGenerator[octaves]; + + for (int i = 0; i < octaves; i++) { + result[i] = new PerlinNoiseGenerator(rand); + } + + return result; + } +} diff --git a/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java b/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java new file mode 100644 index 0000000..b052f3c --- /dev/null +++ b/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java @@ -0,0 +1,520 @@ +package org.bukkit.util.noise; + +import java.util.Random; +import org.bukkit.World; + +/** + * Generates simplex-based noise. + *

            + * This is a modified version of the freely published version in the paper by + * Stefan Gustavson at + * + * http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf + */ +public class SimplexNoiseGenerator extends PerlinNoiseGenerator { + protected static final double SQRT_3 = Math.sqrt(3); + protected static final double SQRT_5 = Math.sqrt(5); + protected static final double F2 = 0.5 * (SQRT_3 - 1); + protected static final double G2 = (3 - SQRT_3) / 6; + protected static final double G22 = G2 * 2.0 - 1; + protected static final double F3 = 1.0 / 3.0; + protected static final double G3 = 1.0 / 6.0; + protected static final double F4 = (SQRT_5 - 1.0) / 4.0; + protected static final double G4 = (5.0 - SQRT_5) / 20.0; + protected static final double G42 = G4 * 2.0; + protected static final double G43 = G4 * 3.0; + protected static final double G44 = G4 * 4.0 - 1.0; + protected static final int grad4[][] = {{0, 1, 1, 1}, {0, 1, 1, -1}, {0, 1, -1, 1}, {0, 1, -1, -1}, + {0, -1, 1, 1}, {0, -1, 1, -1}, {0, -1, -1, 1}, {0, -1, -1, -1}, + {1, 0, 1, 1}, {1, 0, 1, -1}, {1, 0, -1, 1}, {1, 0, -1, -1}, + {-1, 0, 1, 1}, {-1, 0, 1, -1}, {-1, 0, -1, 1}, {-1, 0, -1, -1}, + {1, 1, 0, 1}, {1, 1, 0, -1}, {1, -1, 0, 1}, {1, -1, 0, -1}, + {-1, 1, 0, 1}, {-1, 1, 0, -1}, {-1, -1, 0, 1}, {-1, -1, 0, -1}, + {1, 1, 1, 0}, {1, 1, -1, 0}, {1, -1, 1, 0}, {1, -1, -1, 0}, + {-1, 1, 1, 0}, {-1, 1, -1, 0}, {-1, -1, 1, 0}, {-1, -1, -1, 0}}; + protected static final int simplex[][] = { + {0, 1, 2, 3}, {0, 1, 3, 2}, {0, 0, 0, 0}, {0, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 2, 3, 0}, + {0, 2, 1, 3}, {0, 0, 0, 0}, {0, 3, 1, 2}, {0, 3, 2, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 3, 2, 0}, + {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, + {1, 2, 0, 3}, {0, 0, 0, 0}, {1, 3, 0, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 3, 0, 1}, {2, 3, 1, 0}, + {1, 0, 2, 3}, {1, 0, 3, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 0, 3, 1}, {0, 0, 0, 0}, {2, 1, 3, 0}, + {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, + {2, 0, 1, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 0, 1, 2}, {3, 0, 2, 1}, {0, 0, 0, 0}, {3, 1, 2, 0}, + {2, 1, 0, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 1, 0, 2}, {0, 0, 0, 0}, {3, 2, 0, 1}, {3, 2, 1, 0}}; + protected static double offsetW; + private static final SimplexNoiseGenerator instance = new SimplexNoiseGenerator(); + + protected SimplexNoiseGenerator() { + super(); + } + + /** + * Creates a seeded simplex noise generator for the given world + * + * @param world World to construct this generator for + */ + public SimplexNoiseGenerator(World world) { + this(new Random(world.getSeed())); + } + + /** + * Creates a seeded simplex noise generator for the given seed + * + * @param seed Seed to construct this generator for + */ + public SimplexNoiseGenerator(long seed) { + this(new Random(seed)); + } + + /** + * Creates a seeded simplex noise generator with the given Random + * + * @param rand Random to construct with + */ + public SimplexNoiseGenerator(Random rand) { + super(rand); + offsetW = rand.nextDouble() * 256; + } + + protected static double dot(int g[], double x, double y) { + return g[0] * x + g[1] * y; + } + + protected static double dot(int g[], double x, double y, double z) { + return g[0] * x + g[1] * y + g[2] * z; + } + + protected static double dot(int g[], double x, double y, double z, double w) { + return g[0] * x + g[1] * y + g[2] * z + g[3] * w; + } + + /** + * Computes and returns the 1D unseeded simplex noise for the given + * coordinates in 1D space + * + * @param xin X coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double xin) { + return instance.noise(xin); + } + + /** + * Computes and returns the 2D unseeded simplex noise for the given + * coordinates in 2D space + * + * @param xin X coordinate + * @param yin Y coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double xin, double yin) { + return instance.noise(xin, yin); + } + + /** + * Computes and returns the 3D unseeded simplex noise for the given + * coordinates in 3D space + * + * @param xin X coordinate + * @param yin Y coordinate + * @param zin Z coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double xin, double yin, double zin) { + return instance.noise(xin, yin, zin); + } + + /** + * Computes and returns the 4D simplex noise for the given coordinates in + * 4D space + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param w W coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x, double y, double z, double w) { + return instance.noise(x, y, z, w); + } + + @Override + public double noise(double xin, double yin, double zin) { + xin += offsetX; + yin += offsetY; + zin += offsetZ; + + double n0, n1, n2, n3; // Noise contributions from the four corners + + // Skew the input space to determine which simplex cell we're in + double s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D + int i = floor(xin + s); + int j = floor(yin + s); + int k = floor(zin + s); + double t = (i + j + k) * G3; + double X0 = i - t; // Unskew the cell origin back to (x,y,z) space + double Y0 = j - t; + double Z0 = k - t; + double x0 = xin - X0; // The x,y,z distances from the cell origin + double y0 = yin - Y0; + double z0 = zin - Z0; + + // For the 3D case, the simplex shape is a slightly irregular tetrahedron. + + // Determine which simplex we are in. + int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords + int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords + if (x0 >= y0) { + if (y0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; + } // X Y Z order + else if (x0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 0; + k2 = 1; + } // X Z Y order + else { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 1; + j2 = 0; + k2 = 1; + } // Z X Y order + } else { // x0 y0) { + i1 = 1; + j1 = 0; + } // lower triangle, XY order: (0,0)->(1,0)->(1,1) + else { + i1 = 0; + j1 = 1; + } // upper triangle, YX order: (0,0)->(0,1)->(1,1) + + // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and + // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where + // c = (3-sqrt(3))/6 + + double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + double y1 = y0 - j1 + G2; + double x2 = x0 + G22; // Offsets for last corner in (x,y) unskewed coords + double y2 = y0 + G22; + + // Work out the hashed gradient indices of the three simplex corners + int ii = i & 255; + int jj = j & 255; + int gi0 = perm[ii + perm[jj]] % 12; + int gi1 = perm[ii + i1 + perm[jj + j1]] % 12; + int gi2 = perm[ii + 1 + perm[jj + 1]] % 12; + + // Calculate the contribution from the three corners + double t0 = 0.5 - x0 * x0 - y0 * y0; + if (t0 < 0) { + n0 = 0.0; + } else { + t0 *= t0; + n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient + } + + double t1 = 0.5 - x1 * x1 - y1 * y1; + if (t1 < 0) { + n1 = 0.0; + } else { + t1 *= t1; + n1 = t1 * t1 * dot(grad3[gi1], x1, y1); + } + + double t2 = 0.5 - x2 * x2 - y2 * y2; + if (t2 < 0) { + n2 = 0.0; + } else { + t2 *= t2; + n2 = t2 * t2 * dot(grad3[gi2], x2, y2); + } + + // Add contributions from each corner to get the final noise value. + // The result is scaled to return values in the interval [-1,1]. + return 70.0 * (n0 + n1 + n2); + } + + /** + * Computes and returns the 4D simplex noise for the given coordinates in + * 4D space + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param w W coordinate + * @return Noise at given location, from range -1 to 1 + */ + public double noise(double x, double y, double z, double w) { + x += offsetX; + y += offsetY; + z += offsetZ; + w += offsetW; + + double n0, n1, n2, n3, n4; // Noise contributions from the five corners + + // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in + double s = (x + y + z + w) * F4; // Factor for 4D skewing + int i = floor(x + s); + int j = floor(y + s); + int k = floor(z + s); + int l = floor(w + s); + + double t = (i + j + k + l) * G4; // Factor for 4D unskewing + double X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space + double Y0 = j - t; + double Z0 = k - t; + double W0 = l - t; + double x0 = x - X0; // The x,y,z,w distances from the cell origin + double y0 = y - Y0; + double z0 = z - Z0; + double w0 = w - W0; + + // For the 4D case, the simplex is a 4D shape I won't even try to describe. + // To find out which of the 24 possible simplices we're in, we need to + // determine the magnitude ordering of x0, y0, z0 and w0. + // The method below is a good way of finding the ordering of x,y,z,w and + // then find the correct traversal order for the simplex we’re in. + // First, six pair-wise comparisons are performed between each possible pair + // of the four coordinates, and the results are used to add up binary bits + // for an integer index. + int c1 = (x0 > y0) ? 32 : 0; + int c2 = (x0 > z0) ? 16 : 0; + int c3 = (y0 > z0) ? 8 : 0; + int c4 = (x0 > w0) ? 4 : 0; + int c5 = (y0 > w0) ? 2 : 0; + int c6 = (z0 > w0) ? 1 : 0; + int c = c1 + c2 + c3 + c4 + c5 + c6; + int i1, j1, k1, l1; // The integer offsets for the second simplex corner + int i2, j2, k2, l2; // The integer offsets for the third simplex corner + int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner + + // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. + // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0; + j1 = simplex[c][1] >= 3 ? 1 : 0; + k1 = simplex[c][2] >= 3 ? 1 : 0; + l1 = simplex[c][3] >= 3 ? 1 : 0; + + // The number 2 in the "simplex" array is at the second largest coordinate. + i2 = simplex[c][0] >= 2 ? 1 : 0; + j2 = simplex[c][1] >= 2 ? 1 : 0; + k2 = simplex[c][2] >= 2 ? 1 : 0; + l2 = simplex[c][3] >= 2 ? 1 : 0; + + // The number 1 in the "simplex" array is at the second smallest coordinate. + i3 = simplex[c][0] >= 1 ? 1 : 0; + j3 = simplex[c][1] >= 1 ? 1 : 0; + k3 = simplex[c][2] >= 1 ? 1 : 0; + l3 = simplex[c][3] >= 1 ? 1 : 0; + + // The fifth corner has all coordinate offsets = 1, so no need to look that up. + + double x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords + double y1 = y0 - j1 + G4; + double z1 = z0 - k1 + G4; + double w1 = w0 - l1 + G4; + + double x2 = x0 - i2 + G42; // Offsets for third corner in (x,y,z,w) coords + double y2 = y0 - j2 + G42; + double z2 = z0 - k2 + G42; + double w2 = w0 - l2 + G42; + + double x3 = x0 - i3 + G43; // Offsets for fourth corner in (x,y,z,w) coords + double y3 = y0 - j3 + G43; + double z3 = z0 - k3 + G43; + double w3 = w0 - l3 + G43; + + double x4 = x0 + G44; // Offsets for last corner in (x,y,z,w) coords + double y4 = y0 + G44; + double z4 = z0 + G44; + double w4 = w0 + G44; + + // Work out the hashed gradient indices of the five simplex corners + int ii = i & 255; + int jj = j & 255; + int kk = k & 255; + int ll = l & 255; + + int gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; + int gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; + int gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; + int gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; + int gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; + + // Calculate the contribution from the five corners + double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; + if (t0 < 0) { + n0 = 0.0; + } else { + t0 *= t0; + n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0); + } + + double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t1 < 0) { + n1 = 0.0; + } else { + t1 *= t1; + n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1); + } + + double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; + if (t2 < 0) { + n2 = 0.0; + } else { + t2 *= t2; + n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2); + } + + double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; + if (t3 < 0) { + n3 = 0.0; + } else { + t3 *= t3; + n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3); + } + + double t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t4 < 0) { + n4 = 0.0; + } else { + t4 *= t4; + n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4); + } + + // Sum up and scale the result to cover the range [-1,1] + return 27.0 * (n0 + n1 + n2 + n3 + n4); + } + + /** + * Gets the singleton unseeded instance of this generator + * + * @return Singleton + */ + public static SimplexNoiseGenerator getInstance() { + return instance; + } +} diff --git a/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java b/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java new file mode 100644 index 0000000..61e66aa --- /dev/null +++ b/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java @@ -0,0 +1,129 @@ +package org.bukkit.util.noise; + +import java.util.Random; +import org.bukkit.World; + +/** + * Creates simplex noise through unbiased octaves + */ +public class SimplexOctaveGenerator extends OctaveGenerator { + private double wScale = 1; + + /** + * Creates a simplex octave generator for the given world + * + * @param world World to construct this generator for + * @param octaves Amount of octaves to create + */ + public SimplexOctaveGenerator(World world, int octaves) { + this(new Random(world.getSeed()), octaves); + } + + /** + * Creates a simplex octave generator for the given world + * + * @param seed Seed to construct this generator for + * @param octaves Amount of octaves to create + */ + public SimplexOctaveGenerator(long seed, int octaves) { + this(new Random(seed), octaves); + } + + /** + * Creates a simplex octave generator for the given {@link Random} + * + * @param rand Random object to construct this generator for + * @param octaves Amount of octaves to create + */ + public SimplexOctaveGenerator(Random rand, int octaves) { + super(createOctaves(rand, octaves)); + } + + @Override + public void setScale(double scale) { + super.setScale(scale); + setWScale(scale); + } + + /** + * Gets the scale used for each W-coordinates passed + * + * @return W scale + */ + public double getWScale() { + return wScale; + } + + /** + * Sets the scale used for each W-coordinates passed + * + * @param scale New W scale + */ + public void setWScale(double scale) { + wScale = scale; + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param w W-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double z, double w, double frequency, double amplitude) { + return noise(x, y, z, w, frequency, amplitude, false); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param w W-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double z, double w, double frequency, double amplitude, boolean normalized) { + double result = 0; + double amp = 1; + double freq = 1; + double max = 0; + + x *= xScale; + y *= yScale; + z *= zScale; + w *= wScale; + + for (NoiseGenerator octave : octaves) { + result += ((SimplexNoiseGenerator) octave).noise(x * freq, y * freq, z * freq, w * freq) * amp; + max += amp; + freq *= frequency; + amp *= amplitude; + } + + if (normalized) { + result /= max; + } + + return result; + } + + private static NoiseGenerator[] createOctaves(Random rand, int octaves) { + NoiseGenerator[] result = new NoiseGenerator[octaves]; + + for (int i = 0; i < octaves; i++) { + result[i] = new SimplexNoiseGenerator(rand); + } + + return result; + } +} diff --git a/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java b/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java new file mode 100644 index 0000000..092370e --- /dev/null +++ b/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java @@ -0,0 +1,22 @@ +package org.bukkit.util.permissions; + +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + +public final class BroadcastPermissions { + private static final String ROOT = "bukkit.broadcast"; + private static final String PREFIX = ROOT + "."; + + private BroadcastPermissions() {} + + public static Permission registerPermissions(Permission parent) { + Permission broadcasts = DefaultPermissions.registerPermission(ROOT, "Allows the user to receive all broadcast messages", parent); + + DefaultPermissions.registerPermission(PREFIX + "admin", "Allows the user to receive administrative broadcasts", PermissionDefault.OP, broadcasts); + DefaultPermissions.registerPermission(PREFIX + "user", "Allows the user to receive user broadcasts", PermissionDefault.TRUE, broadcasts); + + broadcasts.recalculatePermissibles(); + + return broadcasts; + } +} diff --git a/src/main/java/org/bukkit/util/permissions/CommandPermissions.java b/src/main/java/org/bukkit/util/permissions/CommandPermissions.java new file mode 100644 index 0000000..4638c91 --- /dev/null +++ b/src/main/java/org/bukkit/util/permissions/CommandPermissions.java @@ -0,0 +1,117 @@ +package org.bukkit.util.permissions; + +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + +public final class CommandPermissions { + private static final String ROOT = "bukkit.command"; + private static final String PREFIX = ROOT + "."; + + private CommandPermissions() {} + + private static Permission registerWhitelist(Permission parent) { + Permission whitelist = DefaultPermissions.registerPermission(PREFIX + "whitelist", "Allows the user to modify the server whitelist", PermissionDefault.OP, parent); + + DefaultPermissions.registerPermission(PREFIX + "whitelist.add", "Allows the user to add a player to the server whitelist", whitelist); + DefaultPermissions.registerPermission(PREFIX + "whitelist.remove", "Allows the user to remove a player from the server whitelist", whitelist); + DefaultPermissions.registerPermission(PREFIX + "whitelist.reload", "Allows the user to reload the server whitelist", whitelist); + DefaultPermissions.registerPermission(PREFIX + "whitelist.enable", "Allows the user to enable the server whitelist", whitelist); + DefaultPermissions.registerPermission(PREFIX + "whitelist.disable", "Allows the user to disable the server whitelist", whitelist); + DefaultPermissions.registerPermission(PREFIX + "whitelist.list", "Allows the user to list all the users on the server whitelist", whitelist); + + whitelist.recalculatePermissibles(); + + return whitelist; + } + + private static Permission registerBan(Permission parent) { + Permission ban = DefaultPermissions.registerPermission(PREFIX + "ban", "Allows the user to ban people", PermissionDefault.OP, parent); + + DefaultPermissions.registerPermission(PREFIX + "ban.player", "Allows the user to ban players", ban); + DefaultPermissions.registerPermission(PREFIX + "ban.ip", "Allows the user to ban IP addresses", ban); + + ban.recalculatePermissibles(); + + return ban; + } + + private static Permission registerUnban(Permission parent) { + Permission unban = DefaultPermissions.registerPermission(PREFIX + "unban", "Allows the user to unban people", PermissionDefault.OP, parent); + + DefaultPermissions.registerPermission(PREFIX + "unban.player", "Allows the user to unban players", unban); + DefaultPermissions.registerPermission(PREFIX + "unban.ip", "Allows the user to unban IP addresses", unban); + + unban.recalculatePermissibles(); + + return unban; + } + + private static Permission registerOp(Permission parent) { + Permission op = DefaultPermissions.registerPermission(PREFIX + "op", "Allows the user to change operators", PermissionDefault.OP, parent); + + DefaultPermissions.registerPermission(PREFIX + "op.give", "Allows the user to give a player operator status", op); + DefaultPermissions.registerPermission(PREFIX + "op.take", "Allows the user to take a players operator status", op); + + op.recalculatePermissibles(); + + return op; + } + + private static Permission registerSave(Permission parent) { + Permission save = DefaultPermissions.registerPermission(PREFIX + "save", "Allows the user to save the worlds", PermissionDefault.OP, parent); + + DefaultPermissions.registerPermission(PREFIX + "save.enable", "Allows the user to enable automatic saving", save); + DefaultPermissions.registerPermission(PREFIX + "save.disable", "Allows the user to disable automatic saving", save); + DefaultPermissions.registerPermission(PREFIX + "save.perform", "Allows the user to perform a manual save", save); + + save.recalculatePermissibles(); + + return save; + } + + private static Permission registerTime(Permission parent) { + Permission time = DefaultPermissions.registerPermission(PREFIX + "time", "Allows the user to alter the time", PermissionDefault.OP, parent); + + DefaultPermissions.registerPermission(PREFIX + "time.add", "Allows the user to fast-forward time", time); + DefaultPermissions.registerPermission(PREFIX + "time.set", "Allows the user to change the time", time); + + time.recalculatePermissibles(); + + return time; + } + + public static Permission registerPermissions(Permission parent) { + Permission commands = DefaultPermissions.registerPermission(ROOT, "Gives the user the ability to use all CraftBukkit commands", parent); + + registerWhitelist(commands); + registerBan(commands); + registerUnban(commands); + registerOp(commands); + registerSave(commands); + registerTime(commands); + + DefaultPermissions.registerPermission(PREFIX + "kill", "Allows the user to commit suicide", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "me", "Allows the user to perform a chat action", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "tell", "Allows the user to privately message another player", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "say", "Allows the user to talk as the console", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "give", "Allows the user to give items to players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "teleport", "Allows the user to teleport players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "kick", "Allows the user to kick players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "stop", "Allows the user to stop the server", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "list", "Allows the user to list all online players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "help", "Allows the user to view the vanilla help menu", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "plugins", "Allows the user to view the list of plugins running on this server", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "reload", "Allows the user to reload the server settings", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "version", "Allows the user to view the version of the server", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "gamemode", "Allows the user to change the gamemode of another player", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "xp", "Allows the user to give themselves or others arbitrary values of experience", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "toggledownfall", "Allows the user to toggle rain on/off for a given world", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "defaultgamemode", "Allows the user to change the default gamemode of the server", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "seed", "Allows the user to view the seed of the world", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "effect", "Allows the user to add/remove effects on players", PermissionDefault.OP, commands); + + commands.recalculatePermissibles(); + + return commands; + } +} diff --git a/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java b/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java new file mode 100644 index 0000000..8c0df8e --- /dev/null +++ b/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java @@ -0,0 +1,82 @@ +package org.bukkit.util.permissions; + +import java.util.Map; +import org.bukkit.Bukkit; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + +public final class DefaultPermissions { + private static final String ROOT = "craftbukkit"; + private static final String LEGACY_PREFIX = "craft"; + + private DefaultPermissions() {} + + public static Permission registerPermission(Permission perm) { + return registerPermission(perm, true); + } + + public static Permission registerPermission(Permission perm, boolean withLegacy) { + Permission result = perm; + + try { + Bukkit.getPluginManager().addPermission(perm); + } catch (IllegalArgumentException ex) { + result = Bukkit.getPluginManager().getPermission(perm.getName()); + } + + if (withLegacy) { + Permission legacy = new Permission(LEGACY_PREFIX + result.getName(), result.getDescription(), PermissionDefault.FALSE); + legacy.getChildren().put(result.getName(), true); + registerPermission(perm, false); + } + + return result; + } + + public static Permission registerPermission(Permission perm, Permission parent) { + parent.getChildren().put(perm.getName(), true); + return registerPermission(perm); + } + + public static Permission registerPermission(String name, String desc) { + Permission perm = registerPermission(new Permission(name, desc)); + return perm; + } + + public static Permission registerPermission(String name, String desc, Permission parent) { + Permission perm = registerPermission(name, desc); + parent.getChildren().put(perm.getName(), true); + return perm; + } + + public static Permission registerPermission(String name, String desc, PermissionDefault def) { + Permission perm = registerPermission(new Permission(name, desc, def)); + return perm; + } + + public static Permission registerPermission(String name, String desc, PermissionDefault def, Permission parent) { + Permission perm = registerPermission(name, desc, def); + parent.getChildren().put(perm.getName(), true); + return perm; + } + + public static Permission registerPermission(String name, String desc, PermissionDefault def, Map children) { + Permission perm = registerPermission(new Permission(name, desc, def, children)); + return perm; + } + + public static Permission registerPermission(String name, String desc, PermissionDefault def, Map children, Permission parent) { + Permission perm = registerPermission(name, desc, def, children); + parent.getChildren().put(perm.getName(), true); + return perm; + } + + public static void registerCorePermissions() { + Permission parent = registerPermission(ROOT, "Gives the user the ability to use all CraftBukkit utilities and commands"); + + CommandPermissions.registerPermissions(parent); + BroadcastPermissions.registerPermissions(parent); + + parent.recalculatePermissibles(); + } +} diff --git a/src/main/javadoc/org/bukkit/block/package-info.java b/src/main/javadoc/org/bukkit/block/package-info.java new file mode 100644 index 0000000..fb7719b --- /dev/null +++ b/src/main/javadoc/org/bukkit/block/package-info.java @@ -0,0 +1,7 @@ +/** + * Classes used to manipulate the voxels in a {@link org.bukkit.World world}, + * including special states. + *

            + */ +package org.bukkit.block; + diff --git a/src/main/javadoc/org/bukkit/command/defaults/package-info.java b/src/main/javadoc/org/bukkit/command/defaults/package-info.java new file mode 100644 index 0000000..f296730 --- /dev/null +++ b/src/main/javadoc/org/bukkit/command/defaults/package-info.java @@ -0,0 +1,7 @@ +/** + * Commands for emulating the Minecraft commands and other necessary ones for + * use by a Bukkit implementation. + *

            + */ +package org.bukkit.command.defaults; + diff --git a/src/main/javadoc/org/bukkit/command/package-info.java b/src/main/javadoc/org/bukkit/command/package-info.java new file mode 100644 index 0000000..f06407a --- /dev/null +++ b/src/main/javadoc/org/bukkit/command/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes relating to handling specialized non-chat player input. + *

            + */ +package org.bukkit.command; + diff --git a/src/main/javadoc/org/bukkit/configuration/file/package-info.java b/src/main/javadoc/org/bukkit/configuration/file/package-info.java new file mode 100644 index 0000000..9b1161b --- /dev/null +++ b/src/main/javadoc/org/bukkit/configuration/file/package-info.java @@ -0,0 +1,8 @@ +/** + * Classes dedicated facilitating {@link + * org.bukkit.configuration.Configuration configurations} to be read and + * stored on the filesystem. + *

            + */ +package org.bukkit.configuration.file; + diff --git a/src/main/javadoc/org/bukkit/configuration/package-info.java b/src/main/javadoc/org/bukkit/configuration/package-info.java new file mode 100644 index 0000000..fc439db --- /dev/null +++ b/src/main/javadoc/org/bukkit/configuration/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes dedicated to handling a plugin's runtime configuration. + *

            + */ +package org.bukkit.configuration; + diff --git a/src/main/javadoc/org/bukkit/configuration/serialization/package-info.java b/src/main/javadoc/org/bukkit/configuration/serialization/package-info.java new file mode 100644 index 0000000..b33306f --- /dev/null +++ b/src/main/javadoc/org/bukkit/configuration/serialization/package-info.java @@ -0,0 +1,8 @@ +/** + * Classes dedicated to being able to perform serialization specialized for + * the Bukkit {@link org.bukkit.configuration.Configuration configuration} + * implementation. + *

            + */ +package org.bukkit.configuration.serialization; + diff --git a/src/main/javadoc/org/bukkit/conversations/package-info.java b/src/main/javadoc/org/bukkit/conversations/package-info.java new file mode 100644 index 0000000..2259e92 --- /dev/null +++ b/src/main/javadoc/org/bukkit/conversations/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes dedicated to facilitate direct player-to-plugin communication. + *

            + */ +package org.bukkit.conversations; + diff --git a/src/main/javadoc/org/bukkit/enchantments/package-info.java b/src/main/javadoc/org/bukkit/enchantments/package-info.java new file mode 100644 index 0000000..a686c82 --- /dev/null +++ b/src/main/javadoc/org/bukkit/enchantments/package-info.java @@ -0,0 +1,8 @@ +/** + * Classes relating to the specialized enhancements to {@link + * org.bukkit.inventory.ItemStack item stacks}, as part of the {@link + * org.bukkit.inventory.meta.ItemMeta meta data}. + *

            + */ +package org.bukkit.enchantments; + diff --git a/src/main/javadoc/org/bukkit/entity/minecart/package-info.java b/src/main/javadoc/org/bukkit/entity/minecart/package-info.java new file mode 100644 index 0000000..9988caa --- /dev/null +++ b/src/main/javadoc/org/bukkit/entity/minecart/package-info.java @@ -0,0 +1,6 @@ +/** + * Interfaces for various {@link org.bukkit.entity.Minecart} types. + *

            + */ +package org.bukkit.entity.minecart; + diff --git a/src/main/javadoc/org/bukkit/entity/package-info.java b/src/main/javadoc/org/bukkit/entity/package-info.java new file mode 100644 index 0000000..581209b --- /dev/null +++ b/src/main/javadoc/org/bukkit/entity/package-info.java @@ -0,0 +1,7 @@ +/** + * Interfaces for non-voxel objects that can exist in a {@link + * org.bukkit.World world}, including all players, monsters, projectiles, etc. + *

            + */ +package org.bukkit.entity; + diff --git a/src/main/javadoc/org/bukkit/event/block/package-info.java b/src/main/javadoc/org/bukkit/event/block/package-info.java new file mode 100644 index 0000000..dd53485 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/block/package-info.java @@ -0,0 +1,8 @@ +/** + * {@link org.bukkit.event.Event Events} relating to when a {@link + * org.bukkit.block.Block block} is changed or interacts with the {@link + * org.bukkit.World world}. + *

            + */ +package org.bukkit.event.block; + diff --git a/src/main/javadoc/org/bukkit/event/enchantment/package-info.java b/src/main/javadoc/org/bukkit/event/enchantment/package-info.java new file mode 100644 index 0000000..7be6f83 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/enchantment/package-info.java @@ -0,0 +1,7 @@ +/** + * {@link org.bukkit.event.Event Events} triggered from an {@link + * org.bukkit.inventory.EnchantingInventory enchantment table}. + *

            + */ +package org.bukkit.event.enchantment; + diff --git a/src/main/javadoc/org/bukkit/event/entity/package-info.java b/src/main/javadoc/org/bukkit/event/entity/package-info.java new file mode 100644 index 0000000..36a1a09 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/entity/package-info.java @@ -0,0 +1,8 @@ +/** + * {@link org.bukkit.event.Event Events} relating to {@link + * org.bukkit.entity.Entity entities}, excluding some directly referencing + * some more specific entity types. + *

            + */ +package org.bukkit.event.entity; + diff --git a/src/main/javadoc/org/bukkit/event/hanging/package-info.java b/src/main/javadoc/org/bukkit/event/hanging/package-info.java new file mode 100644 index 0000000..63e9e7e --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/hanging/package-info.java @@ -0,0 +1,7 @@ +/** + * {@link org.bukkit.event.Event Events} relating to {@link + * org.bukkit.entity.Hanging entities that hang}. + *

            + */ +package org.bukkit.event.hanging; + diff --git a/src/main/javadoc/org/bukkit/event/inventory/package-info.java b/src/main/javadoc/org/bukkit/event/inventory/package-info.java new file mode 100644 index 0000000..7cb5a63 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/inventory/package-info.java @@ -0,0 +1,7 @@ +/** + * {@link org.bukkit.event.Event Events} relating to {@link + * org.bukkit.inventory.Inventory inventory} manipulation. + *

            + */ +package org.bukkit.event.inventory; + diff --git a/src/main/javadoc/org/bukkit/event/package-info.java b/src/main/javadoc/org/bukkit/event/package-info.java new file mode 100644 index 0000000..ab3011a --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes dedicated to handling triggered code executions. + *

            + */ +package org.bukkit.event; + diff --git a/src/main/javadoc/org/bukkit/event/painting/package-info.java b/src/main/javadoc/org/bukkit/event/painting/package-info.java new file mode 100644 index 0000000..39a8bb7 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/painting/package-info.java @@ -0,0 +1,8 @@ +/** + * {@link org.bukkit.event.Event Events} relating to {@link + * org.bukkit.entity.Painting paintings}, but deprecated for more general + * {@link org.bukkit.event.hanging hanging} events. + *

            + */ +package org.bukkit.event.painting; + diff --git a/src/main/javadoc/org/bukkit/event/player/package-info.java b/src/main/javadoc/org/bukkit/event/player/package-info.java new file mode 100644 index 0000000..c5a4954 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/player/package-info.java @@ -0,0 +1,7 @@ +/** + * {@link org.bukkit.event.Event Events} relating to {@link + * org.bukkit.entity.Player players}. + *

            + */ +package org.bukkit.event.player; + diff --git a/src/main/javadoc/org/bukkit/event/server/package-info.java b/src/main/javadoc/org/bukkit/event/server/package-info.java new file mode 100644 index 0000000..a2e1699 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/server/package-info.java @@ -0,0 +1,7 @@ +/** + * {@link org.bukkit.event.Event Events} relating to programmatic state + * changes on the server. + *

            + */ +package org.bukkit.event.server; + diff --git a/src/main/javadoc/org/bukkit/event/vehicle/package-info.java b/src/main/javadoc/org/bukkit/event/vehicle/package-info.java new file mode 100644 index 0000000..07c470a --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/vehicle/package-info.java @@ -0,0 +1,7 @@ +/** + * {@link org.bukkit.event.Event Events} relating to {@link + * org.bukkit.entity.Vehicle vehicular entities}. + *

            + */ +package org.bukkit.event.vehicle; + diff --git a/src/main/javadoc/org/bukkit/event/weather/package-info.java b/src/main/javadoc/org/bukkit/event/weather/package-info.java new file mode 100644 index 0000000..f2e3f49 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/weather/package-info.java @@ -0,0 +1,6 @@ +/** + * {@link org.bukkit.event.Event Events} relating to weather. + *

            + */ +package org.bukkit.event.weather; + diff --git a/src/main/javadoc/org/bukkit/event/world/package-info.java b/src/main/javadoc/org/bukkit/event/world/package-info.java new file mode 100644 index 0000000..3b075f6 --- /dev/null +++ b/src/main/javadoc/org/bukkit/event/world/package-info.java @@ -0,0 +1,7 @@ +/** + * {@link org.bukkit.event.Event Events} triggered by various {@link + * org.bukkit.World world} states or changes. + *

            + */ +package org.bukkit.event.world; + diff --git a/src/main/javadoc/org/bukkit/generator/package-info.java b/src/main/javadoc/org/bukkit/generator/package-info.java new file mode 100644 index 0000000..54d1c29 --- /dev/null +++ b/src/main/javadoc/org/bukkit/generator/package-info.java @@ -0,0 +1,7 @@ +/** + * Classes to facilitate {@link org.bukkit.World world} generation + * implementation. + *

            + */ +package org.bukkit.generator; + diff --git a/src/main/javadoc/org/bukkit/help/package-info.java b/src/main/javadoc/org/bukkit/help/package-info.java new file mode 100644 index 0000000..691dfcd --- /dev/null +++ b/src/main/javadoc/org/bukkit/help/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes used to manipulate the default command and topic assistance system. + *

            + */ +package org.bukkit.help; + diff --git a/src/main/javadoc/org/bukkit/inventory/meta/package-info.java b/src/main/javadoc/org/bukkit/inventory/meta/package-info.java new file mode 100644 index 0000000..f39d93a --- /dev/null +++ b/src/main/javadoc/org/bukkit/inventory/meta/package-info.java @@ -0,0 +1,7 @@ +/** + * The interfaces used when manipulating extra data can can be stored inside + * {@link org.bukkit.inventory.ItemStack item stacks}. + *

            + */ +package org.bukkit.inventory.meta; + diff --git a/src/main/javadoc/org/bukkit/inventory/package-info.java b/src/main/javadoc/org/bukkit/inventory/package-info.java new file mode 100644 index 0000000..79e26ca --- /dev/null +++ b/src/main/javadoc/org/bukkit/inventory/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes involved in manipulating player inventories and item interactions. + *

            + */ +package org.bukkit.inventory; + diff --git a/src/main/javadoc/org/bukkit/map/package-info.java b/src/main/javadoc/org/bukkit/map/package-info.java new file mode 100644 index 0000000..9e08d6e --- /dev/null +++ b/src/main/javadoc/org/bukkit/map/package-info.java @@ -0,0 +1,7 @@ +/** + * Classes to facilitate plugin handling of {@link org.bukkit.Material#MAP + * map} displays. + *

            + */ +package org.bukkit.map; + diff --git a/src/main/javadoc/org/bukkit/material/package-info.java b/src/main/javadoc/org/bukkit/material/package-info.java new file mode 100644 index 0000000..d2fa49f --- /dev/null +++ b/src/main/javadoc/org/bukkit/material/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes that represents various voxel types and states. + *

            + */ +package org.bukkit.material; + diff --git a/src/main/javadoc/org/bukkit/metadata/package-info.java b/src/main/javadoc/org/bukkit/metadata/package-info.java new file mode 100644 index 0000000..44227e6 --- /dev/null +++ b/src/main/javadoc/org/bukkit/metadata/package-info.java @@ -0,0 +1,7 @@ +/** + * Classes dedicated to providing a layer of plugin specified data on various + * Minecraft concepts. + *

            + */ +package org.bukkit.metadata; + diff --git a/src/main/javadoc/org/bukkit/package-info.java b/src/main/javadoc/org/bukkit/package-info.java new file mode 100644 index 0000000..f85c88d --- /dev/null +++ b/src/main/javadoc/org/bukkit/package-info.java @@ -0,0 +1,6 @@ +/** + * More generalized classes in the API. + *

            + */ +package org.bukkit; + diff --git a/src/main/javadoc/org/bukkit/permissions/package-info.java b/src/main/javadoc/org/bukkit/permissions/package-info.java new file mode 100644 index 0000000..3a5befe --- /dev/null +++ b/src/main/javadoc/org/bukkit/permissions/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes dedicated to providing binary state properties to players. + *

            + */ +package org.bukkit.permissions; + diff --git a/src/main/javadoc/org/bukkit/plugin/doc-files/permissions-example_plugin.yml b/src/main/javadoc/org/bukkit/plugin/doc-files/permissions-example_plugin.yml new file mode 100644 index 0000000..34d0381 --- /dev/null +++ b/src/main/javadoc/org/bukkit/plugin/doc-files/permissions-example_plugin.yml @@ -0,0 +1,64 @@ +name: ScrapBukkit +main: com.dinnerbone.bukkit.scrap.ScrapBukkit +version: 1.0.0 +website: http://www.bukkit.org +author: The Bukkit Team +description: > + Miscellaneous administrative commands for Bukkit. + This plugin is one of the default plugins shipped with Bukkit. +# commands: snipped + +permissions: + scrapbukkit.*: + description: Gives all permissions for Scrapbukkit + default: op + children: + scrapbukkit.remove: + description: Allows the player to remove items from anyones inventory + children: + scrapbukkit.remove.self: + description: Allows the player to remove items from their own inventory + scrapbukkit.remove.other: + description: Allows the player to remove items from other peoples inventory + + scrapbukkit.time: + description: Allows the player to view and change the time + children: + scrapbukkit.time.view: + description: Allows the player to view the time + default: true + scrapbukkit.time.change: + description: Allows the player to change the time + + scrapbukkit.tp: + description: Allows the player to teleport anyone to anyone else + children: + scrapbukkit.tp.here: + description: Allows the player to teleport other players to themselves + scrapbukkit.tp.self: + description: Allows the player to teleport themselves to another player + scrapbukkit.tp.other: + description: Allows the player to teleport anyone to another player + + scrapbukkit.give: + description: Allows the player to give items + children: + scrapbukkit.give.self: + description: Allows the player to give themselves items + scrapbukkit.give.other: + description: Allows the player to give other players items + + scrapbukkit.clear: + description: Allows the player to clear inventories + children: + scrapbukkit.clear.self: + description: Allows the player to clear their own inventory + scrapbukkit.clear.other: + description: Allows the player to clear other players inventory + + scrapbukkit.some.standard.perm: {} + scrapbukkit.some.other.perm: true + scrapbukkit.some.bad.perm: false + # This is defined here individually, as simply giving it an association will not cause it to exist at runtime + scrapbukkit.some.bad.perm: {} + scrapbukkit.some.other.perm: {} diff --git a/src/main/javadoc/org/bukkit/plugin/java/package-info.java b/src/main/javadoc/org/bukkit/plugin/java/package-info.java new file mode 100644 index 0000000..8d6f2a5 --- /dev/null +++ b/src/main/javadoc/org/bukkit/plugin/java/package-info.java @@ -0,0 +1,7 @@ +/** + * Classes for handling {@link org.bukkit.plugin.Plugin plugins} written in + * java. + *

            + */ +package org.bukkit.plugin.java; + diff --git a/src/main/javadoc/org/bukkit/plugin/messaging/package-info.java b/src/main/javadoc/org/bukkit/plugin/messaging/package-info.java new file mode 100644 index 0000000..c94ac66 --- /dev/null +++ b/src/main/javadoc/org/bukkit/plugin/messaging/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes dedicated to specialized plugin to client protocols. + *

            + */ +package org.bukkit.plugin.messaging; + diff --git a/src/main/javadoc/org/bukkit/plugin/package-info.java b/src/main/javadoc/org/bukkit/plugin/package-info.java new file mode 100644 index 0000000..087a0a4 --- /dev/null +++ b/src/main/javadoc/org/bukkit/plugin/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes specifically relating to loading software modules at runtime. + *

            + */ +package org.bukkit.plugin; + diff --git a/src/main/javadoc/org/bukkit/potion/package-info.java b/src/main/javadoc/org/bukkit/potion/package-info.java new file mode 100644 index 0000000..9b13a77 --- /dev/null +++ b/src/main/javadoc/org/bukkit/potion/package-info.java @@ -0,0 +1,7 @@ +/** + * Classes to represent various {@link org.bukkit.Material#POTION potion} + * properties and manipulation. + *

            + */ +package org.bukkit.potion; + diff --git a/src/main/javadoc/org/bukkit/projectiles/package-info.java b/src/main/javadoc/org/bukkit/projectiles/package-info.java new file mode 100644 index 0000000..0e39662 --- /dev/null +++ b/src/main/javadoc/org/bukkit/projectiles/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes to represent the source of a projectile + *

            + */ +package org.bukkit.projectiles; + diff --git a/src/main/javadoc/org/bukkit/scheduler/package-info.java b/src/main/javadoc/org/bukkit/scheduler/package-info.java new file mode 100644 index 0000000..87059ea --- /dev/null +++ b/src/main/javadoc/org/bukkit/scheduler/package-info.java @@ -0,0 +1,7 @@ +/** + * Classes dedicated to letting {@link org.bukkit.plugin.Plugin plugins} run + * code at specific time intervals, including thread safety. + *

            + */ +package org.bukkit.scheduler; + diff --git a/src/main/javadoc/org/bukkit/scoreboard/package-info.java b/src/main/javadoc/org/bukkit/scoreboard/package-info.java new file mode 100644 index 0000000..aad5e31 --- /dev/null +++ b/src/main/javadoc/org/bukkit/scoreboard/package-info.java @@ -0,0 +1,6 @@ +/** + * Interfaces used to manage the client side score display system. + *

            + */ +package org.bukkit.scoreboard; + diff --git a/src/main/javadoc/org/bukkit/util/io/package-info.java b/src/main/javadoc/org/bukkit/util/io/package-info.java new file mode 100644 index 0000000..8e46cca --- /dev/null +++ b/src/main/javadoc/org/bukkit/util/io/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes used to facilitate stream processing for specific Bukkit concepts. + *

            + */ +package org.bukkit.util.io; + diff --git a/src/main/javadoc/org/bukkit/util/noise/package-info.java b/src/main/javadoc/org/bukkit/util/noise/package-info.java new file mode 100644 index 0000000..f77e35d --- /dev/null +++ b/src/main/javadoc/org/bukkit/util/noise/package-info.java @@ -0,0 +1,6 @@ +/** + * Classes dedicated to facilitating deterministic noise. + *

            + */ +package org.bukkit.util.noise; + diff --git a/src/main/javadoc/org/bukkit/util/package-info.java b/src/main/javadoc/org/bukkit/util/package-info.java new file mode 100644 index 0000000..a9c4c9d --- /dev/null +++ b/src/main/javadoc/org/bukkit/util/package-info.java @@ -0,0 +1,7 @@ +/** + * Multi and single purpose classes to facilitate various programmatic + * concepts. + *

            + */ +package org.bukkit.util; + diff --git a/src/main/javadoc/org/bukkit/util/permissions/package-info.java b/src/main/javadoc/org/bukkit/util/permissions/package-info.java new file mode 100644 index 0000000..9a40b29 --- /dev/null +++ b/src/main/javadoc/org/bukkit/util/permissions/package-info.java @@ -0,0 +1,7 @@ +/** + * Static methods for miscellaneous {@link org.bukkit.permissions.Permission + * permission} functionality. + *

            + */ +package org.bukkit.util.permissions; + diff --git a/src/main/javadoc/overview.html b/src/main/javadoc/overview.html new file mode 100644 index 0000000..e96bf35 --- /dev/null +++ b/src/main/javadoc/overview.html @@ -0,0 +1,17 @@ + +

            Bukkit, the plugin development framework.

            + +

            + The documentation is for developing plugins and is split into the + respective packages for each subject matter. This documentation does not + cover running a server, contributing code back to the project, or setting + up a workspace. Working knowledge of the Java language is a prerequisite + for developing plugins. +

            + For basic plugin development, see the {@link org.bukkit.plugin plugin + package}. It covers the basic requirements of a plugin jar. +

            + For handling events and triggered code, see the {@link org.bukkit.event + event package}. +

            + diff --git a/src/site/apt/index.apt b/src/site/apt/index.apt new file mode 100644 index 0000000..0a7880a --- /dev/null +++ b/src/site/apt/index.apt @@ -0,0 +1,9 @@ +Welcome to the Bukkit Maven mini-site! + + This website is automatically generated by Maven 3. + As such, it is updated when the main build system (http://ci.bukkit.org) executes the site lifecycle on the Maven job. + For more information about Bukkit, please see the links above. + +Javadocs + + For Javadocs, please select the "Project Reports" then "JavaDocs" option on the left-hand menu. diff --git a/src/site/site.xml b/src/site/site.xml new file mode 100644 index 0000000..ff24fab --- /dev/null +++ b/src/site/site.xml @@ -0,0 +1,29 @@ + + + + Bukkit + http://bukkit.org/logo.png + http://bukkit.org/ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/java/org/bukkit/ArtTest.java b/src/test/java/org/bukkit/ArtTest.java new file mode 100644 index 0000000..29fe34a --- /dev/null +++ b/src/test/java/org/bukkit/ArtTest.java @@ -0,0 +1,45 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.greaterThan; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class ArtTest { + + @Test(expected = IllegalArgumentException.class) + public void getByNullName() { + Art.getByName(null); + } + + @Test + public void getById() { + for (Art art : Art.values()) { + assertThat(Art.getById(art.getId()), is(art)); + } + } + + @Test + public void getByName() { + for (Art art : Art.values()) { + assertThat(Art.getByName(art.toString()), is(art)); + } + } + + @Test + public void dimensionSanityCheck() { + for (Art art : Art.values()) { + assertThat(art.getBlockHeight(), is(greaterThan(0))); + assertThat(art.getBlockWidth(), is(greaterThan(0))); + } + } + + @Test + public void getByNameWithMixedCase() { + Art subject = Art.values()[0]; + String name = subject.toString().replace('E', 'e'); + + assertThat(Art.getByName(name), is(subject)); + } +} diff --git a/src/test/java/org/bukkit/BukkitMirrorTest.java b/src/test/java/org/bukkit/BukkitMirrorTest.java new file mode 100644 index 0000000..219788f --- /dev/null +++ b/src/test/java/org/bukkit/BukkitMirrorTest.java @@ -0,0 +1,75 @@ +package org.bukkit; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import com.google.common.base.Function; +import com.google.common.collect.Lists; + +@RunWith(Parameterized.class) +public class BukkitMirrorTest { + + @Parameters(name="{index}: {1}") + public static List data() { + return Lists.transform(Arrays.asList(Server.class.getDeclaredMethods()), new Function() { + @Override + public Object[] apply(Method input) { + return new Object[] { + input, + input.toGenericString().substring("public abstract ".length()).replace("(", "{").replace(")", "}") + }; + } + }); + } + + @Parameter(0) + public Method server; + + @Parameter(1) + public String name; + + private Method bukkit; + + @Before + public void makeBukkit() throws Throwable { + bukkit = Bukkit.class.getDeclaredMethod(server.getName(), server.getParameterTypes()); + } + + @Test + public void isStatic() throws Throwable { + assertThat(Modifier.isStatic(bukkit.getModifiers()), is(true)); + } + + @Test + public void isDeprecated() throws Throwable { + assertThat(bukkit.isAnnotationPresent(Deprecated.class), is(server.isAnnotationPresent(Deprecated.class))); + } + + @Test + public void returnType() throws Throwable { + assertThat(bukkit.getReturnType(), is((Object) server.getReturnType())); + assertThat(bukkit.getGenericReturnType(), is(server.getGenericReturnType())); + } + + @Test + public void parameterTypes() throws Throwable { + assertThat(bukkit.getGenericParameterTypes(), is(server.getGenericParameterTypes())); + } + + @Test + public void declaredException() throws Throwable { + assertThat(bukkit.getGenericExceptionTypes(), is(server.getGenericExceptionTypes())); + } +} diff --git a/src/test/java/org/bukkit/ChatColorTest.java b/src/test/java/org/bukkit/ChatColorTest.java new file mode 100644 index 0000000..80108a5 --- /dev/null +++ b/src/test/java/org/bukkit/ChatColorTest.java @@ -0,0 +1,83 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class ChatColorTest { + + @Test + public void getByChar() { + for (ChatColor color : ChatColor.values()) { + assertThat(ChatColor.getByChar(color.getChar()), is(color)); + } + } + + @Test(expected = IllegalArgumentException.class) + public void getByStringWithNull() { + ChatColor.getByChar((String) null); + } + + @Test(expected = IllegalArgumentException.class) + public void getByStringWithEmpty() { + ChatColor.getByChar(""); + } + + @Test + public void getByNull() { + assertThat(ChatColor.stripColor(null), is(nullValue())); + } + + @Test + public void getByString() { + for (ChatColor color : ChatColor.values()) { + assertThat(ChatColor.getByChar(String.valueOf(color.getChar())), is(color)); + } + } + + @Test + public void stripColorOnNullString() { + assertThat(ChatColor.stripColor(null), is(nullValue())); + } + + @Test + public void stripColor() { + StringBuilder subject = new StringBuilder(); + StringBuilder expected = new StringBuilder(); + + final String filler = "test"; + for (ChatColor color : ChatColor.values()) { + subject.append(color).append(filler); + expected.append(filler); + } + + assertThat(ChatColor.stripColor(subject.toString()), is(expected.toString())); + } + + @Test + public void toStringWorks() { + for (ChatColor color : ChatColor.values()) { + assertThat(String.format("%c%c", ChatColor.COLOR_CHAR, color.getChar()), is(color.toString())); + } + } + + @Test + public void translateAlternateColorCodes() { + String s = "&0&1&2&3&4&5&6&7&8&9&A&a&B&b&C&c&D&d&E&e&F&f&K&k & more"; + String t = ChatColor.translateAlternateColorCodes('&', s); + String u = ChatColor.BLACK.toString() + ChatColor.DARK_BLUE + ChatColor.DARK_GREEN + ChatColor.DARK_AQUA + ChatColor.DARK_RED + ChatColor.DARK_PURPLE + ChatColor.GOLD + ChatColor.GRAY + ChatColor.DARK_GRAY + ChatColor.BLUE + ChatColor.GREEN + ChatColor.GREEN + ChatColor.AQUA + ChatColor.AQUA + ChatColor.RED + ChatColor.RED + ChatColor.LIGHT_PURPLE + ChatColor.LIGHT_PURPLE + ChatColor.YELLOW + ChatColor.YELLOW + ChatColor.WHITE + ChatColor.WHITE + ChatColor.MAGIC + ChatColor.MAGIC + " & more"; + assertThat(t, is(u)); + } + + @Test + public void getChatColors() { + String s = String.format("%c%ctest%c%ctest%c", ChatColor.COLOR_CHAR, ChatColor.RED.getChar(), ChatColor.COLOR_CHAR, ChatColor.ITALIC.getChar(), ChatColor.COLOR_CHAR); + String expected = ChatColor.RED.toString() + ChatColor.ITALIC; + assertThat(ChatColor.getLastColors(s), is(expected)); + + s = String.format("%c%ctest%c%ctest", ChatColor.COLOR_CHAR, ChatColor.RED.getChar(), ChatColor.COLOR_CHAR, ChatColor.BLUE.getChar()); + assertThat(ChatColor.getLastColors(s), is(ChatColor.BLUE.toString())); + } +} diff --git a/src/test/java/org/bukkit/ChatPaginatorTest.java b/src/test/java/org/bukkit/ChatPaginatorTest.java new file mode 100644 index 0000000..0a8acae --- /dev/null +++ b/src/test/java/org/bukkit/ChatPaginatorTest.java @@ -0,0 +1,166 @@ +package org.bukkit; + +import org.bukkit.util.ChatPaginator; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +/** + */ +public class ChatPaginatorTest { + @Test + public void testWordWrap1() { + String rawString = ChatColor.RED + "123456789 123456789 123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 19); + + assertThat(lines.length, is(2)); + assertThat(lines[0], is(ChatColor.RED + "123456789 123456789")); + assertThat(lines[1], is(ChatColor.RED.toString() + "123456789")); + } + + @Test + public void testWordWrap2() { + String rawString = "123456789 123456789 123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 22); + + assertThat(lines.length, is(2)); + assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456789 123456789")); + assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789")); + } + + @Test + public void testWordWrap3() { + String rawString = ChatColor.RED + "123456789 " + ChatColor.RED + ChatColor.RED + "123456789 " + ChatColor.RED + "123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 16); + + assertThat(lines.length, is(3)); + assertThat(lines[0], is(ChatColor.RED + "123456789")); + assertThat(lines[1], is(ChatColor.RED.toString() + ChatColor.RED + "123456789")); + assertThat(lines[2], is(ChatColor.RED + "123456789")); + } + + @Test + public void testWordWrap4() { + String rawString = "123456789 123456789 123456789 12345"; + String[] lines = ChatPaginator.wordWrap(rawString, 19); + + assertThat(lines.length, is(2)); + assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456789 123456789")); + assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789 12345")); + } + + @Test + public void testWordWrap5() { + String rawString = "123456789\n123456789 123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 19); + + assertThat(lines.length, is(2)); + assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456789")); + assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789 123456789")); + } + + @Test + public void testWordWrap6() { + String rawString = "12345678 23456789 123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 19); + + assertThat(lines.length, is(2)); + assertThat(lines[0], is(ChatColor.WHITE.toString() + "12345678 23456789")); + assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789")); + } + + @Test + public void testWordWrap7() { + String rawString = "12345678 23456789 123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 19); + + assertThat(lines.length, is(2)); + assertThat(lines[0], is(ChatColor.WHITE.toString() + "12345678 23456789")); + assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789")); + } + + @Test + public void testWordWrap8() { + String rawString = "123456789 123456789 123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 6); + + assertThat(lines.length, is(6)); + assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456")); + assertThat(lines[1], is(ChatColor.WHITE.toString() + "789")); + assertThat(lines[2], is(ChatColor.WHITE.toString() + "123456")); + assertThat(lines[3], is(ChatColor.WHITE.toString() + "789")); + assertThat(lines[4], is(ChatColor.WHITE.toString() + "123456")); + assertThat(lines[5], is(ChatColor.WHITE.toString() + "789")); + } + + @Test + public void testWordWrap9() { + String rawString = "1234 123456789 123456789 123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 6); + + assertThat(lines.length, is(7)); + assertThat(lines[0], is(ChatColor.WHITE.toString() + "1234")); + assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456")); + assertThat(lines[2], is(ChatColor.WHITE.toString() + "789")); + assertThat(lines[3], is(ChatColor.WHITE.toString() + "123456")); + assertThat(lines[4], is(ChatColor.WHITE.toString() + "789")); + assertThat(lines[5], is(ChatColor.WHITE.toString() + "123456")); + assertThat(lines[6], is(ChatColor.WHITE.toString() + "789")); + } + + @Test + public void testWordWrap10() { + String rawString = "123456789\n123456789"; + String[] lines = ChatPaginator.wordWrap(rawString, 19); + + assertThat(lines.length, is(2)); + assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456789")); + assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789")); + } + + @Test + public void testWordWrap11() { + String rawString = ChatColor.RED + "a a a " + ChatColor.BLUE + "a a"; + String[] lines = ChatPaginator.wordWrap(rawString, 9); + + assertThat(lines.length, is(1)); + assertThat(lines[0], is(ChatColor.RED + "a a a " + ChatColor.BLUE + "a a")); + } + + @Test + public void testPaginate1() { + String rawString = "1234 123456789 123456789 123456789"; + ChatPaginator.ChatPage page = ChatPaginator.paginate(rawString, 1, 6, 2); + + assertThat(page.getPageNumber(), is(1)); + assertThat(page.getTotalPages(), is(4)); + assertThat(page.getLines().length, is(2)); + assertThat(page.getLines()[0], is(ChatColor.WHITE.toString() + "1234")); + assertThat(page.getLines()[1], is(ChatColor.WHITE.toString() + "123456")); + } + + @Test + public void testPaginate2() { + String rawString = "1234 123456789 123456789 123456789"; + ChatPaginator.ChatPage page = ChatPaginator.paginate(rawString, 2, 6, 2); + + assertThat(page.getPageNumber(), is(2)); + assertThat(page.getTotalPages(), is(4)); + assertThat(page.getLines().length, is(2)); + assertThat(page.getLines()[0], is(ChatColor.WHITE.toString() + "789")); + assertThat(page.getLines()[1], is(ChatColor.WHITE.toString() + "123456")); + } + + @Test + public void testPaginate3() { + String rawString = "1234 123456789 123456789 123456789"; + ChatPaginator.ChatPage page = ChatPaginator.paginate(rawString, 4, 6, 2); + + assertThat(page.getPageNumber(), is(4)); + assertThat(page.getTotalPages(), is(4)); + assertThat(page.getLines().length, is(1)); + assertThat(page.getLines()[0], is(ChatColor.WHITE.toString() + "789")); + } +} diff --git a/src/test/java/org/bukkit/CoalTypeTest.java b/src/test/java/org/bukkit/CoalTypeTest.java new file mode 100644 index 0000000..7eb11ce --- /dev/null +++ b/src/test/java/org/bukkit/CoalTypeTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class CoalTypeTest { + @Test + public void getByData() { + for (CoalType coalType : CoalType.values()) { + assertThat(CoalType.getByData(coalType.getData()), is(coalType)); + } + } +} diff --git a/src/test/java/org/bukkit/ColorTest.java b/src/test/java/org/bukkit/ColorTest.java new file mode 100644 index 0000000..8d9557a --- /dev/null +++ b/src/test/java/org/bukkit/ColorTest.java @@ -0,0 +1,365 @@ +package org.bukkit; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.Test; + +@SuppressWarnings("javadoc") +public class ColorTest { + static class TestColor { + static int id = 0; + final String name; + final int rgb; + final int bgr; + final int r; + final int g; + final int b; + + TestColor(int rgb, int bgr, int r, int g, int b) { + this.rgb = rgb; + this.bgr = bgr; + this.r = r; + this.g = g; + this.b = b; + this.name = id + ":" + Integer.toHexString(rgb).toUpperCase() + "_" + Integer.toHexString(bgr).toUpperCase() + "-r" + Integer.toHexString(r).toUpperCase() + "-g" + Integer.toHexString(g).toUpperCase() + "-b" + Integer.toHexString(b).toUpperCase(); + } + } + + static TestColor[] examples = new TestColor[] { + /* 0xRRGGBB, 0xBBGGRR, 0xRR, 0xGG, 0xBB */ + new TestColor(0xFFFFFF, 0xFFFFFF, 0xFF, 0xFF, 0xFF), + new TestColor(0xFFFFAA, 0xAAFFFF, 0xFF, 0xFF, 0xAA), + new TestColor(0xFF00FF, 0xFF00FF, 0xFF, 0x00, 0xFF), + new TestColor(0x67FF22, 0x22FF67, 0x67, 0xFF, 0x22), + new TestColor(0x000000, 0x000000, 0x00, 0x00, 0x00) + }; + + @Test + public void testSerialization() throws Throwable { + for (TestColor testColor : examples) { + Color base = Color.fromRGB(testColor.rgb); + + YamlConfiguration toSerialize = new YamlConfiguration(); + toSerialize.set("color", base); + String serialized = toSerialize.saveToString(); + + YamlConfiguration deserialized = new YamlConfiguration(); + deserialized.loadFromString(serialized); + + assertThat(testColor.name + " on " + serialized, base, is(deserialized.getColor("color"))); + } + } + + // Equality tests + @Test + public void testEqualities() { + for (TestColor testColor : examples) { + Color fromRGB = Color.fromRGB(testColor.rgb); + Color fromBGR = Color.fromBGR(testColor.bgr); + Color fromRGBs = Color.fromRGB(testColor.r, testColor.g, testColor.b); + Color fromBGRs = Color.fromBGR(testColor.b, testColor.g, testColor.r); + + assertThat(testColor.name, fromRGB, is(fromRGBs)); + assertThat(testColor.name, fromRGB, is(fromBGR)); + assertThat(testColor.name, fromRGB, is(fromBGRs)); + assertThat(testColor.name, fromRGBs, is(fromBGR)); + assertThat(testColor.name, fromRGBs, is(fromBGRs)); + assertThat(testColor.name, fromBGR, is(fromBGRs)); + } + } + + @Test + public void testInequalities() { + for (int i = 1; i < examples.length; i++) { + TestColor testFrom = examples[i]; + Color from = Color.fromRGB(testFrom.rgb); + for (int j = i - 1; j >= 0; j--) { + TestColor testTo = examples[j]; + Color to = Color.fromRGB(testTo.rgb); + String name = testFrom.name + " to " + testTo.name; + assertThat(name, from, is(not(to))); + + Color transform = from.setRed(testTo.r).setBlue(testTo.b).setGreen(testTo.g); + assertThat(name, transform, is(not(sameInstance(from)))); + assertThat(name, transform, is(to)); + } + } + } + + // RGB tests + @Test + public void testRGB() { + for (TestColor testColor : examples) { + assertThat(testColor.name, Color.fromRGB(testColor.rgb).asRGB(), is(testColor.rgb)); + assertThat(testColor.name, Color.fromBGR(testColor.bgr).asRGB(), is(testColor.rgb)); + assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).asRGB(), is(testColor.rgb)); + assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).asRGB(), is(testColor.rgb)); + } + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidRGB1() { + Color.fromRGB(0x01000000); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidRGB2() { + Color.fromRGB(Integer.MIN_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidRGB3() { + Color.fromRGB(Integer.MAX_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidRGB4() { + Color.fromRGB(-1); + } + + // BGR tests + @Test + public void testBGR() { + for (TestColor testColor : examples) { + assertThat(testColor.name, Color.fromRGB(testColor.rgb).asBGR(), is(testColor.bgr)); + assertThat(testColor.name, Color.fromBGR(testColor.bgr).asBGR(), is(testColor.bgr)); + assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).asBGR(), is(testColor.bgr)); + assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).asBGR(), is(testColor.bgr)); + } + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidBGR1() { + Color.fromBGR(0x01000000); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidBGR2() { + Color.fromBGR(Integer.MIN_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidBGR3() { + Color.fromBGR(Integer.MAX_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidBGR4() { + Color.fromBGR(-1); + } + + // Red tests + @Test + public void testRed() { + for (TestColor testColor : examples) { + assertThat(testColor.name, Color.fromRGB(testColor.rgb).getRed(), is(testColor.r)); + assertThat(testColor.name, Color.fromBGR(testColor.bgr).getRed(), is(testColor.r)); + assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).getRed(), is(testColor.r)); + assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).getRed(), is(testColor.r)); + } + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR01() { + Color.fromRGB(-1, 0x00, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR02() { + Color.fromRGB(Integer.MAX_VALUE, 0x00, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR03() { + Color.fromRGB(Integer.MIN_VALUE, 0x00, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR04() { + Color.fromRGB(0x100, 0x00, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR05() { + Color.fromBGR(0x00, 0x00, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR06() { + Color.fromBGR(0x00, 0x00, Integer.MAX_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR07() { + Color.fromBGR(0x00, 0x00, Integer.MIN_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR08() { + Color.fromBGR(0x00, 0x00, 0x100); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR09() { + Color.WHITE.setRed(-1); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR10() { + Color.WHITE.setRed(Integer.MAX_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR11() { + Color.WHITE.setRed(Integer.MIN_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidR12() { + Color.WHITE.setRed(0x100); + } + + // Blue tests + @Test + public void testBlue() { + for (TestColor testColor : examples) { + assertThat(testColor.name, Color.fromRGB(testColor.rgb).getBlue(), is(testColor.b)); + assertThat(testColor.name, Color.fromBGR(testColor.bgr).getBlue(), is(testColor.b)); + assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).getBlue(), is(testColor.b)); + assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).getBlue(), is(testColor.b)); + } + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB01() { + Color.fromRGB(0x00, 0x00, -1); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB02() { + Color.fromRGB(0x00, 0x00, Integer.MAX_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB03() { + Color.fromRGB(0x00, 0x00, Integer.MIN_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB04() { + Color.fromRGB(0x00, 0x00, 0x100); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB05() { + Color.fromBGR(-1, 0x00, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB06() { + Color.fromBGR(Integer.MAX_VALUE, 0x00, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB07() { + Color.fromBGR(Integer.MIN_VALUE, 0x00, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB08() { + Color.fromBGR(0x100, 0x00, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB09() { + Color.WHITE.setBlue(-1); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB10() { + Color.WHITE.setBlue(Integer.MAX_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB11() { + Color.WHITE.setBlue(Integer.MIN_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidB12() { + Color.WHITE.setBlue(0x100); + } + + // Green tests + @Test + public void testGreen() { + for (TestColor testColor : examples) { + assertThat(testColor.name, Color.fromRGB(testColor.rgb).getGreen(), is(testColor.g)); + assertThat(testColor.name, Color.fromBGR(testColor.bgr).getGreen(), is(testColor.g)); + assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).getGreen(), is(testColor.g)); + assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).getGreen(), is(testColor.g)); + } + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG01() { + Color.fromRGB(0x00, -1, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG02() { + Color.fromRGB(0x00, Integer.MAX_VALUE, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG03() { + Color.fromRGB(0x00, Integer.MIN_VALUE, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG04() { + Color.fromRGB(0x00, 0x100, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG05() { + Color.fromBGR(0x00, -1, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG06() { + Color.fromBGR(0x00, Integer.MAX_VALUE, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG07() { + Color.fromBGR(0x00, Integer.MIN_VALUE, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG08() { + Color.fromBGR(0x00, 0x100, 0x00); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG09() { + Color.WHITE.setGreen(-1); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG10() { + Color.WHITE.setGreen(Integer.MAX_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG11() { + Color.WHITE.setGreen(Integer.MIN_VALUE); + } + + @Test(expected=IllegalArgumentException.class) + public void testInvalidG12() { + Color.WHITE.setGreen(0x100); + } +} diff --git a/src/test/java/org/bukkit/CropStateTest.java b/src/test/java/org/bukkit/CropStateTest.java new file mode 100644 index 0000000..f792a1c --- /dev/null +++ b/src/test/java/org/bukkit/CropStateTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class CropStateTest { + @Test + public void getByData() { + for (CropState cropState : CropState.values()) { + assertThat(CropState.getByData(cropState.getData()), is(cropState)); + } + } +} diff --git a/src/test/java/org/bukkit/DifficultyTest.java b/src/test/java/org/bukkit/DifficultyTest.java new file mode 100644 index 0000000..293e283 --- /dev/null +++ b/src/test/java/org/bukkit/DifficultyTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class DifficultyTest { + @Test + public void getByValue() { + for (Difficulty difficulty : Difficulty.values()) { + assertThat(Difficulty.getByValue(difficulty.getValue()), is(difficulty)); + } + } +} diff --git a/src/test/java/org/bukkit/DyeColorTest.java b/src/test/java/org/bukkit/DyeColorTest.java new file mode 100644 index 0000000..9e30fbf --- /dev/null +++ b/src/test/java/org/bukkit/DyeColorTest.java @@ -0,0 +1,70 @@ +package org.bukkit; + +import static org.junit.Assert.*; +import static org.hamcrest.Matchers.*; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.material.Colorable; +import org.bukkit.material.Dye; +import org.bukkit.material.Wool; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(Parameterized.class) +public class DyeColorTest { + + @Parameters(name= "{index}: {0}") + public static List data() { + List list = new ArrayList(); + for (DyeColor dye : DyeColor.values()) { + list.add(new Object[] {dye}); + } + return list; + } + + @Parameter public DyeColor dye; + + @Test + @SuppressWarnings("deprecation") + public void getByData() { + byte data = dye.getData(); + + DyeColor byData = DyeColor.getByData(data); + assertThat(byData, is(dye)); + } + + @Test + public void getByWoolData() { + byte data = dye.getWoolData(); + + DyeColor byData = DyeColor.getByWoolData(data); + assertThat(byData, is(dye)); + } + + @Test + public void getByDyeData() { + byte data = dye.getDyeData(); + + DyeColor byData = DyeColor.getByDyeData(data); + assertThat(byData, is(dye)); + } + + @Test + public void getDyeDyeColor() { + testColorable(new Dye(Material.INK_SACK, dye.getDyeData())); + } + + @Test + public void getWoolDyeColor() { + testColorable(new Wool(Material.WOOL, dye.getWoolData())); + } + + private void testColorable(final Colorable colorable) { + assertThat(colorable.getColor(), is(this.dye)); + } +} diff --git a/src/test/java/org/bukkit/EffectTest.java b/src/test/java/org/bukkit/EffectTest.java new file mode 100644 index 0000000..08aa71d --- /dev/null +++ b/src/test/java/org/bukkit/EffectTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class EffectTest { + @Test + public void getById() { + for (Effect effect : Effect.values()) { + assertThat(Effect.getById(effect.getId()), is(effect)); + } + } +} diff --git a/src/test/java/org/bukkit/EntityEffectTest.java b/src/test/java/org/bukkit/EntityEffectTest.java new file mode 100644 index 0000000..0c92d5c --- /dev/null +++ b/src/test/java/org/bukkit/EntityEffectTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class EntityEffectTest { + @Test + public void getByData() { + for (EntityEffect entityEffect : EntityEffect.values()) { + assertThat(EntityEffect.getByData(entityEffect.getData()), is(entityEffect)); + } + } +} diff --git a/src/test/java/org/bukkit/GameModeTest.java b/src/test/java/org/bukkit/GameModeTest.java new file mode 100644 index 0000000..f671fae --- /dev/null +++ b/src/test/java/org/bukkit/GameModeTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class GameModeTest { + @Test + public void getByValue() { + for (GameMode gameMode : GameMode.values()) { + assertThat(GameMode.getByValue(gameMode.getValue()), is(gameMode)); + } + } +} diff --git a/src/test/java/org/bukkit/GrassSpeciesTest.java b/src/test/java/org/bukkit/GrassSpeciesTest.java new file mode 100644 index 0000000..9e332c7 --- /dev/null +++ b/src/test/java/org/bukkit/GrassSpeciesTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class GrassSpeciesTest { + @Test + public void getByData() { + for (GrassSpecies grassSpecies : GrassSpecies.values()) { + assertThat(GrassSpecies.getByData(grassSpecies.getData()), is(grassSpecies)); + } + } +} diff --git a/src/test/java/org/bukkit/InstrumentTest.java b/src/test/java/org/bukkit/InstrumentTest.java new file mode 100644 index 0000000..f1a0570 --- /dev/null +++ b/src/test/java/org/bukkit/InstrumentTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class InstrumentTest { + @Test + public void getByType() { + for (Instrument instrument : Instrument.values()) { + assertThat(Instrument.getByType(instrument.getType()), is(instrument)); + } + } +} diff --git a/src/test/java/org/bukkit/LocationTest.java b/src/test/java/org/bukkit/LocationTest.java new file mode 100644 index 0000000..fa24776 --- /dev/null +++ b/src/test/java/org/bukkit/LocationTest.java @@ -0,0 +1,196 @@ +package org.bukkit; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.List; +import java.util.Random; + +import org.bukkit.util.Vector; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import com.google.common.collect.ImmutableList; + +@RunWith(Parameterized.class) +public class LocationTest { + private static final double δ = 1.0 / 1000000; + /** + *
            +     * a² + b² = c², a = b
            +     * => 2∙(a²) = 2∙(b²) = c², c = 1
            +     * => 2∙(a²) = 1
            +     * => a² = 1/2
            +     * => a = √(1/2) ∎
            +     * 
            + */ + private static final double HALF_UNIT = Math.sqrt(1 / 2f); + /** + *
            +     * a² + b² = c², c = √(1/2)
            +     * => a² + b² = √(1/2)², a = b
            +     * => 2∙(a²) = 2∙(b²) = 1/2
            +     * => a² = 1/4
            +     * => a = √(1/4) ∎
            +     * 
            + */ + private static final double HALF_HALF_UNIT = Math.sqrt(1 / 4f); + + @Parameters(name= "{index}: {0}") + public static List data() { + Random RANDOM = new Random(1l); // Test is deterministic + int r = 0; + return ImmutableList.of( + new Object[] { "X", + 1, 0, 0, + 270, 0 + }, + new Object[] { "-X", + -1, 0, 0, + 90, 0 + }, + new Object[] { "Z", + 0, 0, 1, + 0, 0 + }, + new Object[] { "-Z", + 0, 0, -1, + 180, 0 + }, + new Object[] { "Y", + 0, 1, 0, + 0, -90 // Zero is here as a "default" value + }, + new Object[] { "-Y", + 0, -1, 0, + 0, 90 // Zero is here as a "default" value + }, + new Object[] { "X Z", + HALF_UNIT, 0, HALF_UNIT, + (270 + 360) / 2, 0 + }, + new Object[] { "X -Z", + HALF_UNIT, 0, -HALF_UNIT, + (270 + 180) / 2, 0 + }, + new Object[] { "-X -Z", + -HALF_UNIT, 0, -HALF_UNIT, + (90 + 180) / 2, 0 + }, + new Object[] { "-X Z", + -HALF_UNIT, 0, HALF_UNIT, + (90 + 0) / 2, 0 + }, + new Object[] { "X Y Z", + HALF_HALF_UNIT, HALF_UNIT, HALF_HALF_UNIT, + (270 + 360) / 2, -45 + }, + new Object[] { "-X -Y -Z", + -HALF_HALF_UNIT, -HALF_UNIT, -HALF_HALF_UNIT, + (90 + 180) / 2, 45 + }, + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++), + getRandom(RANDOM, r++) + ); + } + + private static Object[] getRandom(Random random, int index) { + final double YAW_FACTOR = 360; + final double YAW_OFFSET = 0; + final double PITCH_FACTOR = 180; + final double PITCH_OFFSET = -90; + final double CARTESIAN_FACTOR = 256; + final double CARTESIAN_OFFSET = -128; + + Vector vector; + Location location; + if (random.nextBoolean()) { + float pitch = (float) (random.nextDouble() * PITCH_FACTOR + PITCH_OFFSET); + float yaw = (float) (random.nextDouble() * YAW_FACTOR + YAW_OFFSET); + + location = getEmptyLocation(); + location.setPitch(pitch); + location.setYaw(yaw); + + vector = location.getDirection(); + } else { + double x = random.nextDouble() * CARTESIAN_FACTOR + CARTESIAN_OFFSET; + double y = random.nextDouble() * CARTESIAN_FACTOR + CARTESIAN_OFFSET; + double z = random.nextDouble() * CARTESIAN_FACTOR + CARTESIAN_OFFSET; + + location = getEmptyLocation(); + vector = new Vector(x, y, z).normalize(); + + location.setDirection(vector); + } + + return new Object[] { "R" + index, + vector.getX(), vector.getY(), vector.getZ(), + location.getYaw(), location.getPitch() + }; + } + + @Parameter(0) + public String nane; + @Parameter(1) + public double x; + @Parameter(2) + public double y; + @Parameter(3) + public double z; + @Parameter(4) + public float yaw; + @Parameter(5) + public float pitch; + + @Test + public void testExpectedPitchYaw() { + Location location = getEmptyLocation().setDirection(getVector()); + + assertThat((double) location.getYaw(), is(closeTo(yaw, δ))); + assertThat((double) location.getPitch(), is(closeTo(pitch, δ))); + } + + @Test + public void testExpectedXYZ() { + Vector vector = getLocation().getDirection(); + + assertThat(vector.getX(), is(closeTo(x, δ))); + assertThat(vector.getY(), is(closeTo(y, δ))); + assertThat(vector.getZ(), is(closeTo(z, δ))); + } + + private Vector getVector() { + return new Vector(x, y, z); + } + + private static Location getEmptyLocation() { + return new Location(null, 0, 0, 0); + } + + private Location getLocation() { + Location location = getEmptyLocation(); + location.setYaw(yaw); + location.setPitch(pitch); + return location; + } +} diff --git a/src/test/java/org/bukkit/MaterialTest.java b/src/test/java/org/bukkit/MaterialTest.java new file mode 100644 index 0000000..cbca840 --- /dev/null +++ b/src/test/java/org/bukkit/MaterialTest.java @@ -0,0 +1,85 @@ +package org.bukkit; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import org.bukkit.material.MaterialData; +import org.junit.Test; + +public class MaterialTest { + @Test + public void getByName() { + for (Material material : Material.values()) { + assertThat(Material.getMaterial(material.toString()), is(material)); + } + } + + @Test + public void getById() throws Throwable { + for (Material material : Material.values()) { + if (material.getClass().getField(material.name()).getAnnotation(Deprecated.class) != null) { + continue; + } + assertThat(Material.getMaterial(material.getId()), is(material)); + } + } + + @Test + public void isBlock() { + for (Material material : Material.values()) { + if (material.getId() > 255) continue; + + assertTrue(String.format("[%d] %s", material.getId(), material.toString()), material.isBlock()); + } + } + + @Test + public void getByOutOfRangeId() { + assertThat(Material.getMaterial(Integer.MAX_VALUE), is(nullValue())); + assertThat(Material.getMaterial(Integer.MIN_VALUE), is(nullValue())); + } + + @Test + public void getByNameNull() { + assertThat(Material.getMaterial(null), is(nullValue())); + } + + @Test + public void getData() { + for (Material material : Material.values()) { + Class clazz = material.getData(); + + assertThat(material.getNewData((byte) 0), is(instanceOf(clazz))); + } + } + + @Test(expected = IllegalArgumentException.class) + public void matchMaterialByNull() { + Material.matchMaterial(null); + } + + @Test + public void matchMaterialById() throws Throwable { + for (Material material : Material.values()) { + if (material.getClass().getField(material.name()).getAnnotation(Deprecated.class) != null) { + continue; + } + assertThat(Material.matchMaterial(String.valueOf(material.getId())), is(material)); + } + } + + @Test + public void matchMaterialByName() { + for (Material material : Material.values()) { + assertThat(Material.matchMaterial(material.toString()), is(material)); + } + } + + @Test + public void matchMaterialByLowerCaseAndSpaces() { + for (Material material : Material.values()) { + String name = material.toString().replaceAll("_", " ").toLowerCase(); + assertThat(Material.matchMaterial(name), is(material)); + } + } +} diff --git a/src/test/java/org/bukkit/NoteTest.java b/src/test/java/org/bukkit/NoteTest.java new file mode 100644 index 0000000..4759041 --- /dev/null +++ b/src/test/java/org/bukkit/NoteTest.java @@ -0,0 +1,156 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Collection; + +import org.junit.Test; + +import com.google.common.collect.Lists; + +public class NoteTest { + @Test + public void getToneByData() { + for (Note.Tone tone : Note.Tone.values()) { + assertThat(Note.Tone.getById(tone.getId()), is(tone)); + } + } + + @Test + public void verifySharpedData() { + for (Note.Tone tone : Note.Tone.values()) { + if (!tone.isSharpable()) return; + + assertFalse(tone.isSharped(tone.getId(false))); + assertTrue(tone.isSharped(tone.getId(true))); + } + } + + @Test + public void verifyUnknownToneData() { + Collection tones = Lists.newArrayList(); + for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) { + tones.add((byte) i); + } + + for (Note.Tone tone : Note.Tone.values()) { + if (tone.isSharpable()) tones.remove(tone.getId(true)); + tones.remove(tone.getId()); + } + + for (Byte data : tones) { + assertThat(Note.Tone.getById(data), is(nullValue())); + + for (Note.Tone tone : Note.Tone.values()) { + try { + tone.isSharped(data); + + fail(data + " should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertNotNull(e); + } + } + } + } + + @Test(expected = IllegalArgumentException.class) + public void createNoteBelowMin() { + new Note((byte) -1); + } + + @Test(expected = IllegalArgumentException.class) + public void createNoteAboveMax() { + new Note((byte) 25); + } + + @Test(expected = IllegalArgumentException.class) + public void createNoteOctaveBelowMax() { + new Note((byte) -1, Note.Tone.A, true); + } + + @Test(expected = IllegalArgumentException.class) + public void createNoteOctaveAboveMax() { + new Note((byte) 3, Note.Tone.A, true); + } + + @Test + public void createNoteOctaveNonSharpable() { + Note note = new Note((byte) 0, Note.Tone.B, true); + assertFalse(note.isSharped()); + assertThat(note.getTone(), is(Note.Tone.C)); + } + + @Test + public void createNoteFlat() { + Note note = Note.flat(0, Note.Tone.D); + assertTrue(note.isSharped()); + assertThat(note.getTone(), is(Note.Tone.C)); + } + + @Test + public void createNoteFlatNonFlattenable() { + Note note = Note.flat(0, Note.Tone.C); + assertFalse(note.isSharped()); + assertThat(note.getTone(), is(Note.Tone.B)); + } + + @Test + public void testFlatWrapping() { + Note note = Note.flat(1, Note.Tone.G); + assertTrue(note.isSharped()); + assertThat(note.getTone(), is(Note.Tone.F)); + } + + @Test + public void testFlatWrapping2() { + Note note = new Note(1, Note.Tone.G, false).flattened(); + assertTrue(note.isSharped()); + assertThat(note.getTone(), is(Note.Tone.F)); + } + + @Test + public void testSharpWrapping() { + Note note = new Note(1, Note.Tone.F, false).sharped(); + assertTrue(note.isSharped()); + assertThat(note.getTone(), is(Note.Tone.F)); + assertEquals(note.getOctave(), 2); + } + + @Test(expected=IllegalArgumentException.class) + public void testSharpWrapping2() { + new Note(2, Note.Tone.F, true).sharped(); + } + + @Test + public void testHighest() { + Note note = new Note(2, Note.Tone.F, true); + assertEquals(note.getId(), (byte)24); + } + + @Test + public void testLowest() { + Note note = new Note(0, Note.Tone.F, true); + assertEquals(note.getId(), (byte)0); + } + + @Test + public void doo() { + for (int i = 1; i <= 24; i++) { + Note note = new Note((byte) i); + int octave = note.getOctave(); + Note.Tone tone = note.getTone(); + boolean sharped = note.isSharped(); + + Note newNote = new Note(octave, tone, sharped); + assertThat(newNote, is(note)); + assertThat(newNote.getId(), is(note.getId())); + } + } +} diff --git a/src/test/java/org/bukkit/TestServer.java b/src/test/java/org/bukkit/TestServer.java new file mode 100644 index 0000000..2d84032 --- /dev/null +++ b/src/test/java/org/bukkit/TestServer.java @@ -0,0 +1,100 @@ +package org.bukkit; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Map; +import java.util.logging.Logger; + +import org.bukkit.command.SimpleCommandMap; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.SimplePluginManager; + +import com.google.common.collect.ImmutableMap; + +public class TestServer implements InvocationHandler { + private static interface MethodHandler { + Object handle(TestServer server, Object[] args); + } + + private static final Map methods; + + static { + try { + ImmutableMap.Builder methodMap = ImmutableMap.builder(); + methodMap.put( + Server.class.getMethod("isPrimaryThread"), + new MethodHandler() { + public Object handle(TestServer server, Object[] args) { + return Thread.currentThread().equals(server.creatingThread); + } + } + ); + methodMap.put( + Server.class.getMethod("getPluginManager"), + new MethodHandler() { + public Object handle(TestServer server, Object[] args) { + return server.pluginManager; + } + } + ); + methodMap.put( + Server.class.getMethod("getLogger"), + new MethodHandler() { + final Logger logger = Logger.getLogger(TestServer.class.getCanonicalName()); + public Object handle(TestServer server, Object[] args) { + return logger; + } + } + ); + methodMap.put( + Server.class.getMethod("getName"), + new MethodHandler() { + public Object handle(TestServer server, Object[] args) { + return TestServer.class.getSimpleName(); + } + } + ); + methodMap.put( + Server.class.getMethod("getVersion"), + new MethodHandler() { + public Object handle(TestServer server, Object[] args) { + return "Version_" + TestServer.class.getPackage().getImplementationVersion(); + } + } + ); + methodMap.put( + Server.class.getMethod("getBukkitVersion"), + new MethodHandler() { + public Object handle(TestServer server, Object[] args) { + return "BukkitVersion_" + TestServer.class.getPackage().getImplementationVersion(); + } + } + ); + methods = methodMap.build(); + + TestServer server = new TestServer(); + Server instance = Proxy.getProxyClass(Server.class.getClassLoader(), Server.class).asSubclass(Server.class).getConstructor(InvocationHandler.class).newInstance(server); + Bukkit.setServer(instance); + server.pluginManager = new SimplePluginManager(instance, new SimpleCommandMap(instance)); + } catch (Throwable t) { + throw new Error(t); + } + } + + private Thread creatingThread = Thread.currentThread(); + private PluginManager pluginManager; + private TestServer() {}; + + public static Server getInstance() { + return Bukkit.getServer(); + } + + public Object invoke(Object proxy, Method method, Object[] args) { + MethodHandler handler = methods.get(method); + if (handler != null) { + return handler.handle(this, args); + } + throw new UnsupportedOperationException(String.valueOf(method)); + } +} diff --git a/src/test/java/org/bukkit/TreeSpeciesTest.java b/src/test/java/org/bukkit/TreeSpeciesTest.java new file mode 100644 index 0000000..4a99730 --- /dev/null +++ b/src/test/java/org/bukkit/TreeSpeciesTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class TreeSpeciesTest { + @Test + public void getByData() { + for (TreeSpecies treeSpecies : TreeSpecies.values()) { + assertThat(TreeSpecies.getByData(treeSpecies.getData()), is(treeSpecies)); + } + } +} diff --git a/src/test/java/org/bukkit/WorldTypeTest.java b/src/test/java/org/bukkit/WorldTypeTest.java new file mode 100644 index 0000000..d31c205 --- /dev/null +++ b/src/test/java/org/bukkit/WorldTypeTest.java @@ -0,0 +1,15 @@ +package org.bukkit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +public class WorldTypeTest { + @Test + public void getByName() { + for (WorldType worldType : WorldType.values()) { + assertThat(WorldType.getByName(worldType.getName()), is(worldType)); + } + } +} diff --git a/src/test/java/org/bukkit/configuration/ConfigurationSectionTest.java b/src/test/java/org/bukkit/configuration/ConfigurationSectionTest.java new file mode 100644 index 0000000..6dab477 --- /dev/null +++ b/src/test/java/org/bukkit/configuration/ConfigurationSectionTest.java @@ -0,0 +1,548 @@ +package org.bukkit.configuration; + +import org.bukkit.Material; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; +import org.junit.Test; +import static org.junit.Assert.*; + +public abstract class ConfigurationSectionTest { + public abstract ConfigurationSection getConfigurationSection(); + + @Test + public void testGetKeys() { + ConfigurationSection section = getConfigurationSection(); + + section.set("key", true); + section.set("subsection.subkey", true); + section.set("subsection.subkey2", true); + section.set("subsection.subsubsection.key", true); + section.set("key2", true); + section.set("42", true); + + assertArrayEquals(new String[] { "key", "subsection", "key2", "42" }, section.getKeys(false).toArray()); + assertArrayEquals(new String[] { "key", "subsection", "subsection.subkey", "subsection.subkey2", "subsection.subsubsection", "subsection.subsubsection.key", "key2", "42" }, section.getKeys(true).toArray()); + assertArrayEquals(new String[] { "subkey", "subkey2", "subsubsection", "subsubsection.key" }, section.getConfigurationSection("subsection").getKeys(true).toArray()); + } + + @Test + public void testGetKeysWithDefaults() { + ConfigurationSection section = getConfigurationSection(); + section.getRoot().options().copyDefaults(true); + + section.set("key", true); + section.addDefault("subsection.subkey", true); + section.addDefault("subsection.subkey2", true); + section.addDefault("subsection.subsubsection.key", true); + section.addDefault("key2", true); + + assertArrayEquals(new String[] { "subsection", "key2", "key" }, section.getKeys(false).toArray()); + assertArrayEquals(new String[] { "subsection", "subsection.subkey", "subsection.subkey2", "subsection.subsubsection", "subsection.subsubsection.key", "key2", "key" }, section.getKeys(true).toArray()); + assertArrayEquals(new String[] { "subkey", "subkey2", "subsubsection", "subsubsection.key" }, section.getConfigurationSection("subsection").getKeys(true).toArray()); + } + + @Test + public void testGetValues() { + ConfigurationSection section = getConfigurationSection(); + + section.set("bool", true); + section.set("subsection.string", "test"); + section.set("subsection.long", Long.MAX_VALUE); + section.set("int", 42); + + Map shallowValues = section.getValues(false); + assertArrayEquals(new String[] { "bool", "subsection", "int" }, shallowValues.keySet().toArray()); + assertArrayEquals(new Object[] { true, section.getConfigurationSection("subsection"), 42 }, shallowValues.values().toArray()); + + Map deepValues = section.getValues(true); + assertArrayEquals(new String[] { "bool", "subsection", "subsection.string", "subsection.long", "int" }, deepValues.keySet().toArray()); + assertArrayEquals(new Object[] { true, section.getConfigurationSection("subsection"), "test", Long.MAX_VALUE, 42 }, deepValues.values().toArray()); + } + + @Test + public void testGetValuesWithDefaults() { + ConfigurationSection section = getConfigurationSection(); + section.getRoot().options().copyDefaults(true); + + section.set("bool", true); + section.set("subsection.string", "test"); + section.addDefault("subsection.long", Long.MAX_VALUE); + section.addDefault("int", 42); + + Map shallowValues = section.getValues(false); + assertArrayEquals(new String[] { "subsection", "int", "bool" }, shallowValues.keySet().toArray()); + assertArrayEquals(new Object[] { section.getConfigurationSection("subsection"), 42, true }, shallowValues.values().toArray()); + + Map deepValues = section.getValues(true); + assertArrayEquals(new String[] { "subsection", "subsection.long", "int", "bool", "subsection.string" }, deepValues.keySet().toArray()); + assertArrayEquals(new Object[] { section.getConfigurationSection("subsection"), Long.MAX_VALUE, 42, true, "test" }, deepValues.values().toArray()); + } + + @Test + public void testContains() { + ConfigurationSection section = getConfigurationSection(); + + section.set("exists", true); + + assertTrue(section.contains("exists")); + assertFalse(section.contains("doesnt-exist")); + } + + @Test + public void testIsSet() { + ConfigurationSection section = getConfigurationSection(); + + section.set("notDefault", true); + section.getRoot().addDefault("default", true); + section.getRoot().addDefault("defaultAndSet", true); + section.set("defaultAndSet", true); + + assertTrue(section.isSet("notDefault")); + assertFalse(section.isSet("default")); + assertTrue(section.isSet("defaultAndSet")); + } + + @Test + public void testGetCurrentPath() { + ConfigurationSection section = getConfigurationSection(); + + assertEquals(section.getName(), section.getCurrentPath()); + } + + @Test + public void testGetName() { + ConfigurationSection section = getConfigurationSection().createSection("subsection"); + + assertEquals("subsection", section.getName()); + assertEquals("", section.getRoot().getName()); + } + + @Test + public void testGetRoot() { + ConfigurationSection section = getConfigurationSection(); + + assertNotNull(section.getRoot()); + assertTrue(section.getRoot().contains(section.getCurrentPath())); + } + + @Test + public void testGetParent() { + ConfigurationSection section = getConfigurationSection(); + ConfigurationSection subsection = section.createSection("subsection"); + + assertEquals(section.getRoot(), section.getParent()); + assertEquals(section, subsection.getParent()); + } + + @Test + public void testGet_String() { + ConfigurationSection section = getConfigurationSection(); + + section.set("exists", "hello world"); + + assertEquals("hello world", section.getString("exists")); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGet_String_Object() { + ConfigurationSection section = getConfigurationSection(); + + section.set("exists", "Set Value"); + + assertEquals("Set Value", section.get("exists", "Default Value")); + assertEquals("Default Value", section.get("doesntExist", "Default Value")); + } + + @Test + public void testSet() { + ConfigurationSection section = getConfigurationSection(); + + section.set("exists", "hello world"); + + assertTrue(section.contains("exists")); + assertTrue(section.isSet("exists")); + assertEquals("hello world", section.get("exists")); + + section.set("exists", null); + + assertFalse(section.contains("exists")); + assertFalse(section.isSet("exists")); + } + + @Test + public void testCreateSection() { + ConfigurationSection section = getConfigurationSection(); + ConfigurationSection subsection = section.createSection("subsection"); + + assertEquals("subsection", subsection.getName()); + } + + @Test + public void testSectionMap() { + ConfigurationSection config = getConfigurationSection(); + Map testMap = new LinkedHashMap(); + + testMap.put("string", "Hello World"); + testMap.put("integer", 15); + + config.createSection("test.path", testMap); + + assertEquals(testMap, config.getConfigurationSection("test.path").getValues(false)); + } + + @Test + public void testGetString_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + String value = "Hello World"; + + section.set(key, value); + + assertEquals(value, section.getString(key)); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetString_String_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + String value = "Hello World"; + String def = "Default Value"; + + section.set(key, value); + + assertEquals(value, section.getString(key, def)); + assertEquals(def, section.getString("doesntExist", def)); + } + + @Test + public void testIsString() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + String value = "Hello World"; + + section.set(key, value); + + assertTrue(section.isString(key)); + assertFalse(section.isString("doesntExist")); + } + + @Test + public void testGetInt_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + int value = Integer.MAX_VALUE; + + section.set(key, value); + + assertEquals(value, section.getInt(key)); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetInt_String_Int() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + int value = Integer.MAX_VALUE; + int def = Integer.MIN_VALUE; + + section.set(key, value); + + assertEquals(value, section.getInt(key, def)); + assertEquals(def, section.getInt("doesntExist", def)); + } + + @Test + public void testIsInt() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + int value = Integer.MAX_VALUE; + + section.set(key, value); + + assertTrue(section.isInt(key)); + assertFalse(section.isInt("doesntExist")); + } + + @Test + public void testGetBoolean_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + boolean value = true; + + section.set(key, value); + + assertEquals(value, section.getBoolean(key)); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetBoolean_String_Boolean() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + boolean value = true; + boolean def = false; + + section.set(key, value); + + assertEquals(value, section.getBoolean(key, def)); + assertEquals(def, section.getBoolean("doesntExist", def)); + } + + @Test + public void testIsBoolean() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + boolean value = true; + + section.set(key, value); + + assertTrue(section.isBoolean(key)); + assertFalse(section.isBoolean("doesntExist")); + } + + @Test + public void testGetDouble_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + double value = Double.MAX_VALUE; + + section.set(key, value); + + assertEquals(value, section.getDouble(key), 1); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetDoubleFromInt() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + double value = 123; + + section.set(key, (int) value); + + assertEquals(value, section.getDouble(key), 1); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetDouble_String_Double() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + double value = Double.MAX_VALUE; + double def = Double.MIN_VALUE; + + section.set(key, value); + + assertEquals(value, section.getDouble(key, def), 1); + assertEquals(def, section.getDouble("doesntExist", def), 1); + } + + @Test + public void testIsDouble() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + double value = Double.MAX_VALUE; + + section.set(key, value); + + assertTrue(section.isDouble(key)); + assertFalse(section.isDouble("doesntExist")); + } + + @Test + public void testGetLong_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + long value = Long.MAX_VALUE; + + section.set(key, value); + + assertEquals(value, section.getLong(key)); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetLong_String_Long() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + long value = Long.MAX_VALUE; + long def = Long.MIN_VALUE; + + section.set(key, value); + + assertEquals(value, section.getLong(key, def)); + assertEquals(def, section.getLong("doesntExist", def)); + } + + @Test + public void testIsLong() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + long value = Long.MAX_VALUE; + + section.set(key, value); + + assertTrue(section.isLong(key)); + assertFalse(section.isLong("doesntExist")); + } + + @Test + public void testGetList_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + Map map = new HashMap(); + + map.put("one", 1); + map.put("two", "two"); + map.put("three", 3.14); + + List value = Arrays.asList("One", "Two", "Three", 4, "5", 6.0, true, "false", map); + + section.set(key, value); + + assertEquals(value, section.getList(key)); + assertEquals(Arrays.asList((Object) "One", "Two", "Three", "4", "5", "6.0", "true", "false"), section.getStringList(key)); + assertEquals(Arrays.asList((Object) 4, 5, 6), section.getIntegerList(key)); + assertEquals(Arrays.asList((Object) true, false), section.getBooleanList(key)); + assertEquals(Arrays.asList((Object) 4.0, 5.0, 6.0), section.getDoubleList(key)); + assertEquals(Arrays.asList((Object) 4.0f, 5.0f, 6.0f), section.getFloatList(key)); + assertEquals(Arrays.asList((Object) 4l, 5l, 6l), section.getLongList(key)); + assertEquals(Arrays.asList((Object) (byte) 4, (byte) 5, (byte) 6), section.getByteList(key)); + assertEquals(Arrays.asList((Object) (short) 4, (short) 5, (short) 6), section.getShortList(key)); + assertEquals(map, section.getMapList(key).get(0)); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetList_String_List() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + List value = Arrays.asList("One", "Two", "Three"); + List def = Arrays.asList("A", "B", "C"); + + section.set(key, value); + + assertEquals(value, section.getList(key, def)); + assertEquals(def, section.getList("doesntExist", def)); + } + + @Test + public void testIsList() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + List value = Arrays.asList("One", "Two", "Three"); + + section.set(key, value); + + assertTrue(section.isList(key)); + assertFalse(section.isList("doesntExist")); + } + + @Test + public void testGetVector_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + Vector value = new Vector(Double.MIN_VALUE, Double.MAX_VALUE, 5); + + section.set(key, value); + + assertEquals(value, section.getVector(key)); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetVector_String_Vector() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + Vector value = new Vector(Double.MIN_VALUE, Double.MAX_VALUE, 5); + Vector def = new Vector(100, Double.MIN_VALUE, Double.MAX_VALUE); + + section.set(key, value); + + assertEquals(value, section.getVector(key, def)); + assertEquals(def, section.getVector("doesntExist", def)); + } + + @Test + public void testIsVector() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + Vector value = new Vector(Double.MIN_VALUE, Double.MAX_VALUE, 5); + + section.set(key, value); + + assertTrue(section.isVector(key)); + assertFalse(section.isVector("doesntExist")); + } + + @Test + public void testGetItemStack_String() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + ItemStack value = new ItemStack(Material.WOOD, 50, (short) 2); + + section.set(key, value); + + assertEquals(value, section.getItemStack(key)); + assertNull(section.getString("doesntExist")); + } + + @Test + public void testGetItemStack_String_ItemStack() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + ItemStack value = new ItemStack(Material.WOOD, 50, (short) 2); + ItemStack def = new ItemStack(Material.STONE, 1); + + section.set(key, value); + + assertEquals(value, section.getItemStack(key, def)); + assertEquals(def, section.getItemStack("doesntExist", def)); + } + + @Test + public void testIsItemStack() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + ItemStack value = new ItemStack(Material.WOOD, 50, (short) 2); + + section.set(key, value); + + assertTrue(section.isItemStack(key)); + assertFalse(section.isItemStack("doesntExist")); + } + + @Test + public void testGetConfigurationSection() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + + ConfigurationSection subsection = section.createSection(key); + + assertEquals(subsection, section.getConfigurationSection(key)); + } + + @Test + public void testIsConfigurationSection() { + ConfigurationSection section = getConfigurationSection(); + String key = "exists"; + + section.createSection(key); + + assertTrue(section.isConfigurationSection(key)); + assertFalse(section.isConfigurationSection("doesntExist")); + } + + public enum TestEnum { + HELLO, + WORLD, + BANANAS + } +} \ No newline at end of file diff --git a/src/test/java/org/bukkit/configuration/ConfigurationTest.java b/src/test/java/org/bukkit/configuration/ConfigurationTest.java new file mode 100644 index 0000000..e187d15 --- /dev/null +++ b/src/test/java/org/bukkit/configuration/ConfigurationTest.java @@ -0,0 +1,156 @@ +package org.bukkit.configuration; + +import java.util.LinkedHashMap; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.bukkit.util.Vector; +import org.junit.Test; +import static org.junit.Assert.*; + +public abstract class ConfigurationTest { + public abstract Configuration getConfig(); + + public Map getTestValues() { + HashMap result = new LinkedHashMap(); + + result.put("integer", Integer.MIN_VALUE); + result.put("string", "String Value"); + result.put("long", Long.MAX_VALUE); + result.put("true-boolean", true); + result.put("false-boolean", false); + result.put("vector", new Vector(12345.67, 64, -12345.6789)); + result.put("list", Arrays.asList(1, 2, 3, 4, 5)); + result.put("42", "The Answer"); + + return result; + } + + /** + * Test of addDefault method, of class Configuration. + */ + @Test + public void testAddDefault() { + Configuration config = getConfig(); + Map values = getTestValues(); + + for (Map.Entry entry : values.entrySet()) { + String path = entry.getKey(); + Object object = entry.getValue(); + + config.addDefault(path, object); + + assertEquals(object, config.get(path)); + assertTrue(config.contains(path)); + assertFalse(config.isSet(path)); + assertTrue(config.getDefaults().isSet(path)); + } + } + + /** + * Test of addDefaults method, of class Configuration. + */ + @Test + public void testAddDefaults_Map() { + Configuration config = getConfig(); + Map values = getTestValues(); + + config.addDefaults(values); + + for (Map.Entry entry : values.entrySet()) { + String path = entry.getKey(); + Object object = entry.getValue(); + + assertEquals(object, config.get(path)); + assertTrue(config.contains(path)); + assertFalse(config.isSet(path)); + assertTrue(config.getDefaults().isSet(path)); + } + } + + /** + * Test of addDefaults method, of class Configuration. + */ + @Test + public void testAddDefaults_Configuration() { + Configuration config = getConfig(); + Map values = getTestValues(); + Configuration defaults = getConfig(); + + for (Map.Entry entry : values.entrySet()) { + defaults.set(entry.getKey(), entry.getValue()); + } + + config.addDefaults(defaults); + + for (Map.Entry entry : values.entrySet()) { + String path = entry.getKey(); + Object object = entry.getValue(); + + assertEquals(object, config.get(path)); + assertTrue(config.contains(path)); + assertFalse(config.isSet(path)); + assertTrue(config.getDefaults().isSet(path)); + } + } + + /** + * Test of setDefaults method, of class Configuration. + */ + @Test + public void testSetDefaults() { + Configuration config = getConfig(); + Map values = getTestValues(); + Configuration defaults = getConfig(); + + for (Map.Entry entry : values.entrySet()) { + defaults.set(entry.getKey(), entry.getValue()); + } + + config.setDefaults(defaults); + + for (Map.Entry entry : values.entrySet()) { + String path = entry.getKey(); + Object object = entry.getValue(); + + assertEquals(object, config.get(path)); + assertTrue(config.contains(path)); + assertFalse(config.isSet(path)); + assertTrue(config.getDefaults().isSet(path)); + } + } + + /** + * Test creation of ConfigurationSection + */ + @Test + public void testCreateSection() { + Configuration config = getConfig(); + + Set set = new HashSet(); + set.add("this"); + set.add("this.test.sub"); + set.add("this.test"); + set.add("this.test.other"); + + config.createSection("this.test.sub"); + config.createSection("this.test.other"); + + assertEquals(set, config.getKeys(true)); + } + + /** + * Test of getDefaults method, of class Configuration. + */ + @Test + public void testGetDefaults() { + Configuration config = getConfig(); + Configuration defaults = getConfig(); + + config.setDefaults(defaults); + + assertEquals(defaults, config.getDefaults()); + } +} \ No newline at end of file diff --git a/src/test/java/org/bukkit/configuration/MemoryConfigurationTest.java b/src/test/java/org/bukkit/configuration/MemoryConfigurationTest.java new file mode 100644 index 0000000..3de0ce9 --- /dev/null +++ b/src/test/java/org/bukkit/configuration/MemoryConfigurationTest.java @@ -0,0 +1,8 @@ +package org.bukkit.configuration; + +public class MemoryConfigurationTest extends ConfigurationTest { + @Override + public Configuration getConfig() { + return new MemoryConfiguration(); + } +} diff --git a/src/test/java/org/bukkit/configuration/MemorySectionTest.java b/src/test/java/org/bukkit/configuration/MemorySectionTest.java new file mode 100644 index 0000000..be7768a --- /dev/null +++ b/src/test/java/org/bukkit/configuration/MemorySectionTest.java @@ -0,0 +1,8 @@ +package org.bukkit.configuration; + +public class MemorySectionTest extends ConfigurationSectionTest { + @Override + public ConfigurationSection getConfigurationSection() { + return new MemoryConfiguration().createSection("section"); + } +} diff --git a/src/test/java/org/bukkit/configuration/file/FileConfigurationTest.java b/src/test/java/org/bukkit/configuration/file/FileConfigurationTest.java new file mode 100644 index 0000000..ce0c2e5 --- /dev/null +++ b/src/test/java/org/bukkit/configuration/file/FileConfigurationTest.java @@ -0,0 +1,209 @@ +package org.bukkit.configuration.file; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.Map; +import org.bukkit.configuration.MemoryConfigurationTest; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import static org.junit.Assert.*; + +public abstract class FileConfigurationTest extends MemoryConfigurationTest { + @Rule + public TemporaryFolder testFolder = new TemporaryFolder(); + + @Override + public abstract FileConfiguration getConfig(); + + public abstract String getTestValuesString(); + + public abstract String getTestHeaderInput(); + + public abstract String getTestHeaderResult(); + + @Test + public void testSave_File() throws Exception { + FileConfiguration config = getConfig(); + File file = testFolder.newFile("test.config"); + + for (Map.Entry entry : getTestValues().entrySet()) { + config.set(entry.getKey(), entry.getValue()); + } + + config.save(file); + + assertTrue(file.isFile()); + } + + @Test + public void testSave_String() throws Exception { + FileConfiguration config = getConfig(); + File file = testFolder.newFile("test.config"); + + for (Map.Entry entry : getTestValues().entrySet()) { + config.set(entry.getKey(), entry.getValue()); + } + + config.save(file.getAbsolutePath()); + + assertTrue(file.isFile()); + } + + @Test + public void testSaveToString() { + FileConfiguration config = getConfig(); + + for (Map.Entry entry : getTestValues().entrySet()) { + config.set(entry.getKey(), entry.getValue()); + } + + String result = config.saveToString(); + String expected = getTestValuesString(); + + assertEquals(expected, result); + } + + @Test + public void testLoad_File() throws Exception { + FileConfiguration config = getConfig(); + File file = testFolder.newFile("test.config"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + String saved = getTestValuesString(); + Map values = getTestValues(); + + try { + writer.write(saved); + } finally { + writer.close(); + } + + config.load(file); + + for (Map.Entry entry : values.entrySet()) { + assertEquals(entry.getValue(), config.get(entry.getKey())); + } + + assertEquals(values.keySet(), config.getKeys(true)); + } + + @Test + public void testLoad_String() throws Exception { + FileConfiguration config = getConfig(); + File file = testFolder.newFile("test.config"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + String saved = getTestValuesString(); + Map values = getTestValues(); + + try { + writer.write(saved); + } finally { + writer.close(); + } + + config.load(file.getAbsolutePath()); + + for (Map.Entry entry : values.entrySet()) { + assertEquals(entry.getValue(), config.get(entry.getKey())); + } + + assertEquals(values.keySet(), config.getKeys(true)); + } + + @Test + public void testLoadFromString() throws Exception { + FileConfiguration config = getConfig(); + Map values = getTestValues(); + String saved = getTestValuesString(); + + config.loadFromString(saved); + + for (Map.Entry entry : values.entrySet()) { + assertEquals(entry.getValue(), config.get(entry.getKey())); + } + + assertEquals(values.keySet(), config.getKeys(true)); + assertEquals(saved, config.saveToString()); + } + + @Test + public void testSaveToStringWithHeader() { + FileConfiguration config = getConfig(); + config.options().header(getTestHeaderInput()); + + for (Map.Entry entry : getTestValues().entrySet()) { + config.set(entry.getKey(), entry.getValue()); + } + + String result = config.saveToString(); + String expected = getTestHeaderResult() + "\n" + getTestValuesString(); + + assertEquals(expected, result); + } + + @Test + public void testParseHeader() throws Exception { + FileConfiguration config = getConfig(); + Map values = getTestValues(); + String saved = getTestValuesString(); + String header = getTestHeaderResult(); + String expected = getTestHeaderInput(); + + config.loadFromString(header + "\n" + saved); + + assertEquals(expected, config.options().header()); + + for (Map.Entry entry : values.entrySet()) { + assertEquals(entry.getValue(), config.get(entry.getKey())); + } + + assertEquals(values.keySet(), config.getKeys(true)); + assertEquals(header + "\n" + saved, config.saveToString()); + } + + @Test + public void testCopyHeader() throws Exception { + FileConfiguration config = getConfig(); + FileConfiguration defaults = getConfig(); + Map values = getTestValues(); + String saved = getTestValuesString(); + String header = getTestHeaderResult(); + String expected = getTestHeaderInput(); + + defaults.loadFromString(header); + config.loadFromString(saved); + config.setDefaults(defaults); + + assertNull(config.options().header()); + assertEquals(expected, defaults.options().header()); + + for (Map.Entry entry : values.entrySet()) { + assertEquals(entry.getValue(), config.get(entry.getKey())); + } + + assertEquals(values.keySet(), config.getKeys(true)); + assertEquals(header + "\n" + saved, config.saveToString()); + + config = getConfig(); + config.loadFromString(getTestHeaderResult() + saved); + assertEquals(getTestHeaderResult() + saved, config.saveToString()); + } + + @Test + public void testReloadEmptyConfig() throws Exception { + FileConfiguration config = getConfig(); + + assertEquals("", config.saveToString()); + + config = getConfig(); + config.loadFromString(""); + + assertEquals("", config.saveToString()); + + config = getConfig(); + config.loadFromString("\n\n"); // Should trim the first newlines of a header + + assertEquals("", config.saveToString()); + } +} diff --git a/src/test/java/org/bukkit/configuration/file/YamlConfigurationTest.java b/src/test/java/org/bukkit/configuration/file/YamlConfigurationTest.java new file mode 100644 index 0000000..aa83af3 --- /dev/null +++ b/src/test/java/org/bukkit/configuration/file/YamlConfigurationTest.java @@ -0,0 +1,56 @@ +package org.bukkit.configuration.file; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class YamlConfigurationTest extends FileConfigurationTest { + + @Override + public YamlConfiguration getConfig() { + return new YamlConfiguration(); + } + + @Override + public String getTestHeaderInput() { + return "This is a sample\nheader.\n\nNewline above should be commented.\n\n"; + } + + @Override + public String getTestHeaderResult() { + return "# This is a sample\n# header.\n# \n# Newline above should be commented.\n\n"; + } + + @Override + public String getTestValuesString() { + return "integer: -2147483648\n" + + "string: String Value\n" + + "long: 9223372036854775807\n" + + "true-boolean: true\n" + + "false-boolean: false\n" + + "vector:\n" + + " ==: Vector\n" + + " x: 12345.67\n" + + " y: 64.0\n" + + " z: -12345.6789\n" + + "list:\n" + + "- 1\n" + + "- 2\n" + + "- 3\n" + + "- 4\n" + + "- 5\n" + + "'42': The Answer\n"; + } + + @Test + public void testSaveToStringWithIndent() { + YamlConfiguration config = getConfig(); + config.options().indent(9); + + config.set("section.key", 1); + + String result = config.saveToString(); + String expected = "section:\n key: 1\n"; + + assertEquals(expected, result); + } +} diff --git a/src/test/java/org/bukkit/conversations/ConversationContextTest.java b/src/test/java/org/bukkit/conversations/ConversationContextTest.java new file mode 100644 index 0000000..dfc462b --- /dev/null +++ b/src/test/java/org/bukkit/conversations/ConversationContextTest.java @@ -0,0 +1,34 @@ +package org.bukkit.conversations; + +import org.junit.Test; +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; + +/** + */ +public class ConversationContextTest { + @Test + public void TestFromWhom() { + Conversable conversable = new FakeConversable(); + ConversationContext context = new ConversationContext(null, conversable, new HashMap()); + assertEquals(conversable, context.getForWhom()); + } + + @Test + public void TestPlugin() { + Conversable conversable = new FakeConversable(); + ConversationContext context = new ConversationContext(null, conversable, new HashMap()); + assertEquals(null, context.getPlugin()); + } + + @Test + public void TestSessionData() { + Conversable conversable = new FakeConversable(); + Map session = new HashMap(); + session.put("key", "value"); + ConversationContext context = new ConversationContext(null, conversable, session); + assertEquals("value", context.getSessionData("key")); + } +} diff --git a/src/test/java/org/bukkit/conversations/ConversationTest.java b/src/test/java/org/bukkit/conversations/ConversationTest.java new file mode 100644 index 0000000..732caab --- /dev/null +++ b/src/test/java/org/bukkit/conversations/ConversationTest.java @@ -0,0 +1,116 @@ +package org.bukkit.conversations; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + */ +public class ConversationTest { + + @Test + public void testBaseConversationFlow() { + FakeConversable forWhom = new FakeConversable(); + Conversation conversation = new Conversation(null, forWhom, new FirstPrompt()); + + // Conversation not yet begun + assertNull(forWhom.lastSentMessage); + assertEquals(conversation.getForWhom(), forWhom); + assertTrue(conversation.isModal()); + + // Begin the conversation + conversation.begin(); + assertEquals("FirstPrompt", forWhom.lastSentMessage); + assertEquals(conversation, forWhom.begunConversation); + + // Send the first input + conversation.acceptInput("FirstInput"); + assertEquals("SecondPrompt", forWhom.lastSentMessage); + assertEquals(conversation, forWhom.abandonedConverstion); + } + + @Test + public void testConversationFactory() { + FakeConversable forWhom = new FakeConversable(); + NullConversationPrefix prefix = new NullConversationPrefix(); + ConversationFactory factory = new ConversationFactory(null) + .withFirstPrompt(new FirstPrompt()) + .withModality(false) + .withPrefix(prefix); + Conversation conversation = factory.buildConversation(forWhom); + + // Conversation not yet begun + assertNull(forWhom.lastSentMessage); + assertEquals(conversation.getForWhom(), forWhom); + assertFalse(conversation.isModal()); + assertEquals(conversation.getPrefix(), prefix); + + // Begin the conversation + conversation.begin(); + assertEquals("FirstPrompt", forWhom.lastSentMessage); + assertEquals(conversation, forWhom.begunConversation); + + // Send the first input + conversation.acceptInput("FirstInput"); + assertEquals("SecondPrompt", forWhom.lastSentMessage); + assertEquals(conversation, forWhom.abandonedConverstion); + } + + @Test + public void testEscapeSequence() { + FakeConversable forWhom = new FakeConversable(); + Conversation conversation = new Conversation(null, forWhom, new FirstPrompt()); + conversation.addConversationCanceller(new ExactMatchConversationCanceller("bananas")); + + // Begin the conversation + conversation.begin(); + assertEquals("FirstPrompt", forWhom.lastSentMessage); + assertEquals(conversation, forWhom.begunConversation); + + // Send the first input + conversation.acceptInput("bananas"); + assertEquals("bananas", forWhom.lastSentMessage); + assertEquals(conversation, forWhom.abandonedConverstion); + } + + @Test + public void testNotPlayer() { + FakeConversable forWhom = new FakeConversable(); + NullConversationPrefix prefix = new NullConversationPrefix(); + ConversationFactory factory = new ConversationFactory(null) + .thatExcludesNonPlayersWithMessage("bye"); + Conversation conversation = factory.buildConversation(forWhom); + + // Begin the conversation + conversation.begin(); + assertEquals("bye", forWhom.lastSentMessage); + assertEquals(conversation, forWhom.begunConversation); + assertEquals(conversation, forWhom.abandonedConverstion); + } + + private class FirstPrompt extends StringPrompt { + + public String getPromptText(ConversationContext context) { + return "FirstPrompt"; + } + + public Prompt acceptInput(ConversationContext context, String input) { + assertEquals("FirstInput", input); + context.setSessionData("data", 10); + return new SecondPrompt(); + } + } + + private class SecondPrompt extends MessagePrompt { + + @Override + protected Prompt getNextPrompt(ConversationContext context) { + return Prompt.END_OF_CONVERSATION; + } + + public String getPromptText(ConversationContext context) { + // Assert that session data passes from one prompt to the next + assertEquals(context.getSessionData("data"), 10); + return "SecondPrompt"; + } + } +} diff --git a/src/test/java/org/bukkit/conversations/FakeConversable.java b/src/test/java/org/bukkit/conversations/FakeConversable.java new file mode 100644 index 0000000..87fb311 --- /dev/null +++ b/src/test/java/org/bukkit/conversations/FakeConversable.java @@ -0,0 +1,105 @@ +package org.bukkit.conversations; + +import org.bukkit.Server; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.Plugin; + +import java.util.Set; + +/** + */ +public class FakeConversable implements Conversable { + public String lastSentMessage; + public Conversation begunConversation; + public Conversation abandonedConverstion; + public ConversationAbandonedEvent abandonedConversationEvent; + + public boolean isConversing() { + return false; + } + + public void acceptConversationInput(String input) { + + } + + public boolean beginConversation(Conversation conversation) { + begunConversation = conversation; + conversation.outputNextPrompt(); + return true; + } + + public void abandonConversation(Conversation conversation) { + abandonedConverstion = conversation; + } + + public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { + abandonedConverstion = conversation; + abandonedConversationEvent = details; + } + + public void sendRawMessage(String message) { + lastSentMessage = message; + } + + public Server getServer() { + return null; + } + + public String getName() { + return null; + } + + public boolean isPermissionSet(String name) { + return false; + } + + public boolean isPermissionSet(Permission perm) { + return false; + } + + public boolean hasPermission(String name) { + return false; + } + + public boolean hasPermission(Permission perm) { + return false; + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + return null; + } + + public PermissionAttachment addAttachment(Plugin plugin) { + return null; + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + return null; + } + + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + return null; + } + + public void removeAttachment(PermissionAttachment attachment) { + + } + + public void recalculatePermissions() { + + } + + public Set getEffectivePermissions() { + return null; + } + + public boolean isOp() { + return false; + } + + public void setOp(boolean value) { + + } +} diff --git a/src/test/java/org/bukkit/conversations/ValidatingPromptTest.java b/src/test/java/org/bukkit/conversations/ValidatingPromptTest.java new file mode 100644 index 0000000..d1c0f42 --- /dev/null +++ b/src/test/java/org/bukkit/conversations/ValidatingPromptTest.java @@ -0,0 +1,115 @@ +package org.bukkit.conversations; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + */ +public class ValidatingPromptTest { + + @Test + public void TestBooleanPrompt() { + TestBooleanPrompt prompt = new TestBooleanPrompt(); + assertTrue(prompt.isInputValid(null, "true")); + assertFalse(prompt.isInputValid(null, "bananas")); + prompt.acceptInput(null, "true"); + assertTrue(prompt.result); + prompt.acceptInput(null, "no"); + assertFalse(prompt.result); + } + + @Test + public void TestFixedSetPrompt() { + TestFixedSetPrompt prompt = new TestFixedSetPrompt("foo", "bar"); + assertTrue(prompt.isInputValid(null, "foo")); + assertFalse(prompt.isInputValid(null, "cheese")); + prompt.acceptInput(null, "foo"); + assertEquals("foo", prompt.result); + } + + @Test + public void TestNumericPrompt() { + TestNumericPrompt prompt = new TestNumericPrompt(); + assertTrue(prompt.isInputValid(null, "1010220")); + assertFalse(prompt.isInputValid(null, "tomato")); + prompt.acceptInput(null, "1010220"); + assertEquals(1010220, prompt.result); + } + + @Test + public void TestRegexPrompt() { + TestRegexPrompt prompt = new TestRegexPrompt("a.c"); + assertTrue(prompt.isInputValid(null, "abc")); + assertTrue(prompt.isInputValid(null, "axc")); + assertFalse(prompt.isInputValid(null, "xyz")); + prompt.acceptInput(null, "abc"); + assertEquals("abc", prompt.result); + } + + //TODO: TestPlayerNamePrompt() + + private class TestBooleanPrompt extends BooleanPrompt { + public boolean result; + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, boolean input) { + result = input; + return null; + } + + public String getPromptText(ConversationContext context) { + return null; + } + } + + private class TestFixedSetPrompt extends FixedSetPrompt { + public String result; + + public TestFixedSetPrompt(String... fixedSet) { + super(fixedSet); + } + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, String input) { + result = input; + return null; + } + + public String getPromptText(ConversationContext context) { + return null; + } + } + + private class TestNumericPrompt extends NumericPrompt { + public Number result; + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, Number input) { + result = input; + return null; + } + + public String getPromptText(ConversationContext context) { + return null; + } + } + + private class TestRegexPrompt extends RegexPrompt { + public String result; + + public TestRegexPrompt(String pattern) { + super(pattern); + } + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, String input) { + result = input; + return null; + } + + public String getPromptText(ConversationContext context) { + return null; + } + } +} diff --git a/src/test/java/org/bukkit/event/PlayerChatTabCompleteEventTest.java b/src/test/java/org/bukkit/event/PlayerChatTabCompleteEventTest.java new file mode 100644 index 0000000..619bf30 --- /dev/null +++ b/src/test/java/org/bukkit/event/PlayerChatTabCompleteEventTest.java @@ -0,0 +1,28 @@ +package org.bukkit.event; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.bukkit.event.player.PlayerChatTabCompleteEvent; +import org.bukkit.plugin.messaging.TestPlayer; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; + +public class PlayerChatTabCompleteEventTest { + + @Test + public void testGetLastToken() { + assertThat(getToken("Hello everyone!"), is("everyone!")); + assertThat(getToken(" welcome to the show..."), is("show...")); + assertThat(getToken("The whitespace is here "), is("")); + assertThat(getToken("Too much whitespace is here "), is("")); + assertThat(getToken("The_whitespace_is_missing"), is("The_whitespace_is_missing")); + assertThat(getToken(""), is("")); + assertThat(getToken(" "), is("")); + } + + private String getToken(String message) { + return new PlayerChatTabCompleteEvent(TestPlayer.getInstance(), message, ImmutableList.of()).getLastToken(); + } +} diff --git a/src/test/java/org/bukkit/event/TestEvent.java b/src/test/java/org/bukkit/event/TestEvent.java new file mode 100644 index 0000000..25904f5 --- /dev/null +++ b/src/test/java/org/bukkit/event/TestEvent.java @@ -0,0 +1,19 @@ +package org.bukkit.event; + + +public class TestEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + + public TestEvent(boolean async) { + super(async); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/src/test/java/org/bukkit/metadata/FixedMetadataValueTest.java b/src/test/java/org/bukkit/metadata/FixedMetadataValueTest.java new file mode 100644 index 0000000..5583b27 --- /dev/null +++ b/src/test/java/org/bukkit/metadata/FixedMetadataValueTest.java @@ -0,0 +1,42 @@ +package org.bukkit.metadata; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.TestPlugin; +import org.junit.Test; + +public class FixedMetadataValueTest { + private Plugin plugin = new TestPlugin("X"); + private FixedMetadataValue subject; + + @Test + public void testBasic() { + subject = new FixedMetadataValue(plugin, new Integer(50)); + assertSame(plugin, subject.getOwningPlugin()); + assertEquals(new Integer(50), subject.value()); + } + + @Test + public void testNumberTypes() { + subject = new FixedMetadataValue(plugin, new Integer(5)); + assertEquals(new Integer(5), subject.value()); + assertEquals(5, subject.asInt()); + assertEquals(true, subject.asBoolean()); + assertEquals(5, subject.asByte()); + assertEquals(5.0, subject.asFloat(), 0.1e-8); + assertEquals(5.0D, subject.asDouble(), 0.1e-8D); + assertEquals(5L, subject.asLong()); + assertEquals(5, subject.asShort()); + assertEquals("5", subject.asString()); + } + + @Test + public void testInvalidateDoesNothing() { + Object o = new Object(); + subject = new FixedMetadataValue(plugin, o); + subject.invalidate(); + assertSame(o, subject.value()); + } +} diff --git a/src/test/java/org/bukkit/metadata/LazyMetadataValueTest.java b/src/test/java/org/bukkit/metadata/LazyMetadataValueTest.java new file mode 100644 index 0000000..a3172db --- /dev/null +++ b/src/test/java/org/bukkit/metadata/LazyMetadataValueTest.java @@ -0,0 +1,135 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.TestPlugin; +import org.junit.Test; + +import java.util.concurrent.Callable; + +import static org.junit.Assert.*; + +public class LazyMetadataValueTest { + private LazyMetadataValue subject; + private TestPlugin plugin = new TestPlugin("x"); + + @Test + public void testLazyInt() { + int value = 10; + subject = makeSimpleCallable(value); + + assertEquals(value, subject.value()); + } + + @Test + public void testLazyDouble() { + double value = 10.5; + subject = makeSimpleCallable(value); + + assertEquals(value, (Double)subject.value(), 0.01); + } + + @Test + public void testLazyString() { + String value = "TEN"; + subject = makeSimpleCallable(value); + + assertEquals(value, subject.value()); + } + + @Test + public void testLazyBoolean() { + boolean value = false; + subject = makeSimpleCallable(value); + + assertEquals(value, subject.value()); + } + + @Test(expected=MetadataEvaluationException.class) + public void testEvalException() { + subject = new LazyMetadataValue(plugin, LazyMetadataValue.CacheStrategy.CACHE_AFTER_FIRST_EVAL, new Callable() { + public Object call() throws Exception { + throw new RuntimeException("Gotcha!"); + } + }); + subject.value(); + } + + @Test + public void testCacheStrategyCacheAfterFirstEval() { + final Counter counter = new Counter(); + final int value = 10; + subject = new LazyMetadataValue(plugin, LazyMetadataValue.CacheStrategy.CACHE_AFTER_FIRST_EVAL, new Callable() { + public Object call() throws Exception { + counter.increment(); + return value; + } + }); + + subject.value(); + subject.value(); + assertEquals(value, subject.value()); + assertEquals(1, counter.value()); + + subject.invalidate(); + subject.value(); + assertEquals(2, counter.value()); + } + + @Test + public void testCacheStrategyNeverCache() { + final Counter counter = new Counter(); + final int value = 10; + subject = new LazyMetadataValue(plugin, LazyMetadataValue.CacheStrategy.NEVER_CACHE, new Callable() { + public Object call() throws Exception { + counter.increment(); + return value; + } + }); + + subject.value(); + subject.value(); + assertEquals(value, subject.value()); + assertEquals(3, counter.value()); + } + + @Test + public void testCacheStrategyEternally() { + final Counter counter = new Counter(); + final int value = 10; + subject = new LazyMetadataValue(plugin, LazyMetadataValue.CacheStrategy.CACHE_ETERNALLY, new Callable() { + public Object call() throws Exception { + counter.increment(); + return value; + } + }); + + subject.value(); + subject.value(); + assertEquals(value, subject.value()); + assertEquals(1, counter.value()); + + subject.invalidate(); + subject.value(); + assertEquals(value, subject.value()); + assertEquals(1, counter.value()); + } + + private LazyMetadataValue makeSimpleCallable(final Object value) { + return new LazyMetadataValue(plugin, new Callable() { + public Object call() throws Exception { + return value; + } + }); + } + + private class Counter { + private int c = 0; + + public void increment() { + c++; + } + + public int value() { + return c; + } + } +} diff --git a/src/test/java/org/bukkit/metadata/MetadataConversionTest.java b/src/test/java/org/bukkit/metadata/MetadataConversionTest.java new file mode 100644 index 0000000..a595cc8 --- /dev/null +++ b/src/test/java/org/bukkit/metadata/MetadataConversionTest.java @@ -0,0 +1,103 @@ +// Copyright (C) 2011 Ryan Michela +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.TestPlugin; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + */ +public class MetadataConversionTest { + private Plugin plugin = new TestPlugin("x"); + private FixedMetadataValue subject; + + private void setSubject(Object value) { + subject = new FixedMetadataValue(plugin, value); + } + + @Test + public void testFromInt() { + setSubject(10); + + assertEquals(10, subject.asInt()); + assertEquals(10, subject.asFloat(), 0.000001); + assertEquals(10, subject.asDouble(), 0.000001); + assertEquals(10, subject.asLong()); + assertEquals(10, subject.asShort()); + assertEquals(10, subject.asByte()); + assertEquals(true, subject.asBoolean()); + assertEquals("10", subject.asString()); + } + + @Test + public void testFromFloat() { + setSubject(10.5); + + assertEquals(10, subject.asInt()); + assertEquals(10.5, subject.asFloat(), 0.000001); + assertEquals(10.5, subject.asDouble(), 0.000001); + assertEquals(10, subject.asLong()); + assertEquals(10, subject.asShort()); + assertEquals(10, subject.asByte()); + assertEquals(true, subject.asBoolean()); + assertEquals("10.5", subject.asString()); + } + + @Test + public void testFromNumericString() { + setSubject("10"); + + assertEquals(10, subject.asInt()); + assertEquals(10, subject.asFloat(), 0.000001); + assertEquals(10, subject.asDouble(), 0.000001); + assertEquals(10, subject.asLong()); + assertEquals(10, subject.asShort()); + assertEquals(10, subject.asByte()); + assertEquals(false, subject.asBoolean()); + assertEquals("10", subject.asString()); + } + + @Test + public void testFromNonNumericString() { + setSubject("true"); + + assertEquals(0, subject.asInt()); + assertEquals(0, subject.asFloat(), 0.000001); + assertEquals(0, subject.asDouble(), 0.000001); + assertEquals(0, subject.asLong()); + assertEquals(0, subject.asShort()); + assertEquals(0, subject.asByte()); + assertEquals(true, subject.asBoolean()); + assertEquals("true", subject.asString()); + } + + @Test + public void testFromNull() { + setSubject(null); + + assertEquals(0, subject.asInt()); + assertEquals(0, subject.asFloat(), 0.000001); + assertEquals(0, subject.asDouble(), 0.000001); + assertEquals(0, subject.asLong()); + assertEquals(0, subject.asShort()); + assertEquals(0, subject.asByte()); + assertEquals(false, subject.asBoolean()); + assertEquals("", subject.asString()); + } +} diff --git a/src/test/java/org/bukkit/metadata/MetadataStoreTest.java b/src/test/java/org/bukkit/metadata/MetadataStoreTest.java new file mode 100644 index 0000000..30f0368 --- /dev/null +++ b/src/test/java/org/bukkit/metadata/MetadataStoreTest.java @@ -0,0 +1,143 @@ +package org.bukkit.metadata; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import java.util.concurrent.Callable; + +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.TestPlugin; +import org.junit.Test; + +public class MetadataStoreTest { + private Plugin pluginX = new TestPlugin("x"); + private Plugin pluginY = new TestPlugin("y"); + + StringMetadataStore subject = new StringMetadataStore(); + + @Test + public void testMetadataStore() { + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); + + assertTrue(subject.hasMetadata("subject", "key")); + List values = subject.getMetadata("subject", "key"); + assertEquals(10, values.get(0).value()); + } + + @Test + public void testMetadataNotPresent() { + assertFalse(subject.hasMetadata("subject", "key")); + List values = subject.getMetadata("subject", "key"); + assertTrue(values.isEmpty()); + } + + @Test + public void testInvalidateAll() { + final Counter counter = new Counter(); + + subject.setMetadata("subject", "key", new LazyMetadataValue(pluginX, new Callable() { + public Object call() throws Exception { + counter.increment(); + return 10; + } + })); + + assertTrue(subject.hasMetadata("subject", "key")); + subject.getMetadata("subject", "key").get(0).value(); + subject.invalidateAll(pluginX); + subject.getMetadata("subject", "key").get(0).value(); + assertEquals(2, counter.value()); + } + + @Test + public void testInvalidateAllButActuallyNothing() { + final Counter counter = new Counter(); + + subject.setMetadata("subject", "key", new LazyMetadataValue(pluginX, new Callable() { + public Object call() throws Exception { + counter.increment(); + return 10; + } + })); + + assertTrue(subject.hasMetadata("subject", "key")); + subject.getMetadata("subject", "key").get(0).value(); + subject.invalidateAll(pluginY); + subject.getMetadata("subject", "key").get(0).value(); + assertEquals(1, counter.value()); + } + + @Test + public void testMetadataReplace() { + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginY, 10)); + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 20)); + + for (MetadataValue mv : subject.getMetadata("subject", "key")) { + if (mv.getOwningPlugin().equals(pluginX)) { + assertEquals(20, mv.value()); + } + if (mv.getOwningPlugin().equals(pluginY)) { + assertEquals(10, mv.value()); + } + } + } + + @Test + public void testMetadataRemove() { + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginY, 20)); + subject.removeMetadata("subject", "key", pluginX); + + assertTrue(subject.hasMetadata("subject", "key")); + assertEquals(1, subject.getMetadata("subject", "key").size()); + assertEquals(20, subject.getMetadata("subject", "key").get(0).value()); + } + + @Test + public void testMetadataRemoveLast() { + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); + subject.removeMetadata("subject", "key", pluginX); + + assertFalse(subject.hasMetadata("subject", "key")); + assertEquals(0, subject.getMetadata("subject", "key").size()); + } + + @Test + public void testMetadataRemoveForNonExistingPlugin() { + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); + subject.removeMetadata("subject", "key", pluginY); + + assertTrue(subject.hasMetadata("subject", "key")); + assertEquals(1, subject.getMetadata("subject", "key").size()); + assertEquals(10, subject.getMetadata("subject", "key").get(0).value()); + } + + @Test + public void testHasMetadata() { + subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); + assertTrue(subject.hasMetadata("subject", "key")); + assertFalse(subject.hasMetadata("subject", "otherKey")); + } + + private class StringMetadataStore extends MetadataStoreBase implements MetadataStore { + @Override + protected String disambiguate(String subject, String metadataKey) { + return subject + ":" + metadataKey; + } + } + + private class Counter { + int c = 0; + + public void increment() { + c++; + } + + public int value() { + return c; + } + } +} diff --git a/src/test/java/org/bukkit/metadata/MetadataValueAdapterTest.java b/src/test/java/org/bukkit/metadata/MetadataValueAdapterTest.java new file mode 100644 index 0000000..7d8a17f --- /dev/null +++ b/src/test/java/org/bukkit/metadata/MetadataValueAdapterTest.java @@ -0,0 +1,97 @@ +package org.bukkit.metadata; + +import static org.junit.Assert.assertEquals; + +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.TestPlugin; +import org.junit.Test; + +public class MetadataValueAdapterTest { + private TestPlugin plugin = new TestPlugin("x"); + + @Test + public void testAdapterBasics() { + IncrementingMetaValue mv = new IncrementingMetaValue(plugin); + // check getOwningPlugin + assertEquals(mv.getOwningPlugin(), this.plugin); + + // Check value-getting and invalidation. + assertEquals(new Integer(1), mv.value()); + assertEquals(new Integer(2), mv.value()); + mv.invalidate(); + assertEquals(new Integer(1), mv.value()); + } + + @Test + public void testAdapterConversions() { + IncrementingMetaValue mv = new IncrementingMetaValue(plugin); + + assertEquals(1, mv.asInt()); + assertEquals(2L, mv.asLong()); + assertEquals(3.0, mv.asFloat(), 0.001); + assertEquals(4, mv.asByte()); + assertEquals(5.0, mv.asDouble(), 0.001); + assertEquals(6, mv.asShort()); + assertEquals("7", mv.asString()); + } + + /** Boolean conversion is non-trivial, we want to test it thoroughly. */ + @Test + public void testBooleanConversion() { + // null is False. + assertEquals(false, simpleValue(null).asBoolean()); + + // String to boolean. + assertEquals(true, simpleValue("True").asBoolean()); + assertEquals(true, simpleValue("TRUE").asBoolean()); + assertEquals(false, simpleValue("false").asBoolean()); + + // Number to boolean. + assertEquals(true, simpleValue(1).asBoolean()); + assertEquals(true, simpleValue(5.0).asBoolean()); + assertEquals(false, simpleValue(0).asBoolean()); + assertEquals(false, simpleValue(0.1).asBoolean()); + + // Boolean as boolean, of course. + assertEquals(true, simpleValue(Boolean.TRUE).asBoolean()); + assertEquals(false, simpleValue(Boolean.FALSE).asBoolean()); + + // any object that is not null and not a Boolean, String, or Number is true. + assertEquals(true, simpleValue(new Object()).asBoolean()); + } + + /** Test String conversions return an empty string when given null. */ + @Test + public void testStringConversionNull() { + assertEquals("", simpleValue(null).asString()); + } + + /** Get a fixed value MetadataValue. */ + private MetadataValue simpleValue(Object value) { + return new FixedMetadataValue(plugin, value); + } + + /** + * A sample non-trivial MetadataValueAdapter implementation. + * + * The rationale for implementing an incrementing value is to have a value + * which changes with every call to value(). This is important for testing + * because we want to make sure all the tested conversions are calling the + * value() method exactly once and no caching is going on. + */ + class IncrementingMetaValue extends MetadataValueAdapter { + private int internalValue = 0; + + protected IncrementingMetaValue(Plugin owningPlugin) { + super(owningPlugin); + } + + public Object value() { + return ++internalValue; + } + + public void invalidate() { + internalValue = 0; + } + } +} diff --git a/src/test/java/org/bukkit/plugin/PluginManagerTest.java b/src/test/java/org/bukkit/plugin/PluginManagerTest.java new file mode 100644 index 0000000..6b86128 --- /dev/null +++ b/src/test/java/org/bukkit/plugin/PluginManagerTest.java @@ -0,0 +1,176 @@ +package org.bukkit.plugin; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import org.bukkit.TestServer; +import org.bukkit.event.Event; +import org.bukkit.event.TestEvent; +import org.bukkit.permissions.Permission; + +import org.junit.After; +import org.junit.Test; + +public class PluginManagerTest { + private class MutableObject { + volatile Object value = null; + } + + private static final PluginManager pm = TestServer.getInstance().getPluginManager(); + + private final MutableObject store = new MutableObject(); + + @Test + public void testAsyncSameThread() { + final Event event = new TestEvent(true); + try { + pm.callEvent(event); + } catch (IllegalStateException ex) { + assertThat(event.getEventName() + " cannot be triggered asynchronously from primary server thread.", is(ex.getMessage())); + return; + } + throw new IllegalStateException("No exception thrown"); + } + + @Test + public void testSyncSameThread() { + final Event event = new TestEvent(false); + pm.callEvent(event); + } + + @Test + public void testAsyncLocked() throws InterruptedException { + final Event event = new TestEvent(true); + Thread secondThread = new Thread( + new Runnable() { + public void run() { + try { + synchronized (pm) { + pm.callEvent(event); + } + } catch (Throwable ex) { + store.value = ex; + } + } + } + ); + secondThread.start(); + secondThread.join(); + assertThat(store.value, is(instanceOf(IllegalStateException.class))); + assertThat(event.getEventName() + " cannot be triggered asynchronously from inside synchronized code.", is(((Throwable) store.value).getMessage())); + } + + @Test + public void testAsyncUnlocked() throws InterruptedException { + final Event event = new TestEvent(true); + Thread secondThread = new Thread( + new Runnable() { + public void run() { + try { + pm.callEvent(event); + } catch (Throwable ex) { + store.value = ex; + } + }}); + secondThread.start(); + secondThread.join(); + if (store.value != null) { + throw new RuntimeException((Throwable) store.value); + } + } + + @Test + public void testSyncUnlocked() throws InterruptedException { + final Event event = new TestEvent(false); + Thread secondThread = new Thread( + new Runnable() { + public void run() { + try { + pm.callEvent(event); + } catch (Throwable ex) { + store.value = ex; + } + } + } + ); + secondThread.start(); + secondThread.join(); + if (store.value != null) { + throw new RuntimeException((Throwable) store.value); + } + } + + @Test + public void testSyncLocked() throws InterruptedException { + final Event event = new TestEvent(false); + Thread secondThread = new Thread( + new Runnable() { + public void run() { + try { + synchronized (pm) { + pm.callEvent(event); + } + } catch (Throwable ex) { + store.value = ex; + } + } + } + ); + secondThread.start(); + secondThread.join(); + if (store.value != null) { + throw new RuntimeException((Throwable) store.value); + } + } + + @Test + public void testRemovePermissionByNameLower() { + this.testRemovePermissionByName("lower"); + } + + @Test + public void testRemovePermissionByNameUpper() { + this.testRemovePermissionByName("UPPER"); + } + + @Test + public void testRemovePermissionByNameCamel() { + this.testRemovePermissionByName("CaMeL"); + } + + public void testRemovePermissionByPermissionLower() { + this.testRemovePermissionByPermission("lower"); + } + + @Test + public void testRemovePermissionByPermissionUpper() { + this.testRemovePermissionByPermission("UPPER"); + } + + @Test + public void testRemovePermissionByPermissionCamel() { + this.testRemovePermissionByPermission("CaMeL"); + } + + private void testRemovePermissionByName(final String name) { + final Permission perm = new Permission(name); + pm.addPermission(perm); + assertThat("Permission \"" + name + "\" was not added", pm.getPermission(name), is(perm)); + pm.removePermission(name); + assertThat("Permission \"" + name + "\" was not removed", pm.getPermission(name), is(nullValue())); + } + + private void testRemovePermissionByPermission(final String name) { + final Permission perm = new Permission(name); + pm.addPermission(perm); + assertThat("Permission \"" + name + "\" was not added", pm.getPermission(name), is(perm)); + pm.removePermission(perm); + assertThat("Permission \"" + name + "\" was not removed", pm.getPermission(name), is(nullValue())); + } + + @After + public void tearDown() { + pm.clearPlugins(); + assertThat(pm.getPermissions(), is(empty())); + } +} diff --git a/src/test/java/org/bukkit/plugin/TestPlugin.java b/src/test/java/org/bukkit/plugin/TestPlugin.java new file mode 100644 index 0000000..7e09892 --- /dev/null +++ b/src/test/java/org/bukkit/plugin/TestPlugin.java @@ -0,0 +1,111 @@ +package org.bukkit.plugin; + +import java.io.File; +import java.io.InputStream; +import java.util.List; + +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.generator.ChunkGenerator; + +import com.avaje.ebean.EbeanServer; + +public class TestPlugin extends PluginBase { + private boolean enabled = true; + + final private String pluginName; + + public TestPlugin(String pluginName) { + this.pluginName = pluginName; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public File getDataFolder() { + throw new UnsupportedOperationException("Not supported."); + } + + public PluginDescriptionFile getDescription() { + return new PluginDescriptionFile(pluginName, "1.0", "test.test"); + } + + public FileConfiguration getConfig() { + throw new UnsupportedOperationException("Not supported."); + } + + public InputStream getResource(String filename) { + throw new UnsupportedOperationException("Not supported."); + } + + public void saveConfig() { + throw new UnsupportedOperationException("Not supported."); + } + + public void saveDefaultConfig() { + throw new UnsupportedOperationException("Not supported."); + } + + public void saveResource(String resourcePath, boolean replace) { + throw new UnsupportedOperationException("Not supported."); + } + + public void reloadConfig() { + throw new UnsupportedOperationException("Not supported."); + } + + public PluginLogger getLogger() { + throw new UnsupportedOperationException("Not supported."); + } + + public PluginLoader getPluginLoader() { + throw new UnsupportedOperationException("Not supported."); + } + + public Server getServer() { + throw new UnsupportedOperationException("Not supported."); + } + + public boolean isEnabled() { + return enabled; + } + + public void onDisable() { + throw new UnsupportedOperationException("Not supported."); + } + + public void onLoad() { + throw new UnsupportedOperationException("Not supported."); + } + + public void onEnable() { + throw new UnsupportedOperationException("Not supported."); + } + + public boolean isNaggable() { + throw new UnsupportedOperationException("Not supported."); + } + + public void setNaggable(boolean canNag) { + throw new UnsupportedOperationException("Not supported."); + } + + public EbeanServer getDatabase() { + throw new UnsupportedOperationException("Not supported."); + } + + public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { + throw new UnsupportedOperationException("Not supported."); + } + + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + throw new UnsupportedOperationException("Not supported."); + } + + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + throw new UnsupportedOperationException("Not supported."); + } +} diff --git a/src/test/java/org/bukkit/plugin/TimedRegisteredListenerTest.java b/src/test/java/org/bukkit/plugin/TimedRegisteredListenerTest.java new file mode 100644 index 0000000..b206b1f --- /dev/null +++ b/src/test/java/org/bukkit/plugin/TimedRegisteredListenerTest.java @@ -0,0 +1,56 @@ +package org.bukkit.plugin; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.player.PlayerEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.junit.Test; + +public class TimedRegisteredListenerTest { + + @Test + public void testEventClass() throws EventException { + Listener listener = new Listener() {}; + EventExecutor executor = new EventExecutor() { + public void execute(Listener listener, Event event) {} + }; + TestPlugin plugin = new TestPlugin("Test"); + + PlayerInteractEvent interactEvent = new PlayerInteractEvent(null, null, null, null, null); + PlayerMoveEvent moveEvent = new PlayerMoveEvent(null, null, null); + BlockBreakEvent breakEvent = new BlockBreakEvent(null, null); + + TimedRegisteredListener trl = new TimedRegisteredListener(listener, executor, EventPriority.NORMAL, plugin, false); + + // Ensure that the correct event type is reported for a single event + trl.callEvent(interactEvent); + assertThat(trl.getEventClass(), is((Object) PlayerInteractEvent.class)); + // Ensure that no superclass is used in lieu of the actual event, after two identical event types + trl.callEvent(interactEvent); + assertThat(trl.getEventClass(), is((Object) PlayerInteractEvent.class)); + // Ensure that the closest superclass of the two events is chosen + trl.callEvent(moveEvent); + assertThat(trl.getEventClass(), is((Object) PlayerEvent.class)); + // As above, so below + trl.callEvent(breakEvent); + assertThat(trl.getEventClass(), is((Object) Event.class)); + // In the name of being thorough, check that it never travels down the hierarchy again. + trl.callEvent(breakEvent); + assertThat(trl.getEventClass(), is((Object) Event.class)); + + trl = new TimedRegisteredListener(listener, executor, EventPriority.NORMAL, plugin, false); + + trl.callEvent(breakEvent); + assertThat(trl.getEventClass(), is((Object) BlockBreakEvent.class)); + // Test moving up the class hierarchy by more than one class at a time + trl.callEvent(moveEvent); + assertThat(trl.getEventClass(), is((Object) Event.class)); + } +} diff --git a/src/test/java/org/bukkit/plugin/messaging/StandardMessengerTest.java b/src/test/java/org/bukkit/plugin/messaging/StandardMessengerTest.java new file mode 100644 index 0000000..644e6d1 --- /dev/null +++ b/src/test/java/org/bukkit/plugin/messaging/StandardMessengerTest.java @@ -0,0 +1,289 @@ +package org.bukkit.plugin.messaging; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.TestPlugin; +import java.util.Collection; +import org.junit.Test; +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; + +public class StandardMessengerTest { + public StandardMessenger getMessenger() { + return new StandardMessenger(); + } + + private int count = 0; + public TestPlugin getPlugin() { + return new TestPlugin("" + count++); + } + + @Test + public void testIsReservedChannel() { + Messenger messenger = getMessenger(); + + assertTrue(messenger.isReservedChannel("REGISTER")); + assertFalse(messenger.isReservedChannel("register")); + assertTrue(messenger.isReservedChannel("UNREGISTER")); + assertFalse(messenger.isReservedChannel("unregister")); + assertFalse(messenger.isReservedChannel("notReserved")); + } + + @Test + public void testRegisterAndUnregisterOutgoingPluginChannel() { + Messenger messenger = getMessenger(); + TestPlugin plugin = getPlugin(); + + assertFalse(messenger.isOutgoingChannelRegistered(plugin, "foo")); + messenger.registerOutgoingPluginChannel(plugin, "foo"); + assertTrue(messenger.isOutgoingChannelRegistered(plugin, "foo")); + assertFalse(messenger.isOutgoingChannelRegistered(plugin, "bar")); + + messenger.unregisterOutgoingPluginChannel(plugin, "foo"); + assertFalse(messenger.isOutgoingChannelRegistered(plugin, "foo")); + } + + @Test(expected = ReservedChannelException.class) + public void testReservedOutgoingRegistration() { + Messenger messenger = getMessenger(); + TestPlugin plugin = getPlugin(); + + messenger.registerOutgoingPluginChannel(plugin, "REGISTER"); + } + + @Test + public void testUnregisterOutgoingPluginChannel_Plugin() { + Messenger messenger = getMessenger(); + TestPlugin plugin = getPlugin(); + + assertFalse(messenger.isOutgoingChannelRegistered(plugin, "foo")); + messenger.registerOutgoingPluginChannel(plugin, "foo"); + messenger.registerOutgoingPluginChannel(plugin, "bar"); + assertTrue(messenger.isOutgoingChannelRegistered(plugin, "foo")); + assertTrue(messenger.isOutgoingChannelRegistered(plugin, "bar")); + + messenger.unregisterOutgoingPluginChannel(plugin); + assertFalse(messenger.isOutgoingChannelRegistered(plugin, "foo")); + assertFalse(messenger.isOutgoingChannelRegistered(plugin, "bar")); + } + + @Test + public void testRegisterIncomingPluginChannel() { + Messenger messenger = getMessenger(); + TestPlugin plugin = getPlugin(); + TestMessageListener listener = new TestMessageListener("foo", "bar".getBytes()); + Player player = TestPlayer.getInstance(); + PluginMessageListenerRegistration registration = messenger.registerIncomingPluginChannel(plugin, "foo", listener); + + assertTrue(registration.isValid()); + assertTrue(messenger.isIncomingChannelRegistered(plugin, "foo")); + messenger.dispatchIncomingMessage(player, "foo", "bar".getBytes()); + assertTrue(listener.hasReceived()); + + messenger.unregisterIncomingPluginChannel(plugin, "foo", listener); + listener.reset(); + + assertFalse(registration.isValid()); + assertFalse(messenger.isIncomingChannelRegistered(plugin, "foo")); + messenger.dispatchIncomingMessage(player, "foo", "bar".getBytes()); + assertFalse(listener.hasReceived()); + } + + @Test(expected = ReservedChannelException.class) + public void testReservedIncomingRegistration() { + Messenger messenger = getMessenger(); + TestPlugin plugin = getPlugin(); + + messenger.registerIncomingPluginChannel(plugin, "REGISTER", new TestMessageListener("foo", "bar".getBytes())); + } + + @Test(expected = IllegalArgumentException.class) + public void testDuplicateIncomingRegistration() { + Messenger messenger = getMessenger(); + TestPlugin plugin = getPlugin(); + TestMessageListener listener = new TestMessageListener("foo", "bar".getBytes()); + + messenger.registerIncomingPluginChannel(plugin, "baz", listener); + messenger.registerIncomingPluginChannel(plugin, "baz", listener); + } + + @Test + public void testUnregisterIncomingPluginChannel_Plugin_String() { + Messenger messenger = getMessenger(); + TestPlugin plugin = getPlugin(); + TestMessageListener listener1 = new TestMessageListener("foo", "bar".getBytes()); + TestMessageListener listener2 = new TestMessageListener("baz", "qux".getBytes()); + Player player = TestPlayer.getInstance(); + PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin, "foo", listener1); + PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin, "baz", listener2); + + assertTrue(registration1.isValid()); + assertTrue(registration2.isValid()); + messenger.dispatchIncomingMessage(player, "foo", "bar".getBytes()); + messenger.dispatchIncomingMessage(player, "baz", "qux".getBytes()); + assertTrue(listener1.hasReceived()); + assertTrue(listener2.hasReceived()); + + messenger.unregisterIncomingPluginChannel(plugin, "foo"); + listener1.reset(); + listener2.reset(); + + assertFalse(registration1.isValid()); + assertTrue(registration2.isValid()); + messenger.dispatchIncomingMessage(player, "foo", "bar".getBytes()); + messenger.dispatchIncomingMessage(player, "baz", "qux".getBytes()); + assertFalse(listener1.hasReceived()); + assertTrue(listener2.hasReceived()); + } + + @Test + public void testUnregisterIncomingPluginChannel_Plugin() { + Messenger messenger = getMessenger(); + TestPlugin plugin = getPlugin(); + TestMessageListener listener1 = new TestMessageListener("foo", "bar".getBytes()); + TestMessageListener listener2 = new TestMessageListener("baz", "qux".getBytes()); + Player player = TestPlayer.getInstance(); + PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin, "foo", listener1); + PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin, "baz", listener2); + + assertTrue(registration1.isValid()); + assertTrue(registration2.isValid()); + messenger.dispatchIncomingMessage(player, "foo", "bar".getBytes()); + messenger.dispatchIncomingMessage(player, "baz", "qux".getBytes()); + assertTrue(listener1.hasReceived()); + assertTrue(listener2.hasReceived()); + + messenger.unregisterIncomingPluginChannel(plugin); + listener1.reset(); + listener2.reset(); + + assertFalse(registration1.isValid()); + assertFalse(registration2.isValid()); + messenger.dispatchIncomingMessage(player, "foo", "bar".getBytes()); + messenger.dispatchIncomingMessage(player, "baz", "qux".getBytes()); + assertFalse(listener1.hasReceived()); + assertFalse(listener2.hasReceived()); + } + + @Test + public void testGetOutgoingChannels() { + Messenger messenger = getMessenger(); + TestPlugin plugin1 = getPlugin(); + TestPlugin plugin2 = getPlugin(); + + assertEquals(messenger.getOutgoingChannels()); + + messenger.registerOutgoingPluginChannel(plugin1, "foo"); + messenger.registerOutgoingPluginChannel(plugin1, "bar"); + messenger.registerOutgoingPluginChannel(plugin2, "baz"); + messenger.registerOutgoingPluginChannel(plugin2, "baz"); + + assertEquals(messenger.getOutgoingChannels(), "foo", "bar", "baz"); + } + + @Test + public void testGetOutgoingChannels_Plugin() { + Messenger messenger = getMessenger(); + TestPlugin plugin1 = getPlugin(); + TestPlugin plugin2 = getPlugin(); + TestPlugin plugin3 = getPlugin(); + + messenger.registerOutgoingPluginChannel(plugin1, "foo"); + messenger.registerOutgoingPluginChannel(plugin1, "bar"); + messenger.registerOutgoingPluginChannel(plugin2, "baz"); + messenger.registerOutgoingPluginChannel(plugin2, "qux"); + + assertEquals(messenger.getOutgoingChannels(plugin1), "foo", "bar"); + assertEquals(messenger.getOutgoingChannels(plugin2), "baz", "qux"); + assertEquals(messenger.getOutgoingChannels(plugin3)); + } + + @Test + public void testGetIncomingChannels() { + Messenger messenger = getMessenger(); + TestPlugin plugin1 = getPlugin(); + TestPlugin plugin2 = getPlugin(); + + assertEquals(messenger.getIncomingChannels()); + + messenger.registerIncomingPluginChannel(plugin1, "foo", new TestMessageListener("foo", "bar".getBytes())); + messenger.registerIncomingPluginChannel(plugin1, "bar", new TestMessageListener("foo", "bar".getBytes())); + messenger.registerIncomingPluginChannel(plugin2, "baz", new TestMessageListener("foo", "bar".getBytes())); + messenger.registerIncomingPluginChannel(plugin2, "baz", new TestMessageListener("foo", "bar".getBytes())); + + assertEquals(messenger.getIncomingChannels(), "foo", "bar", "baz"); + } + + @Test + public void testGetIncomingChannels_Plugin() { + Messenger messenger = getMessenger(); + TestPlugin plugin1 = getPlugin(); + TestPlugin plugin2 = getPlugin(); + TestPlugin plugin3 = getPlugin(); + + messenger.registerIncomingPluginChannel(plugin1, "foo", new TestMessageListener("foo", "bar".getBytes())); + messenger.registerIncomingPluginChannel(plugin1, "bar", new TestMessageListener("foo", "bar".getBytes())); + messenger.registerIncomingPluginChannel(plugin2, "baz", new TestMessageListener("foo", "bar".getBytes())); + messenger.registerIncomingPluginChannel(plugin2, "qux", new TestMessageListener("foo", "bar".getBytes())); + + assertEquals(messenger.getIncomingChannels(plugin1), "foo", "bar"); + assertEquals(messenger.getIncomingChannels(plugin2), "baz", "qux"); + assertEquals(messenger.getIncomingChannels(plugin3)); + } + + @Test + public void testGetIncomingChannelRegistrations_Plugin() { + Messenger messenger = getMessenger(); + TestPlugin plugin1 = getPlugin(); + TestPlugin plugin2 = getPlugin(); + TestPlugin plugin3 = getPlugin(); + PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin1, "foo", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin1, "bar", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration3 = messenger.registerIncomingPluginChannel(plugin2, "baz", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration4 = messenger.registerIncomingPluginChannel(plugin2, "qux", new TestMessageListener("foo", "bar".getBytes())); + + assertEquals(messenger.getIncomingChannelRegistrations(plugin1), registration1, registration2); + assertEquals(messenger.getIncomingChannelRegistrations(plugin2), registration3, registration4); + assertEquals(messenger.getIncomingChannels(plugin3)); + } + + @Test + public void testGetIncomingChannelRegistrations_String() { + Messenger messenger = getMessenger(); + TestPlugin plugin1 = getPlugin(); + TestPlugin plugin2 = getPlugin(); + PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin1, "foo", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin1, "bar", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration3 = messenger.registerIncomingPluginChannel(plugin2, "foo", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration4 = messenger.registerIncomingPluginChannel(plugin2, "bar", new TestMessageListener("foo", "bar".getBytes())); + + assertEquals(messenger.getIncomingChannelRegistrations("foo"), registration1, registration3); + assertEquals(messenger.getIncomingChannelRegistrations("bar"), registration2, registration4); + assertEquals(messenger.getIncomingChannelRegistrations("baz")); + } + + @Test + public void testGetIncomingChannelRegistrations_Plugin_String() { + Messenger messenger = getMessenger(); + TestPlugin plugin1 = getPlugin(); + TestPlugin plugin2 = getPlugin(); + TestPlugin plugin3 = getPlugin(); + PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin1, "foo", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin1, "foo", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration3 = messenger.registerIncomingPluginChannel(plugin1, "bar", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration4 = messenger.registerIncomingPluginChannel(plugin2, "bar", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration5 = messenger.registerIncomingPluginChannel(plugin2, "baz", new TestMessageListener("foo", "bar".getBytes())); + PluginMessageListenerRegistration registration6 = messenger.registerIncomingPluginChannel(plugin2, "baz", new TestMessageListener("foo", "bar".getBytes())); + + assertEquals(messenger.getIncomingChannelRegistrations(plugin1, "foo"), registration1, registration2); + assertEquals(messenger.getIncomingChannelRegistrations(plugin1, "bar"), registration3); + assertEquals(messenger.getIncomingChannelRegistrations(plugin2, "bar"), registration4); + assertEquals(messenger.getIncomingChannelRegistrations(plugin2, "baz"), registration5, registration6); + assertEquals(messenger.getIncomingChannelRegistrations(plugin1, "baz")); + assertEquals(messenger.getIncomingChannelRegistrations(plugin3, "qux")); + } + + private static void assertEquals(Collection actual, T... expected) { + assertThat("Size of the array", actual.size(), is(expected.length)); + assertThat(actual, hasItems(expected)); + } +} diff --git a/src/test/java/org/bukkit/plugin/messaging/TestMessageListener.java b/src/test/java/org/bukkit/plugin/messaging/TestMessageListener.java new file mode 100644 index 0000000..98860ec --- /dev/null +++ b/src/test/java/org/bukkit/plugin/messaging/TestMessageListener.java @@ -0,0 +1,29 @@ +package org.bukkit.plugin.messaging; + +import org.bukkit.entity.Player; +import static org.junit.Assert.*; + +public class TestMessageListener implements PluginMessageListener { + private final String channel; + private final byte[] message; + private boolean received = false; + + public TestMessageListener(String channel, byte[] message) { + this.channel = channel; + this.message = message; + } + + public void onPluginMessageReceived(String channel, Player player, byte[] message) { + assertEquals(this.channel, channel); + assertArrayEquals(this.message, message); + this.received = true; + } + + public boolean hasReceived() { + return received; + } + + public void reset() { + received = false; + } +} diff --git a/src/test/java/org/bukkit/plugin/messaging/TestPlayer.java b/src/test/java/org/bukkit/plugin/messaging/TestPlayer.java new file mode 100644 index 0000000..71f59c5 --- /dev/null +++ b/src/test/java/org/bukkit/plugin/messaging/TestPlayer.java @@ -0,0 +1,50 @@ +package org.bukkit.plugin.messaging; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; + +import org.bukkit.entity.Player; + + +public class TestPlayer implements InvocationHandler { + private static interface MethodHandler { + Object handle(TestPlayer server, Object[] args); + } + private static final Constructor constructor; + private static final HashMap methods = new HashMap(); + static { + try { + /* + methods.put(Player.class.getMethod("methodName"), + new MethodHandler() { + public Object handle(TestPlayer server, Object[] args) { + } + }); + */ + constructor = Proxy.getProxyClass(Player.class.getClassLoader(), Player.class).asSubclass(Player.class).getConstructor(InvocationHandler.class); + } catch (Throwable t) { + throw new Error(t); + } + } + + private TestPlayer() {}; + + public static Player getInstance() { + try { + return constructor.newInstance(new TestPlayer()); + } catch (Throwable t) { + throw new RuntimeException(t); + } + } + + public Object invoke(Object proxy, Method method, Object[] args) { + MethodHandler handler = methods.get(method); + if (handler != null) { + return handler.handle(this, args); + } + throw new UnsupportedOperationException(String.valueOf(method)); + } +} diff --git a/src/test/java/org/bukkit/potion/PotionTest.java b/src/test/java/org/bukkit/potion/PotionTest.java new file mode 100644 index 0000000..58252ae --- /dev/null +++ b/src/test/java/org/bukkit/potion/PotionTest.java @@ -0,0 +1,148 @@ +package org.bukkit.potion; + +import static org.junit.Assert.*; +import static org.hamcrest.Matchers.is; + +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.ItemStack; +import org.junit.Test; + +public class PotionTest { + @Test + public void applyToItemStack() { + Potion potion = new Potion(PotionType.POISON); + ItemStack stack = new ItemStack(Material.POTION, 1); + potion.apply(stack); + assertTrue(stack.getDurability() == potion.toDamageValue()); + } + + @Test + public void fromDamage() { + Potion potion = Potion.fromDamage(PotionType.POISON.getDamageValue()); + assertTrue(potion.getType() == PotionType.POISON); + potion = Potion.fromDamage(PotionType.POISON.getDamageValue() | SPLASH_BIT); + assertTrue(potion.getType() == PotionType.POISON && potion.isSplash()); + potion = Potion.fromDamage(0x25 /* Potion of Healing II */); + assertTrue(potion.getType() == PotionType.INSTANT_HEAL && potion.getLevel() == 2); + } + + @Test(expected = IllegalArgumentException.class) + public void illegalApplyToItemStack() { + Potion potion = new Potion(PotionType.POISON); + potion.apply(new ItemStack(Material.AIR, 1)); + } + + @Test + public void ItemStackConversion() { + Potion potion = new Potion(PotionType.POISON); + ItemStack itemstack = potion.toItemStack(1); + assertThat(itemstack.getType(), is(Material.POTION)); + assertTrue(itemstack.getAmount() == 1); + assertTrue(itemstack.getDurability() == potion.toDamageValue()); + } + + @Test + public void setExtended() { + PotionEffectType.registerPotionEffectType(new PotionEffectType(19){ + @Override + public double getDurationModifier() { + return 1; + } + + @Override + public String getName() { + return "Poison"; + } + + @Override + public boolean isInstant() { + return false; + } + }); + Potion potion = new Potion(PotionType.POISON); + assertFalse(potion.hasExtendedDuration()); + potion.setHasExtendedDuration(true); + assertTrue(potion.hasExtendedDuration()); + assertTrue((potion.toDamageValue() & EXTENDED_BIT) != 0); + } + + @Test + public void setSplash() { + Potion potion = new Potion(PotionType.POISON); + assertFalse(potion.isSplash()); + potion.setSplash(true); + assertTrue(potion.isSplash()); + assertTrue((potion.toDamageValue() & SPLASH_BIT) != 0); + } + + @Test + public void setLevel() { + Potion potion = new Potion(PotionType.POISON); + assertEquals(1, potion.getLevel()); + potion.setLevel(2); + assertEquals(2, potion.getLevel()); + assertTrue((potion.toDamageValue() & 0x3F) == (PotionType.POISON.getDamageValue() | 0x20)); + } + + @Test(expected=IllegalArgumentException.class) + public void nullType() { + new Potion(null, 2); + } + + @Test(expected=IllegalArgumentException.class) + public void maxLevelConstruct() { + new Potion(PotionType.POISON, 3); + } + + @Test(expected=IllegalArgumentException.class) + public void maxLevelSet() { + Potion potion = new Potion(PotionType.POISON); + potion.setLevel(3); + } + + @Test(expected=IllegalArgumentException.class) + public void nullStack() { + Potion potion = new Potion(PotionType.POISON); + potion.apply((ItemStack) null); + } + + @Test(expected=IllegalArgumentException.class) + public void nullEntity() { + Potion potion = new Potion(PotionType.POISON); + potion.apply((LivingEntity) null); + } + + @Test + public void water() { + Potion potion = new Potion(PotionType.WATER); + assertEquals(0, potion.getLevel()); + assertFalse(potion.isSplash()); + assertFalse(potion.hasExtendedDuration()); + assertEquals(0, potion.toDamageValue()); + } + + @Test + public void mundane() { + Potion potion = new Potion(0); + assertFalse(potion.getType() == PotionType.WATER); + assertFalse(potion.toDamageValue() == 0); + assertEquals(8192, potion.toDamageValue()); + Potion potion2 = Potion.fromDamage(8192); + assertEquals(potion, potion2); + assertEquals(0, potion.getLevel()); + } + + @Test + public void awkward() { + Potion potion = new Potion(16); + assertEquals(16, potion.getNameId()); + assertFalse(potion.isSplash()); + assertFalse(potion.hasExtendedDuration()); + assertNull(potion.getType()); + assertEquals(16, potion.toDamageValue()); + } + + private static final int EXTENDED_BIT = 0x40; + private static final int SPLASH_BIT = 0x4000; +} diff --git a/src/test/java/org/bukkit/util/StringUtilStartsWithTest.java b/src/test/java/org/bukkit/util/StringUtilStartsWithTest.java new file mode 100644 index 0000000..b85a2b2 --- /dev/null +++ b/src/test/java/org/bukkit/util/StringUtilStartsWithTest.java @@ -0,0 +1,86 @@ +package org.bukkit.util; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import com.google.common.collect.ImmutableList; + +@RunWith(Parameterized.class) +public class StringUtilStartsWithTest { + + @Parameters(name= "{index}: {0} startsWith {1} == {2}") + public static List data() { + return ImmutableList.of( + new Object[] { + "Apple", + "Apples", + false + }, + new Object[] { + "Apples", + "Apple", + true + }, + new Object[] { + "Apple", + "Apple", + true + }, + new Object[] { + "Apple", + "apples", + false + }, + new Object[] { + "apple", + "Apples", + false + }, + new Object[] { + "apple", + "apples", + false + }, + new Object[] { + "Apples", + "apPL", + true + }, + new Object[] { + "123456789", + "1234567", + true + }, + new Object[] { + "", + "", + true + }, + new Object[] { + "string", + "", + true + } + ); + } + + @Parameter(0) + public String base; + @Parameter(1) + public String prefix; + @Parameter(2) + public boolean result; + + @Test + public void testFor() { + assertThat(base + " starts with " + prefix + ": " + result, StringUtil.startsWithIgnoreCase(base, prefix), is(result)); + } +} diff --git a/src/test/java/org/bukkit/util/StringUtilTest.java b/src/test/java/org/bukkit/util/StringUtilTest.java new file mode 100644 index 0000000..9c8444c --- /dev/null +++ b/src/test/java/org/bukkit/util/StringUtilTest.java @@ -0,0 +1,61 @@ +package org.bukkit.util; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import com.google.common.collect.ImmutableList; + +public class StringUtilTest { + + @Test(expected=NullPointerException.class) + public void nullPrefixTest() { + StringUtil.startsWithIgnoreCase("String", null); + } + + @Test(expected=IllegalArgumentException.class) + public void nullStringTest() { + StringUtil.startsWithIgnoreCase(null, "String"); + } + + @Test(expected=IllegalArgumentException.class) + public void nullCollectionTest() { + StringUtil.copyPartialMatches("Token", ImmutableList.of(), null); + } + + @Test(expected=IllegalArgumentException.class) + public void nullIterableTest() { + StringUtil.copyPartialMatches("Token", null, new ArrayList()); + } + + @Test(expected=IllegalArgumentException.class) + public void nullTokenTest() { + StringUtil.copyPartialMatches(null, ImmutableList.of(), new ArrayList()); + } + + @Test + public void copyTokenTest() { + String token = "ab"; + Iterable original = ImmutableList.of("ab12", "aC561", "AB5195", "Ab76", "", "a"); + List expected = ImmutableList.of("ab12", "AB5195", "Ab76" ); + List list = new ArrayList(); + assertThat(StringUtil.copyPartialMatches(token, original, list), is(expected)); + assertThat(StringUtil.copyPartialMatches(token, original, list), is(sameInstance(list))); + assertThat(list.size(), is(expected.size() * 2)); + } + + @Test(expected=UnsupportedOperationException.class) + public void copyUnsupportedTest() { + StringUtil.copyPartialMatches("token", ImmutableList.of("token1", "token2"), ImmutableList.of()); + } + + @Test(expected=IllegalArgumentException.class) + public void copyNullTest() { + StringUtil.copyPartialMatches("token", Arrays.asList("token1", "token2", null), new ArrayList()); + } +} diff --git a/src/test/java/org/bukkit/util/io/BukkitObjectStreamTest.java b/src/test/java/org/bukkit/util/io/BukkitObjectStreamTest.java new file mode 100644 index 0000000..d0af4a0 --- /dev/null +++ b/src/test/java/org/bukkit/util/io/BukkitObjectStreamTest.java @@ -0,0 +1,173 @@ +package org.bukkit.util.io; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; + +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.FireworkEffect.Type; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.util.Vector; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import com.google.common.collect.ImmutableList; + +@RunWith(Parameterized.class) +public class BukkitObjectStreamTest { + + @Parameters(name= "{index}: {0}") + public static List data() { + return ImmutableList.of( + new Object[] { + Color.class.getName(), + "rO0ABXNyADZjb20uZ29vZ2xlLmNvbW1vbi5jb2xsZWN0LkltbXV0YWJsZUxpc3QkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAVsACGVsZW1lbnRzdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwdXIAE1tMamF2YS5sYW5nLk9iamVjdDuQzlifEHMpbAIAAHhwAAAABXNyABpvcmcuYnVra2l0LnV0aWwuaW8uV3JhcHBlcvJQR+zxEm8FAgABTAADbWFwdAAPTGphdmEvdXRpbC9NYXA7eHBzcgA1Y29tLmdvb2dsZS5jb21tb24uY29sbGVjdC5JbW11dGFibGVNYXAkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAlsABGtleXNxAH4AAVsABnZhbHVlc3EAfgABeHB1cQB+AAMAAAAEdAACPT10AANSRUR0AARCTFVFdAAFR1JFRU51cQB+AAMAAAAEdAAFQ29sb3JzcgARamF2YS5sYW5nLkludGVnZXIS4qCk94GHOAIAAUkABXZhbHVleHIAEGphdmEubGFuZy5OdW1iZXKGrJUdC5TgiwIAAHhwAAAA/3NxAH4AEQAAAP9zcQB+ABEAAAD/c3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARAAAAAHNxAH4AEQAAAIBzcQB+ABEAAACAc3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARAAAAgHNxAH4AEQAAAIBxAH4AGnNxAH4ABXNxAH4ACHVxAH4AAwAAAARxAH4AC3EAfgAMcQB+AA1xAH4ADnVxAH4AAwAAAARxAH4AEHNxAH4AEQAAAP9xAH4AGnEAfgAac3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARAAAA/3EAfgAac3EAfgARAAAApQ==", + ImmutableList.of( + Color.WHITE, + Color.TEAL, + Color.PURPLE, + Color.RED, + Color.ORANGE + ) + }, + new Object[] { + FireworkEffect.class.getName(), + "rO0ABXNyADZjb20uZ29vZ2xlLmNvbW1vbi5jb2xsZWN0LkltbXV0YWJsZUxpc3QkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAVsACGVsZW1lbnRzdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwdXIAE1tMamF2YS5sYW5nLk9iamVjdDuQzlifEHMpbAIAAHhwAAAAA3NyABpvcmcuYnVra2l0LnV0aWwuaW8uV3JhcHBlcvJQR+zxEm8FAgABTAADbWFwdAAPTGphdmEvdXRpbC9NYXA7eHBzcgA1Y29tLmdvb2dsZS5jb21tb24uY29sbGVjdC5JbW11dGFibGVNYXAkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAlsABGtleXNxAH4AAVsABnZhbHVlc3EAfgABeHB1cQB+AAMAAAAGdAACPT10AAdmbGlja2VydAAFdHJhaWx0AAZjb2xvcnN0AAtmYWRlLWNvbG9yc3QABHR5cGV1cQB+AAMAAAAGdAAIRmlyZXdvcmtzcgARamF2YS5sYW5nLkJvb2xlYW7NIHKA1Zz67gIAAVoABXZhbHVleHABc3EAfgATAHNxAH4AAHVxAH4AAwAAAAJzcQB+AAVzcQB+AAh1cQB+AAMAAAAEcQB+AAt0AANSRUR0AARCTFVFdAAFR1JFRU51cQB+AAMAAAAEdAAFQ29sb3JzcgARamF2YS5sYW5nLkludGVnZXIS4qCk94GHOAIAAUkABXZhbHVleHIAEGphdmEubGFuZy5OdW1iZXKGrJUdC5TgiwIAAHhwAAAAAHEAfgAicQB+ACJzcQB+AAVzcQB+AAh1cQB+AAMAAAAEcQB+AAtxAH4AG3EAfgAccQB+AB11cQB+AAMAAAAEcQB+AB9zcQB+ACAAAADAc3EAfgAgAAAAwHNxAH4AIAAAAMBzcQB+AAB1cQB+AAMAAAABc3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+ABtxAH4AHHEAfgAddXEAfgADAAAABHEAfgAfc3EAfgAgAAAA/3NxAH4AIAAAAP9zcQB+ACAAAAD/dAAKQkFMTF9MQVJHRXNxAH4ABXNxAH4ACHVxAH4AAwAAAAZxAH4AC3EAfgAMcQB+AA1xAH4ADnEAfgAPcQB+ABB1cQB+AAMAAAAGcQB+ABJxAH4AFXEAfgAVc3EAfgAAdXEAfgADAAAAAXNxAH4ABXNxAH4ACHVxAH4AAwAAAARxAH4AC3EAfgAbcQB+ABxxAH4AHXVxAH4AAwAAAARxAH4AH3EAfgAic3EAfgAgAAAAgHEAfgAic3EAfgAAdXEAfgADAAAAAHQABEJBTExzcQB+AAVzcQB+AAh1cQB+AAMAAAAGcQB+AAtxAH4ADHEAfgANcQB+AA5xAH4AD3EAfgAQdXEAfgADAAAABnEAfgAScQB+ABRxAH4AFHNxAH4AAHVxAH4AAwAAAAFzcQB+AAVzcQB+AAh1cQB+AAMAAAAEcQB+AAtxAH4AG3EAfgAccQB+AB11cQB+AAMAAAAEcQB+AB9zcQB+ACAAAACAcQB+ACJxAH4AInEAfgA/dAAHQ1JFRVBFUg==", + ImmutableList.of( + FireworkEffect.builder() + .withColor(Color.BLACK, Color.SILVER) + .with(Type.BALL_LARGE) + .withFade(Color.WHITE) + .withFlicker() + .build(), + FireworkEffect.builder() + .withColor(Color.NAVY) + .build(), + FireworkEffect.builder() + .withColor(Color.MAROON) + .withTrail() + .withFlicker() + .with(Type.CREEPER) + .build() + ), + }, + new Object[] { + Vector.class.getName(), + "rO0ABXNyADZjb20uZ29vZ2xlLmNvbW1vbi5jb2xsZWN0LkltbXV0YWJsZUxpc3QkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAVsACGVsZW1lbnRzdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwdXIAE1tMamF2YS5sYW5nLk9iamVjdDuQzlifEHMpbAIAAHhwAAAABHNyABpvcmcuYnVra2l0LnV0aWwuaW8uV3JhcHBlcvJQR+zxEm8FAgABTAADbWFwdAAPTGphdmEvdXRpbC9NYXA7eHBzcgA1Y29tLmdvb2dsZS5jb21tb24uY29sbGVjdC5JbW11dGFibGVNYXAkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAlsABGtleXNxAH4AAVsABnZhbHVlc3EAfgABeHB1cQB+AAMAAAAEdAACPT10AAF4dAABeXQAAXp1cQB+AAMAAAAEdAAGVmVjdG9yc3IAEGphdmEubGFuZy5Eb3VibGWAs8JKKWv7BAIAAUQABXZhbHVleHIAEGphdmEubGFuZy5OdW1iZXKGrJUdC5TgiwIAAHhwAAAAAAAAAABzcQB+ABEAAAAAAAAAAHNxAH4AEQAAAAAAAAAAc3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARQIOFwo9cKPZzcQB+ABFAtCKcKPXCj3NxAH4AEUBzrpeNT987c3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARwEQTMzMzMzNzcQB+ABFASYAAAAAAAHNxAH4AEcCjqG3UQTVUc3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARQd/////AAABzcQB+ABHB4AAAAAAAAHNxAH4AEQAAAAAAAAAA", + ImmutableList.of( + new Vector(0, 0, 0), + new Vector(624.72, 5154.61, 314.912), + new Vector(-40.15, 51, -2516.21451), + new Vector(Integer.MAX_VALUE, Integer.MIN_VALUE, 0) + ) + }); + } + + @Parameter(0) + public String className; + + @Parameter(1) + public String preEncoded; + + @Parameter(2) + public List object; + + @Test + public void checkSerlialization() throws Throwable { + // If this test fails, you may start your trek to debug by commenting the '@Ignore' on the next method + // (and of course, you would read those comments too) + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oos = null; + try { + oos = new BukkitObjectOutputStream(out); + oos.writeObject(object); + } finally { + if (oos != null) { + try { + oos.close(); + } catch (IOException e) { + } + } + } + + final byte[] preEncodedArray = Base64Coder.decode(preEncoded); + + final Object readBack; + final Object preEncoded; + + ObjectInputStream ois = null; + ObjectInputStream preois = null; + try { + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + ByteArrayInputStream preIn = new ByteArrayInputStream(preEncodedArray); + ois = new BukkitObjectInputStream(in); + preois = new BukkitObjectInputStream(preIn); + + readBack = ois.readObject(); + preEncoded = preois.readObject(); + } finally { + if (ois != null) { + try { + ois.close(); + } catch (IOException ex) { + } + } + if (preois != null) { + try { + preois.close(); + } catch (IOException ex) { + } + } + } + + assertThat(object, is(readBack)); + assertThat(object, is(preEncoded)); + } + + @Ignore + @Test + public void preEncoded() throws Throwable { + // This test is placed in the case that a necessary change is made to change the encoding format + // Just remove the ignore (or run manually) and it'll give you the new pre-encoded values + + // It really does not matter if the encoded array is different per system (hence why this test is set to not run), + // as long as all systems can deserialize it. + + // The entire reason the pre-encoded string was added is to make a build (test) fail if someone accidentally makes it not backward-compatible + + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oos = null; + try { + oos = new BukkitObjectOutputStream(out); + oos.writeObject(object); + oos.flush(); + } finally { + if (oos != null) { + try { + oos.close(); + } catch (IOException e) { + } + } + } + + final String string = new String(Base64Coder.encode(out.toByteArray())); + try { + assertThat(preEncoded, is(string)); + } catch (Throwable t) { + System.out.println(className + ": \"" + string + "\""); + throw t; + } + } +}